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 visitMGATHER(SDNode *N);
311 SDValue visitMSCATTER(SDNode *N);
312 SDValue visitFP_TO_FP16(SDNode *N);
314 SDValue visitFADDForFMACombine(SDNode *N);
315 SDValue visitFSUBForFMACombine(SDNode *N);
317 SDValue XformToShuffleWithZero(SDNode *N);
318 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
320 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
322 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
323 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
324 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
325 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
326 SDValue N3, ISD::CondCode CC,
327 bool NotExtCompare = false);
328 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
329 SDLoc DL, bool foldBooleans = true);
331 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
333 bool isOneUseSetCC(SDValue N) const;
335 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
337 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
338 SDValue CombineExtLoad(SDNode *N);
339 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
340 SDValue BuildSDIV(SDNode *N);
341 SDValue BuildSDIVPow2(SDNode *N);
342 SDValue BuildUDIV(SDNode *N);
343 SDValue BuildReciprocalEstimate(SDValue Op);
344 SDValue BuildRsqrtEstimate(SDValue Op);
345 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
346 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
347 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
348 bool DemandHighBits = true);
349 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
350 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
351 SDValue InnerPos, SDValue InnerNeg,
352 unsigned PosOpcode, unsigned NegOpcode,
354 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
355 SDValue ReduceLoadWidth(SDNode *N);
356 SDValue ReduceLoadOpStoreWidth(SDNode *N);
357 SDValue TransformFPLoadStorePair(SDNode *N);
358 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
359 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
361 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
363 /// Walk up chain skipping non-aliasing memory nodes,
364 /// looking for aliasing nodes and adding them to the Aliases vector.
365 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
366 SmallVectorImpl<SDValue> &Aliases);
368 /// Return true if there is any possibility that the two addresses overlap.
369 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
371 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
372 /// chain (aliasing node.)
373 SDValue FindBetterChain(SDNode *N, SDValue Chain);
375 /// Holds a pointer to an LSBaseSDNode as well as information on where it
376 /// is located in a sequence of memory operations connected by a chain.
378 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
379 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
380 // Ptr to the mem node.
381 LSBaseSDNode *MemNode;
382 // Offset from the base ptr.
383 int64_t OffsetFromBase;
384 // What is the sequence number of this mem node.
385 // Lowest mem operand in the DAG starts at zero.
386 unsigned SequenceNum;
389 /// This is a helper function for MergeConsecutiveStores. When the source
390 /// elements of the consecutive stores are all constants or all extracted
391 /// vector elements, try to merge them into one larger store.
392 /// \return True if a merged store was created.
393 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
394 EVT MemVT, unsigned NumElem,
395 bool IsConstantSrc, bool UseVector);
397 /// Merge consecutive store operations into a wide store.
398 /// This optimization uses wide integers or vectors when possible.
399 /// \return True if some memory operations were changed.
400 bool MergeConsecutiveStores(StoreSDNode *N);
402 /// \brief Try to transform a truncation where C is a constant:
403 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
405 /// \p N needs to be a truncation and its first operand an AND. Other
406 /// requirements are checked by the function (e.g. that trunc is
407 /// single-use) and if missed an empty SDValue is returned.
408 SDValue distributeTruncateThroughAnd(SDNode *N);
411 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
412 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
413 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
414 auto *F = DAG.getMachineFunction().getFunction();
415 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
416 F->hasFnAttribute(Attribute::MinSize);
419 /// Runs the dag combiner on all nodes in the work list
420 void Run(CombineLevel AtLevel);
422 SelectionDAG &getDAG() const { return DAG; }
424 /// Returns a type large enough to hold any valid shift amount - before type
425 /// legalization these can be huge.
426 EVT getShiftAmountTy(EVT LHSTy) {
427 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
428 if (LHSTy.isVector())
430 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
431 : TLI.getPointerTy();
434 /// This method returns true if we are running before type legalization or
435 /// if the specified VT is legal.
436 bool isTypeLegal(const EVT &VT) {
437 if (!LegalTypes) return true;
438 return TLI.isTypeLegal(VT);
441 /// Convenience wrapper around TargetLowering::getSetCCResultType
442 EVT getSetCCResultType(EVT VT) const {
443 return TLI.getSetCCResultType(*DAG.getContext(), VT);
450 /// This class is a DAGUpdateListener that removes any deleted
451 /// nodes from the worklist.
452 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
455 explicit WorklistRemover(DAGCombiner &dc)
456 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
458 void NodeDeleted(SDNode *N, SDNode *E) override {
459 DC.removeFromWorklist(N);
464 //===----------------------------------------------------------------------===//
465 // TargetLowering::DAGCombinerInfo implementation
466 //===----------------------------------------------------------------------===//
468 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
469 ((DAGCombiner*)DC)->AddToWorklist(N);
472 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
473 ((DAGCombiner*)DC)->removeFromWorklist(N);
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
478 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
483 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
487 SDValue TargetLowering::DAGCombinerInfo::
488 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
489 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
492 void TargetLowering::DAGCombinerInfo::
493 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
494 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
497 //===----------------------------------------------------------------------===//
499 //===----------------------------------------------------------------------===//
501 void DAGCombiner::deleteAndRecombine(SDNode *N) {
502 removeFromWorklist(N);
504 // If the operands of this node are only used by the node, they will now be
505 // dead. Make sure to re-visit them and recursively delete dead nodes.
506 for (const SDValue &Op : N->ops())
507 // For an operand generating multiple values, one of the values may
508 // become dead allowing further simplification (e.g. split index
509 // arithmetic from an indexed load).
510 if (Op->hasOneUse() || Op->getNumValues() > 1)
511 AddToWorklist(Op.getNode());
516 /// Return 1 if we can compute the negated form of the specified expression for
517 /// the same cost as the expression itself, or 2 if we can compute the negated
518 /// form more cheaply than the expression itself.
519 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
520 const TargetLowering &TLI,
521 const TargetOptions *Options,
522 unsigned Depth = 0) {
523 // fneg is removable even if it has multiple uses.
524 if (Op.getOpcode() == ISD::FNEG) return 2;
526 // Don't allow anything with multiple uses.
527 if (!Op.hasOneUse()) return 0;
529 // Don't recurse exponentially.
530 if (Depth > 6) return 0;
532 switch (Op.getOpcode()) {
533 default: return false;
534 case ISD::ConstantFP:
535 // Don't invert constant FP values after legalize. The negated constant
536 // isn't necessarily legal.
537 return LegalOperations ? 0 : 1;
539 // FIXME: determine better conditions for this xform.
540 if (!Options->UnsafeFPMath) return 0;
542 // After operation legalization, it might not be legal to create new FSUBs.
543 if (LegalOperations &&
544 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
547 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
548 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
551 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
552 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
555 // We can't turn -(A-B) into B-A when we honor signed zeros.
556 if (!Options->UnsafeFPMath) return 0;
558 // fold (fneg (fsub A, B)) -> (fsub B, A)
563 if (Options->HonorSignDependentRoundingFPMath()) return 0;
565 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
566 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
570 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
576 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
581 /// If isNegatibleForFree returns true, return the newly negated expression.
582 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
583 bool LegalOperations, unsigned Depth = 0) {
584 const TargetOptions &Options = DAG.getTarget().Options;
585 // fneg is removable even if it has multiple uses.
586 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
588 // Don't allow anything with multiple uses.
589 assert(Op.hasOneUse() && "Unknown reuse!");
591 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
592 switch (Op.getOpcode()) {
593 default: llvm_unreachable("Unknown code");
594 case ISD::ConstantFP: {
595 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
597 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
600 // FIXME: determine better conditions for this xform.
601 assert(Options.UnsafeFPMath);
603 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
604 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
605 DAG.getTargetLoweringInfo(), &Options, Depth+1))
606 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607 GetNegatedExpression(Op.getOperand(0), DAG,
608 LegalOperations, Depth+1),
610 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
611 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
612 GetNegatedExpression(Op.getOperand(1), DAG,
613 LegalOperations, Depth+1),
616 // We can't turn -(A-B) into B-A when we honor signed zeros.
617 assert(Options.UnsafeFPMath);
619 // fold (fneg (fsub 0, B)) -> B
620 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
621 if (N0CFP->getValueAPF().isZero())
622 return Op.getOperand(1);
624 // fold (fneg (fsub A, B)) -> (fsub B, A)
625 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
626 Op.getOperand(1), Op.getOperand(0));
630 assert(!Options.HonorSignDependentRoundingFPMath());
632 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
633 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
634 DAG.getTargetLoweringInfo(), &Options, Depth+1))
635 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
636 GetNegatedExpression(Op.getOperand(0), DAG,
637 LegalOperations, Depth+1),
640 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
641 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
643 GetNegatedExpression(Op.getOperand(1), DAG,
644 LegalOperations, Depth+1));
648 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
649 GetNegatedExpression(Op.getOperand(0), DAG,
650 LegalOperations, Depth+1));
652 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
653 GetNegatedExpression(Op.getOperand(0), DAG,
654 LegalOperations, Depth+1),
659 // Return true if this node is a setcc, or is a select_cc
660 // that selects between the target values used for true and false, making it
661 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
662 // the appropriate nodes based on the type of node we are checking. This
663 // simplifies life a bit for the callers.
664 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
666 if (N.getOpcode() == ISD::SETCC) {
667 LHS = N.getOperand(0);
668 RHS = N.getOperand(1);
669 CC = N.getOperand(2);
673 if (N.getOpcode() != ISD::SELECT_CC ||
674 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
675 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
678 if (TLI.getBooleanContents(N.getValueType()) ==
679 TargetLowering::UndefinedBooleanContent)
682 LHS = N.getOperand(0);
683 RHS = N.getOperand(1);
684 CC = N.getOperand(4);
688 /// Return true if this is a SetCC-equivalent operation with only one use.
689 /// If this is true, it allows the users to invert the operation for free when
690 /// it is profitable to do so.
691 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
693 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
698 /// Returns true if N is a BUILD_VECTOR node whose
699 /// elements are all the same constant or undefined.
700 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
701 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
706 unsigned SplatBitSize;
708 EVT EltVT = N->getValueType(0).getVectorElementType();
709 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
711 EltVT.getSizeInBits() >= SplatBitSize);
714 // \brief Returns the SDNode if it is a constant integer BuildVector
715 // or constant integer.
716 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
717 if (isa<ConstantSDNode>(N))
719 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
724 // \brief Returns the SDNode if it is a constant float BuildVector
725 // or constant float.
726 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
727 if (isa<ConstantFPSDNode>(N))
729 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
734 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
736 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
737 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
740 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
741 BitVector UndefElements;
742 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
744 // BuildVectors can truncate their operands. Ignore that case here.
745 // FIXME: We blindly ignore splats which include undef which is overly
747 if (CN && UndefElements.none() &&
748 CN->getValueType(0) == N.getValueType().getScalarType())
755 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
757 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
758 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
761 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
762 BitVector UndefElements;
763 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
765 if (CN && UndefElements.none())
772 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
773 SDValue N0, SDValue N1) {
774 EVT VT = N0.getValueType();
775 if (N0.getOpcode() == Opc) {
776 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
777 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
778 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
779 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
780 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
783 if (N0.hasOneUse()) {
784 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
786 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
787 if (!OpNode.getNode())
789 AddToWorklist(OpNode.getNode());
790 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
795 if (N1.getOpcode() == Opc) {
796 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
797 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
798 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
799 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
800 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
803 if (N1.hasOneUse()) {
804 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
806 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
807 if (!OpNode.getNode())
809 AddToWorklist(OpNode.getNode());
810 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
818 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
820 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
822 DEBUG(dbgs() << "\nReplacing.1 ";
824 dbgs() << "\nWith: ";
825 To[0].getNode()->dump(&DAG);
826 dbgs() << " and " << NumTo-1 << " other values\n");
827 for (unsigned i = 0, e = NumTo; i != e; ++i)
828 assert((!To[i].getNode() ||
829 N->getValueType(i) == To[i].getValueType()) &&
830 "Cannot combine value to value of different type!");
832 WorklistRemover DeadNodes(*this);
833 DAG.ReplaceAllUsesWith(N, To);
835 // Push the new nodes and any users onto the worklist
836 for (unsigned i = 0, e = NumTo; i != e; ++i) {
837 if (To[i].getNode()) {
838 AddToWorklist(To[i].getNode());
839 AddUsersToWorklist(To[i].getNode());
844 // Finally, if the node is now dead, remove it from the graph. The node
845 // may not be dead if the replacement process recursively simplified to
846 // something else needing this node.
848 deleteAndRecombine(N);
849 return SDValue(N, 0);
853 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
854 // Replace all uses. If any nodes become isomorphic to other nodes and
855 // are deleted, make sure to remove them from our worklist.
856 WorklistRemover DeadNodes(*this);
857 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
859 // Push the new node and any (possibly new) users onto the worklist.
860 AddToWorklist(TLO.New.getNode());
861 AddUsersToWorklist(TLO.New.getNode());
863 // Finally, if the node is now dead, remove it from the graph. The node
864 // may not be dead if the replacement process recursively simplified to
865 // something else needing this node.
866 if (TLO.Old.getNode()->use_empty())
867 deleteAndRecombine(TLO.Old.getNode());
870 /// Check the specified integer node value to see if it can be simplified or if
871 /// things it uses can be simplified by bit propagation. If so, return true.
872 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
873 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
874 APInt KnownZero, KnownOne;
875 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
879 AddToWorklist(Op.getNode());
881 // Replace the old value with the new one.
883 DEBUG(dbgs() << "\nReplacing.2 ";
884 TLO.Old.getNode()->dump(&DAG);
885 dbgs() << "\nWith: ";
886 TLO.New.getNode()->dump(&DAG);
889 CommitTargetLoweringOpt(TLO);
893 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
895 EVT VT = Load->getValueType(0);
896 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
898 DEBUG(dbgs() << "\nReplacing.9 ";
900 dbgs() << "\nWith: ";
901 Trunc.getNode()->dump(&DAG);
903 WorklistRemover DeadNodes(*this);
904 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
905 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
906 deleteAndRecombine(Load);
907 AddToWorklist(Trunc.getNode());
910 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
913 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
914 EVT MemVT = LD->getMemoryVT();
915 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
916 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
918 : LD->getExtensionType();
920 return DAG.getExtLoad(ExtType, dl, PVT,
921 LD->getChain(), LD->getBasePtr(),
922 MemVT, LD->getMemOperand());
925 unsigned Opc = Op.getOpcode();
928 case ISD::AssertSext:
929 return DAG.getNode(ISD::AssertSext, dl, PVT,
930 SExtPromoteOperand(Op.getOperand(0), PVT),
932 case ISD::AssertZext:
933 return DAG.getNode(ISD::AssertZext, dl, PVT,
934 ZExtPromoteOperand(Op.getOperand(0), PVT),
936 case ISD::Constant: {
938 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
939 return DAG.getNode(ExtOpc, dl, PVT, Op);
943 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
945 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
948 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
949 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
951 EVT OldVT = Op.getValueType();
953 bool Replace = false;
954 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955 if (!NewOp.getNode())
957 AddToWorklist(NewOp.getNode());
960 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
962 DAG.getValueType(OldVT));
965 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
966 EVT OldVT = Op.getValueType();
968 bool Replace = false;
969 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
970 if (!NewOp.getNode())
972 AddToWorklist(NewOp.getNode());
975 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
976 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
979 /// Promote the specified integer binary operation if the target indicates it is
980 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
981 /// i32 since i16 instructions are longer.
982 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
983 if (!LegalOperations)
986 EVT VT = Op.getValueType();
987 if (VT.isVector() || !VT.isInteger())
990 // If operation type is 'undesirable', e.g. i16 on x86, consider
992 unsigned Opc = Op.getOpcode();
993 if (TLI.isTypeDesirableForOp(Opc, VT))
997 // Consult target whether it is a good idea to promote this operation and
998 // what's the right type to promote it to.
999 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1000 assert(PVT != VT && "Don't know what type to promote to!");
1002 bool Replace0 = false;
1003 SDValue N0 = Op.getOperand(0);
1004 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1008 bool Replace1 = false;
1009 SDValue N1 = Op.getOperand(1);
1014 NN1 = PromoteOperand(N1, PVT, Replace1);
1019 AddToWorklist(NN0.getNode());
1021 AddToWorklist(NN1.getNode());
1024 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1026 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1028 DEBUG(dbgs() << "\nPromoting ";
1029 Op.getNode()->dump(&DAG));
1031 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1032 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1037 /// Promote the specified integer shift operation if the target indicates it is
1038 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1039 /// i32 since i16 instructions are longer.
1040 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1041 if (!LegalOperations)
1044 EVT VT = Op.getValueType();
1045 if (VT.isVector() || !VT.isInteger())
1048 // If operation type is 'undesirable', e.g. i16 on x86, consider
1050 unsigned Opc = Op.getOpcode();
1051 if (TLI.isTypeDesirableForOp(Opc, VT))
1055 // Consult target whether it is a good idea to promote this operation and
1056 // what's the right type to promote it to.
1057 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058 assert(PVT != VT && "Don't know what type to promote to!");
1060 bool Replace = false;
1061 SDValue N0 = Op.getOperand(0);
1062 if (Opc == ISD::SRA)
1063 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1064 else if (Opc == ISD::SRL)
1065 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1067 N0 = PromoteOperand(N0, PVT, Replace);
1071 AddToWorklist(N0.getNode());
1073 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1075 DEBUG(dbgs() << "\nPromoting ";
1076 Op.getNode()->dump(&DAG));
1078 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1079 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1084 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1085 if (!LegalOperations)
1088 EVT VT = Op.getValueType();
1089 if (VT.isVector() || !VT.isInteger())
1092 // If operation type is 'undesirable', e.g. i16 on x86, consider
1094 unsigned Opc = Op.getOpcode();
1095 if (TLI.isTypeDesirableForOp(Opc, VT))
1099 // Consult target whether it is a good idea to promote this operation and
1100 // what's the right type to promote it to.
1101 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1102 assert(PVT != VT && "Don't know what type to promote to!");
1103 // fold (aext (aext x)) -> (aext x)
1104 // fold (aext (zext x)) -> (zext x)
1105 // fold (aext (sext x)) -> (sext x)
1106 DEBUG(dbgs() << "\nPromoting ";
1107 Op.getNode()->dump(&DAG));
1108 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1113 bool DAGCombiner::PromoteLoad(SDValue Op) {
1114 if (!LegalOperations)
1117 EVT VT = Op.getValueType();
1118 if (VT.isVector() || !VT.isInteger())
1121 // If operation type is 'undesirable', e.g. i16 on x86, consider
1123 unsigned Opc = Op.getOpcode();
1124 if (TLI.isTypeDesirableForOp(Opc, VT))
1128 // Consult target whether it is a good idea to promote this operation and
1129 // what's the right type to promote it to.
1130 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1131 assert(PVT != VT && "Don't know what type to promote to!");
1134 SDNode *N = Op.getNode();
1135 LoadSDNode *LD = cast<LoadSDNode>(N);
1136 EVT MemVT = LD->getMemoryVT();
1137 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1138 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1140 : LD->getExtensionType();
1141 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1142 LD->getChain(), LD->getBasePtr(),
1143 MemVT, LD->getMemOperand());
1144 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1146 DEBUG(dbgs() << "\nPromoting ";
1149 Result.getNode()->dump(&DAG);
1151 WorklistRemover DeadNodes(*this);
1152 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1153 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1154 deleteAndRecombine(N);
1155 AddToWorklist(Result.getNode());
1161 /// \brief Recursively delete a node which has no uses and any operands for
1162 /// which it is the only use.
1164 /// Note that this both deletes the nodes and removes them from the worklist.
1165 /// It also adds any nodes who have had a user deleted to the worklist as they
1166 /// may now have only one use and subject to other combines.
1167 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1168 if (!N->use_empty())
1171 SmallSetVector<SDNode *, 16> Nodes;
1174 N = Nodes.pop_back_val();
1178 if (N->use_empty()) {
1179 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1180 Nodes.insert(N->getOperand(i).getNode());
1182 removeFromWorklist(N);
1187 } while (!Nodes.empty());
1191 //===----------------------------------------------------------------------===//
1192 // Main DAG Combiner implementation
1193 //===----------------------------------------------------------------------===//
1195 void DAGCombiner::Run(CombineLevel AtLevel) {
1196 // set the instance variables, so that the various visit routines may use it.
1198 LegalOperations = Level >= AfterLegalizeVectorOps;
1199 LegalTypes = Level >= AfterLegalizeTypes;
1201 // Add all the dag nodes to the worklist.
1202 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1203 E = DAG.allnodes_end(); I != E; ++I)
1206 // Create a dummy node (which is not added to allnodes), that adds a reference
1207 // to the root node, preventing it from being deleted, and tracking any
1208 // changes of the root.
1209 HandleSDNode Dummy(DAG.getRoot());
1211 // while the worklist isn't empty, find a node and
1212 // try and combine it.
1213 while (!WorklistMap.empty()) {
1215 // The Worklist holds the SDNodes in order, but it may contain null entries.
1217 N = Worklist.pop_back_val();
1220 bool GoodWorklistEntry = WorklistMap.erase(N);
1221 (void)GoodWorklistEntry;
1222 assert(GoodWorklistEntry &&
1223 "Found a worklist entry without a corresponding map entry!");
1225 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1226 // N is deleted from the DAG, since they too may now be dead or may have a
1227 // reduced number of uses, allowing other xforms.
1228 if (recursivelyDeleteUnusedNodes(N))
1231 WorklistRemover DeadNodes(*this);
1233 // If this combine is running after legalizing the DAG, re-legalize any
1234 // nodes pulled off the worklist.
1235 if (Level == AfterLegalizeDAG) {
1236 SmallSetVector<SDNode *, 16> UpdatedNodes;
1237 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1239 for (SDNode *LN : UpdatedNodes) {
1241 AddUsersToWorklist(LN);
1247 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1249 // Add any operands of the new node which have not yet been combined to the
1250 // worklist as well. Because the worklist uniques things already, this
1251 // won't repeatedly process the same operand.
1252 CombinedNodes.insert(N);
1253 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1254 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1255 AddToWorklist(N->getOperand(i).getNode());
1257 SDValue RV = combine(N);
1264 // If we get back the same node we passed in, rather than a new node or
1265 // zero, we know that the node must have defined multiple values and
1266 // CombineTo was used. Since CombineTo takes care of the worklist
1267 // mechanics for us, we have no work to do in this case.
1268 if (RV.getNode() == N)
1271 assert(N->getOpcode() != ISD::DELETED_NODE &&
1272 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1273 "Node was deleted but visit returned new node!");
1275 DEBUG(dbgs() << " ... into: ";
1276 RV.getNode()->dump(&DAG));
1278 // Transfer debug value.
1279 DAG.TransferDbgValues(SDValue(N, 0), RV);
1280 if (N->getNumValues() == RV.getNode()->getNumValues())
1281 DAG.ReplaceAllUsesWith(N, RV.getNode());
1283 assert(N->getValueType(0) == RV.getValueType() &&
1284 N->getNumValues() == 1 && "Type mismatch");
1286 DAG.ReplaceAllUsesWith(N, &OpV);
1289 // Push the new node and any users onto the worklist
1290 AddToWorklist(RV.getNode());
1291 AddUsersToWorklist(RV.getNode());
1293 // Finally, if the node is now dead, remove it from the graph. The node
1294 // may not be dead if the replacement process recursively simplified to
1295 // something else needing this node. This will also take care of adding any
1296 // operands which have lost a user to the worklist.
1297 recursivelyDeleteUnusedNodes(N);
1300 // If the root changed (e.g. it was a dead load, update the root).
1301 DAG.setRoot(Dummy.getValue());
1302 DAG.RemoveDeadNodes();
1305 SDValue DAGCombiner::visit(SDNode *N) {
1306 switch (N->getOpcode()) {
1308 case ISD::TokenFactor: return visitTokenFactor(N);
1309 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1310 case ISD::ADD: return visitADD(N);
1311 case ISD::SUB: return visitSUB(N);
1312 case ISD::ADDC: return visitADDC(N);
1313 case ISD::SUBC: return visitSUBC(N);
1314 case ISD::ADDE: return visitADDE(N);
1315 case ISD::SUBE: return visitSUBE(N);
1316 case ISD::MUL: return visitMUL(N);
1317 case ISD::SDIV: return visitSDIV(N);
1318 case ISD::UDIV: return visitUDIV(N);
1319 case ISD::SREM: return visitSREM(N);
1320 case ISD::UREM: return visitUREM(N);
1321 case ISD::MULHU: return visitMULHU(N);
1322 case ISD::MULHS: return visitMULHS(N);
1323 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1324 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1325 case ISD::SMULO: return visitSMULO(N);
1326 case ISD::UMULO: return visitUMULO(N);
1327 case ISD::SDIVREM: return visitSDIVREM(N);
1328 case ISD::UDIVREM: return visitUDIVREM(N);
1329 case ISD::AND: return visitAND(N);
1330 case ISD::OR: return visitOR(N);
1331 case ISD::XOR: return visitXOR(N);
1332 case ISD::SHL: return visitSHL(N);
1333 case ISD::SRA: return visitSRA(N);
1334 case ISD::SRL: return visitSRL(N);
1336 case ISD::ROTL: return visitRotate(N);
1337 case ISD::CTLZ: return visitCTLZ(N);
1338 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1339 case ISD::CTTZ: return visitCTTZ(N);
1340 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1341 case ISD::CTPOP: return visitCTPOP(N);
1342 case ISD::SELECT: return visitSELECT(N);
1343 case ISD::VSELECT: return visitVSELECT(N);
1344 case ISD::SELECT_CC: return visitSELECT_CC(N);
1345 case ISD::SETCC: return visitSETCC(N);
1346 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1347 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1348 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1349 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1350 case ISD::TRUNCATE: return visitTRUNCATE(N);
1351 case ISD::BITCAST: return visitBITCAST(N);
1352 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1353 case ISD::FADD: return visitFADD(N);
1354 case ISD::FSUB: return visitFSUB(N);
1355 case ISD::FMUL: return visitFMUL(N);
1356 case ISD::FMA: return visitFMA(N);
1357 case ISD::FDIV: return visitFDIV(N);
1358 case ISD::FREM: return visitFREM(N);
1359 case ISD::FSQRT: return visitFSQRT(N);
1360 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1361 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1362 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1363 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1364 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1365 case ISD::FP_ROUND: return visitFP_ROUND(N);
1366 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1367 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1368 case ISD::FNEG: return visitFNEG(N);
1369 case ISD::FABS: return visitFABS(N);
1370 case ISD::FFLOOR: return visitFFLOOR(N);
1371 case ISD::FMINNUM: return visitFMINNUM(N);
1372 case ISD::FMAXNUM: return visitFMAXNUM(N);
1373 case ISD::FCEIL: return visitFCEIL(N);
1374 case ISD::FTRUNC: return visitFTRUNC(N);
1375 case ISD::BRCOND: return visitBRCOND(N);
1376 case ISD::BR_CC: return visitBR_CC(N);
1377 case ISD::LOAD: return visitLOAD(N);
1378 case ISD::STORE: return visitSTORE(N);
1379 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1380 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1381 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1382 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1383 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1384 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1385 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1386 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1387 case ISD::MGATHER: return visitMGATHER(N);
1388 case ISD::MLOAD: return visitMLOAD(N);
1389 case ISD::MSCATTER: return visitMSCATTER(N);
1390 case ISD::MSTORE: return visitMSTORE(N);
1391 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1396 SDValue DAGCombiner::combine(SDNode *N) {
1397 SDValue RV = visit(N);
1399 // If nothing happened, try a target-specific DAG combine.
1400 if (!RV.getNode()) {
1401 assert(N->getOpcode() != ISD::DELETED_NODE &&
1402 "Node was deleted but visit returned NULL!");
1404 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1405 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1407 // Expose the DAG combiner to the target combiner impls.
1408 TargetLowering::DAGCombinerInfo
1409 DagCombineInfo(DAG, Level, false, this);
1411 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1415 // If nothing happened still, try promoting the operation.
1416 if (!RV.getNode()) {
1417 switch (N->getOpcode()) {
1425 RV = PromoteIntBinOp(SDValue(N, 0));
1430 RV = PromoteIntShiftOp(SDValue(N, 0));
1432 case ISD::SIGN_EXTEND:
1433 case ISD::ZERO_EXTEND:
1434 case ISD::ANY_EXTEND:
1435 RV = PromoteExtend(SDValue(N, 0));
1438 if (PromoteLoad(SDValue(N, 0)))
1444 // If N is a commutative binary node, try commuting it to enable more
1446 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1447 N->getNumValues() == 1) {
1448 SDValue N0 = N->getOperand(0);
1449 SDValue N1 = N->getOperand(1);
1451 // Constant operands are canonicalized to RHS.
1452 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1453 SDValue Ops[] = {N1, N0};
1455 if (auto *FlagsNode = dyn_cast<SDNodeWithFlags>(N)) {
1456 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1457 Ops, &FlagsNode->Flags);
1459 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1462 return SDValue(CSENode, 0);
1469 /// Given a node, return its input chain if it has one, otherwise return a null
1471 static SDValue getInputChainForNode(SDNode *N) {
1472 if (unsigned NumOps = N->getNumOperands()) {
1473 if (N->getOperand(0).getValueType() == MVT::Other)
1474 return N->getOperand(0);
1475 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1476 return N->getOperand(NumOps-1);
1477 for (unsigned i = 1; i < NumOps-1; ++i)
1478 if (N->getOperand(i).getValueType() == MVT::Other)
1479 return N->getOperand(i);
1484 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1485 // If N has two operands, where one has an input chain equal to the other,
1486 // the 'other' chain is redundant.
1487 if (N->getNumOperands() == 2) {
1488 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1489 return N->getOperand(0);
1490 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1491 return N->getOperand(1);
1494 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1495 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1496 SmallPtrSet<SDNode*, 16> SeenOps;
1497 bool Changed = false; // If we should replace this token factor.
1499 // Start out with this token factor.
1502 // Iterate through token factors. The TFs grows when new token factors are
1504 for (unsigned i = 0; i < TFs.size(); ++i) {
1505 SDNode *TF = TFs[i];
1507 // Check each of the operands.
1508 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1509 SDValue Op = TF->getOperand(i);
1511 switch (Op.getOpcode()) {
1512 case ISD::EntryToken:
1513 // Entry tokens don't need to be added to the list. They are
1518 case ISD::TokenFactor:
1519 if (Op.hasOneUse() &&
1520 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1521 // Queue up for processing.
1522 TFs.push_back(Op.getNode());
1523 // Clean up in case the token factor is removed.
1524 AddToWorklist(Op.getNode());
1531 // Only add if it isn't already in the list.
1532 if (SeenOps.insert(Op.getNode()).second)
1543 // If we've changed things around then replace token factor.
1546 // The entry token is the only possible outcome.
1547 Result = DAG.getEntryNode();
1549 // New and improved token factor.
1550 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1553 // Add users to worklist if AA is enabled, since it may introduce
1554 // a lot of new chained token factors while removing memory deps.
1555 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1556 : DAG.getSubtarget().useAA();
1557 return CombineTo(N, Result, UseAA /*add to worklist*/);
1563 /// MERGE_VALUES can always be eliminated.
1564 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1565 WorklistRemover DeadNodes(*this);
1566 // Replacing results may cause a different MERGE_VALUES to suddenly
1567 // be CSE'd with N, and carry its uses with it. Iterate until no
1568 // uses remain, to ensure that the node can be safely deleted.
1569 // First add the users of this node to the work list so that they
1570 // can be tried again once they have new operands.
1571 AddUsersToWorklist(N);
1573 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1574 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1575 } while (!N->use_empty());
1576 deleteAndRecombine(N);
1577 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1580 SDValue DAGCombiner::visitADD(SDNode *N) {
1581 SDValue N0 = N->getOperand(0);
1582 SDValue N1 = N->getOperand(1);
1583 EVT VT = N0.getValueType();
1586 if (VT.isVector()) {
1587 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1590 // fold (add x, 0) -> x, vector edition
1591 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1593 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1597 // fold (add x, undef) -> undef
1598 if (N0.getOpcode() == ISD::UNDEF)
1600 if (N1.getOpcode() == ISD::UNDEF)
1602 // fold (add c1, c2) -> c1+c2
1603 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1604 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1606 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1607 // canonicalize constant to RHS
1608 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1609 !isConstantIntBuildVectorOrConstantInt(N1))
1610 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1611 // fold (add x, 0) -> x
1612 if (N1C && N1C->isNullValue())
1614 // fold (add Sym, c) -> Sym+c
1615 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1616 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1617 GA->getOpcode() == ISD::GlobalAddress)
1618 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1620 (uint64_t)N1C->getSExtValue());
1621 // fold ((c1-A)+c2) -> (c1+c2)-A
1622 if (N1C && N0.getOpcode() == ISD::SUB)
1623 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1625 return DAG.getNode(ISD::SUB, DL, VT,
1626 DAG.getConstant(N1C->getAPIntValue()+
1627 N0C->getAPIntValue(), DL, VT),
1631 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1633 // fold ((0-A) + B) -> B-A
1634 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1635 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1636 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1637 // fold (A + (0-B)) -> A-B
1638 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1639 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1640 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1641 // fold (A+(B-A)) -> B
1642 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1643 return N1.getOperand(0);
1644 // fold ((B-A)+A) -> B
1645 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1646 return N0.getOperand(0);
1647 // fold (A+(B-(A+C))) to (B-C)
1648 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1649 N0 == N1.getOperand(1).getOperand(0))
1650 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1651 N1.getOperand(1).getOperand(1));
1652 // fold (A+(B-(C+A))) to (B-C)
1653 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1654 N0 == N1.getOperand(1).getOperand(1))
1655 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1656 N1.getOperand(1).getOperand(0));
1657 // fold (A+((B-A)+or-C)) to (B+or-C)
1658 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1659 N1.getOperand(0).getOpcode() == ISD::SUB &&
1660 N0 == N1.getOperand(0).getOperand(1))
1661 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1662 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1664 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1665 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1666 SDValue N00 = N0.getOperand(0);
1667 SDValue N01 = N0.getOperand(1);
1668 SDValue N10 = N1.getOperand(0);
1669 SDValue N11 = N1.getOperand(1);
1671 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1672 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1673 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1674 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1677 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1678 return SDValue(N, 0);
1680 // fold (a+b) -> (a|b) iff a and b share no bits.
1681 if (VT.isInteger() && !VT.isVector()) {
1682 APInt LHSZero, LHSOne;
1683 APInt RHSZero, RHSOne;
1684 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1686 if (LHSZero.getBoolValue()) {
1687 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1689 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1690 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1691 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1692 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1693 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1698 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1699 if (N1.getOpcode() == ISD::SHL &&
1700 N1.getOperand(0).getOpcode() == ISD::SUB)
1701 if (ConstantSDNode *C =
1702 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1703 if (C->getAPIntValue() == 0)
1704 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1705 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1706 N1.getOperand(0).getOperand(1),
1708 if (N0.getOpcode() == ISD::SHL &&
1709 N0.getOperand(0).getOpcode() == ISD::SUB)
1710 if (ConstantSDNode *C =
1711 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1712 if (C->getAPIntValue() == 0)
1713 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1714 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1715 N0.getOperand(0).getOperand(1),
1718 if (N1.getOpcode() == ISD::AND) {
1719 SDValue AndOp0 = N1.getOperand(0);
1720 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1721 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1722 unsigned DestBits = VT.getScalarType().getSizeInBits();
1724 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1725 // and similar xforms where the inner op is either ~0 or 0.
1726 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1728 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1732 // add (sext i1), X -> sub X, (zext i1)
1733 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1734 N0.getOperand(0).getValueType() == MVT::i1 &&
1735 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1737 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1738 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1741 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1742 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1743 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1744 if (TN->getVT() == MVT::i1) {
1746 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1747 DAG.getConstant(1, DL, VT));
1748 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1755 SDValue DAGCombiner::visitADDC(SDNode *N) {
1756 SDValue N0 = N->getOperand(0);
1757 SDValue N1 = N->getOperand(1);
1758 EVT VT = N0.getValueType();
1760 // If the flag result is dead, turn this into an ADD.
1761 if (!N->hasAnyUseOfValue(1))
1762 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1763 DAG.getNode(ISD::CARRY_FALSE,
1764 SDLoc(N), MVT::Glue));
1766 // canonicalize constant to RHS.
1767 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1768 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1770 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1772 // fold (addc x, 0) -> x + no carry out
1773 if (N1C && N1C->isNullValue())
1774 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1775 SDLoc(N), MVT::Glue));
1777 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1778 APInt LHSZero, LHSOne;
1779 APInt RHSZero, RHSOne;
1780 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1782 if (LHSZero.getBoolValue()) {
1783 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1785 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1786 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1787 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1788 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1789 DAG.getNode(ISD::CARRY_FALSE,
1790 SDLoc(N), MVT::Glue));
1796 SDValue DAGCombiner::visitADDE(SDNode *N) {
1797 SDValue N0 = N->getOperand(0);
1798 SDValue N1 = N->getOperand(1);
1799 SDValue CarryIn = N->getOperand(2);
1801 // canonicalize constant to RHS
1802 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1803 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1805 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1808 // fold (adde x, y, false) -> (addc x, y)
1809 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1810 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1815 // Since it may not be valid to emit a fold to zero for vector initializers
1816 // check if we can before folding.
1817 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1819 bool LegalOperations, bool LegalTypes) {
1821 return DAG.getConstant(0, DL, VT);
1822 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1823 return DAG.getConstant(0, DL, VT);
1827 SDValue DAGCombiner::visitSUB(SDNode *N) {
1828 SDValue N0 = N->getOperand(0);
1829 SDValue N1 = N->getOperand(1);
1830 EVT VT = N0.getValueType();
1833 if (VT.isVector()) {
1834 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1837 // fold (sub x, 0) -> x, vector edition
1838 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1842 // fold (sub x, x) -> 0
1843 // FIXME: Refactor this and xor and other similar operations together.
1845 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1846 // fold (sub c1, c2) -> c1-c2
1847 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1848 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1850 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1851 // fold (sub x, c) -> (add x, -c)
1854 return DAG.getNode(ISD::ADD, DL, VT, N0,
1855 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1857 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1858 if (N0C && N0C->isAllOnesValue())
1859 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1860 // fold A-(A-B) -> B
1861 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1862 return N1.getOperand(1);
1863 // fold (A+B)-A -> B
1864 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1865 return N0.getOperand(1);
1866 // fold (A+B)-B -> A
1867 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1868 return N0.getOperand(0);
1869 // fold C2-(A+C1) -> (C2-C1)-A
1870 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1871 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1872 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1874 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1876 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1879 // fold ((A+(B+or-C))-B) -> A+or-C
1880 if (N0.getOpcode() == ISD::ADD &&
1881 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1882 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1883 N0.getOperand(1).getOperand(0) == N1)
1884 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1885 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1886 // fold ((A+(C+B))-B) -> A+C
1887 if (N0.getOpcode() == ISD::ADD &&
1888 N0.getOperand(1).getOpcode() == ISD::ADD &&
1889 N0.getOperand(1).getOperand(1) == N1)
1890 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1891 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1892 // fold ((A-(B-C))-C) -> A-B
1893 if (N0.getOpcode() == ISD::SUB &&
1894 N0.getOperand(1).getOpcode() == ISD::SUB &&
1895 N0.getOperand(1).getOperand(1) == N1)
1896 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1897 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1899 // If either operand of a sub is undef, the result is undef
1900 if (N0.getOpcode() == ISD::UNDEF)
1902 if (N1.getOpcode() == ISD::UNDEF)
1905 // If the relocation model supports it, consider symbol offsets.
1906 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1907 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1908 // fold (sub Sym, c) -> Sym-c
1909 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1910 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1912 (uint64_t)N1C->getSExtValue());
1913 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1914 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1915 if (GA->getGlobal() == GB->getGlobal())
1916 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1920 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1921 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1922 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1923 if (TN->getVT() == MVT::i1) {
1925 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1926 DAG.getConstant(1, DL, VT));
1927 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1934 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1935 SDValue N0 = N->getOperand(0);
1936 SDValue N1 = N->getOperand(1);
1937 EVT VT = N0.getValueType();
1939 // If the flag result is dead, turn this into an SUB.
1940 if (!N->hasAnyUseOfValue(1))
1941 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1942 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1945 // fold (subc x, x) -> 0 + no borrow
1948 return CombineTo(N, DAG.getConstant(0, DL, VT),
1949 DAG.getNode(ISD::CARRY_FALSE, DL,
1953 // fold (subc x, 0) -> x + no borrow
1954 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1955 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1956 if (N1C && N1C->isNullValue())
1957 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1960 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1961 if (N0C && N0C->isAllOnesValue())
1962 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1963 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1969 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1970 SDValue N0 = N->getOperand(0);
1971 SDValue N1 = N->getOperand(1);
1972 SDValue CarryIn = N->getOperand(2);
1974 // fold (sube x, y, false) -> (subc x, y)
1975 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1976 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1981 SDValue DAGCombiner::visitMUL(SDNode *N) {
1982 SDValue N0 = N->getOperand(0);
1983 SDValue N1 = N->getOperand(1);
1984 EVT VT = N0.getValueType();
1986 // fold (mul x, undef) -> 0
1987 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1988 return DAG.getConstant(0, SDLoc(N), VT);
1990 bool N0IsConst = false;
1991 bool N1IsConst = false;
1992 APInt ConstValue0, ConstValue1;
1994 if (VT.isVector()) {
1995 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1998 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1999 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2001 N0IsConst = isa<ConstantSDNode>(N0);
2003 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2004 N1IsConst = isa<ConstantSDNode>(N1);
2006 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2009 // fold (mul c1, c2) -> c1*c2
2010 if (N0IsConst && N1IsConst)
2011 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2012 N0.getNode(), N1.getNode());
2014 // canonicalize constant to RHS (vector doesn't have to splat)
2015 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2016 !isConstantIntBuildVectorOrConstantInt(N1))
2017 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2018 // fold (mul x, 0) -> 0
2019 if (N1IsConst && ConstValue1 == 0)
2021 // We require a splat of the entire scalar bit width for non-contiguous
2024 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2025 // fold (mul x, 1) -> x
2026 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2028 // fold (mul x, -1) -> 0-x
2029 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2031 return DAG.getNode(ISD::SUB, DL, VT,
2032 DAG.getConstant(0, DL, VT), N0);
2034 // fold (mul x, (1 << c)) -> x << c
2035 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2037 return DAG.getNode(ISD::SHL, DL, VT, N0,
2038 DAG.getConstant(ConstValue1.logBase2(), DL,
2039 getShiftAmountTy(N0.getValueType())));
2041 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2042 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2043 unsigned Log2Val = (-ConstValue1).logBase2();
2045 // FIXME: If the input is something that is easily negated (e.g. a
2046 // single-use add), we should put the negate there.
2047 return DAG.getNode(ISD::SUB, DL, VT,
2048 DAG.getConstant(0, DL, VT),
2049 DAG.getNode(ISD::SHL, DL, VT, N0,
2050 DAG.getConstant(Log2Val, DL,
2051 getShiftAmountTy(N0.getValueType()))));
2055 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2056 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2057 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2058 isa<ConstantSDNode>(N0.getOperand(1)))) {
2059 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2060 N1, N0.getOperand(1));
2061 AddToWorklist(C3.getNode());
2062 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2063 N0.getOperand(0), C3);
2066 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2069 SDValue Sh(nullptr,0), Y(nullptr,0);
2070 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2071 if (N0.getOpcode() == ISD::SHL &&
2072 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2073 isa<ConstantSDNode>(N0.getOperand(1))) &&
2074 N0.getNode()->hasOneUse()) {
2076 } else if (N1.getOpcode() == ISD::SHL &&
2077 isa<ConstantSDNode>(N1.getOperand(1)) &&
2078 N1.getNode()->hasOneUse()) {
2083 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2084 Sh.getOperand(0), Y);
2085 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2086 Mul, Sh.getOperand(1));
2090 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2091 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2092 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2093 isa<ConstantSDNode>(N0.getOperand(1))))
2094 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2095 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2096 N0.getOperand(0), N1),
2097 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2098 N0.getOperand(1), N1));
2101 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2107 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2108 SDValue N0 = N->getOperand(0);
2109 SDValue N1 = N->getOperand(1);
2110 EVT VT = N->getValueType(0);
2114 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2117 // fold (sdiv c1, c2) -> c1/c2
2118 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2119 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2120 if (N0C && N1C && !N1C->isNullValue())
2121 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2122 // fold (sdiv X, 1) -> X
2123 if (N1C && N1C->getAPIntValue() == 1LL)
2125 // fold (sdiv X, -1) -> 0-X
2126 if (N1C && N1C->isAllOnesValue()) {
2128 return DAG.getNode(ISD::SUB, DL, VT,
2129 DAG.getConstant(0, DL, VT), N0);
2131 // If we know the sign bits of both operands are zero, strength reduce to a
2132 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2133 if (!VT.isVector()) {
2134 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2135 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2139 // fold (sdiv X, pow2) -> simple ops after legalize
2140 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2141 (-N1C->getAPIntValue()).isPowerOf2())) {
2142 // If dividing by powers of two is cheap, then don't perform the following
2144 if (TLI.isPow2SDivCheap())
2147 // Target-specific implementation of sdiv x, pow2.
2148 SDValue Res = BuildSDIVPow2(N);
2152 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2155 // Splat the sign bit into the register
2157 DAG.getNode(ISD::SRA, DL, VT, N0,
2158 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2159 getShiftAmountTy(N0.getValueType())));
2160 AddToWorklist(SGN.getNode());
2162 // Add (N0 < 0) ? abs2 - 1 : 0;
2164 DAG.getNode(ISD::SRL, DL, VT, SGN,
2165 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2166 getShiftAmountTy(SGN.getValueType())));
2167 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2168 AddToWorklist(SRL.getNode());
2169 AddToWorklist(ADD.getNode()); // Divide by pow2
2170 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2171 DAG.getConstant(lg2, DL,
2172 getShiftAmountTy(ADD.getValueType())));
2174 // If we're dividing by a positive value, we're done. Otherwise, we must
2175 // negate the result.
2176 if (N1C->getAPIntValue().isNonNegative())
2179 AddToWorklist(SRA.getNode());
2180 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2183 // If integer divide is expensive and we satisfy the requirements, emit an
2184 // alternate sequence.
2185 if (N1C && !TLI.isIntDivCheap()) {
2186 SDValue Op = BuildSDIV(N);
2187 if (Op.getNode()) return Op;
2191 if (N0.getOpcode() == ISD::UNDEF)
2192 return DAG.getConstant(0, SDLoc(N), VT);
2193 // X / undef -> undef
2194 if (N1.getOpcode() == ISD::UNDEF)
2200 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2201 SDValue N0 = N->getOperand(0);
2202 SDValue N1 = N->getOperand(1);
2203 EVT VT = N->getValueType(0);
2207 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2210 // fold (udiv c1, c2) -> c1/c2
2211 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2212 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2213 if (N0C && N1C && !N1C->isNullValue())
2214 return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2215 // fold (udiv x, (1 << c)) -> x >>u c
2216 if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2218 return DAG.getNode(ISD::SRL, DL, VT, N0,
2219 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2220 getShiftAmountTy(N0.getValueType())));
2222 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2223 if (N1.getOpcode() == ISD::SHL) {
2224 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2225 if (SHC->getAPIntValue().isPowerOf2()) {
2226 EVT ADDVT = N1.getOperand(1).getValueType();
2228 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2230 DAG.getConstant(SHC->getAPIntValue()
2233 AddToWorklist(Add.getNode());
2234 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2238 // fold (udiv x, c) -> alternate
2239 if (N1C && !TLI.isIntDivCheap()) {
2240 SDValue Op = BuildUDIV(N);
2241 if (Op.getNode()) return Op;
2245 if (N0.getOpcode() == ISD::UNDEF)
2246 return DAG.getConstant(0, SDLoc(N), VT);
2247 // X / undef -> undef
2248 if (N1.getOpcode() == ISD::UNDEF)
2254 SDValue DAGCombiner::visitSREM(SDNode *N) {
2255 SDValue N0 = N->getOperand(0);
2256 SDValue N1 = N->getOperand(1);
2257 EVT VT = N->getValueType(0);
2259 // fold (srem c1, c2) -> c1%c2
2260 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2261 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2262 if (N0C && N1C && !N1C->isNullValue())
2263 return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2264 // If we know the sign bits of both operands are zero, strength reduce to a
2265 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2266 if (!VT.isVector()) {
2267 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2268 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2271 // If X/C can be simplified by the division-by-constant logic, lower
2272 // X%C to the equivalent of X-X/C*C.
2273 if (N1C && !N1C->isNullValue()) {
2274 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2275 AddToWorklist(Div.getNode());
2276 SDValue OptimizedDiv = combine(Div.getNode());
2277 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2278 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2280 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2281 AddToWorklist(Mul.getNode());
2287 if (N0.getOpcode() == ISD::UNDEF)
2288 return DAG.getConstant(0, SDLoc(N), VT);
2289 // X % undef -> undef
2290 if (N1.getOpcode() == ISD::UNDEF)
2296 SDValue DAGCombiner::visitUREM(SDNode *N) {
2297 SDValue N0 = N->getOperand(0);
2298 SDValue N1 = N->getOperand(1);
2299 EVT VT = N->getValueType(0);
2301 // fold (urem c1, c2) -> c1%c2
2302 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2303 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2304 if (N0C && N1C && !N1C->isNullValue())
2305 return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2306 // fold (urem x, pow2) -> (and x, pow2-1)
2307 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2309 return DAG.getNode(ISD::AND, DL, VT, N0,
2310 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2312 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2313 if (N1.getOpcode() == ISD::SHL) {
2314 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2315 if (SHC->getAPIntValue().isPowerOf2()) {
2318 DAG.getNode(ISD::ADD, DL, VT, N1,
2319 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2321 AddToWorklist(Add.getNode());
2322 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2327 // If X/C can be simplified by the division-by-constant logic, lower
2328 // X%C to the equivalent of X-X/C*C.
2329 if (N1C && !N1C->isNullValue()) {
2330 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2331 AddToWorklist(Div.getNode());
2332 SDValue OptimizedDiv = combine(Div.getNode());
2333 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2334 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2336 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2337 AddToWorklist(Mul.getNode());
2343 if (N0.getOpcode() == ISD::UNDEF)
2344 return DAG.getConstant(0, SDLoc(N), VT);
2345 // X % undef -> undef
2346 if (N1.getOpcode() == ISD::UNDEF)
2352 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2353 SDValue N0 = N->getOperand(0);
2354 SDValue N1 = N->getOperand(1);
2355 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2356 EVT VT = N->getValueType(0);
2359 // fold (mulhs x, 0) -> 0
2360 if (N1C && N1C->isNullValue())
2362 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2363 if (N1C && N1C->getAPIntValue() == 1) {
2365 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2366 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2368 getShiftAmountTy(N0.getValueType())));
2370 // fold (mulhs x, undef) -> 0
2371 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2372 return DAG.getConstant(0, SDLoc(N), VT);
2374 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2376 if (VT.isSimple() && !VT.isVector()) {
2377 MVT Simple = VT.getSimpleVT();
2378 unsigned SimpleSize = Simple.getSizeInBits();
2379 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2380 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2381 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2382 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2383 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2384 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2385 DAG.getConstant(SimpleSize, DL,
2386 getShiftAmountTy(N1.getValueType())));
2387 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2394 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2395 SDValue N0 = N->getOperand(0);
2396 SDValue N1 = N->getOperand(1);
2397 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2398 EVT VT = N->getValueType(0);
2401 // fold (mulhu x, 0) -> 0
2402 if (N1C && N1C->isNullValue())
2404 // fold (mulhu x, 1) -> 0
2405 if (N1C && N1C->getAPIntValue() == 1)
2406 return DAG.getConstant(0, DL, N0.getValueType());
2407 // fold (mulhu x, undef) -> 0
2408 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2409 return DAG.getConstant(0, DL, VT);
2411 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2413 if (VT.isSimple() && !VT.isVector()) {
2414 MVT Simple = VT.getSimpleVT();
2415 unsigned SimpleSize = Simple.getSizeInBits();
2416 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2417 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2418 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2419 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2420 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2421 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2422 DAG.getConstant(SimpleSize, DL,
2423 getShiftAmountTy(N1.getValueType())));
2424 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2431 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2432 /// give the opcodes for the two computations that are being performed. Return
2433 /// true if a simplification was made.
2434 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2436 // If the high half is not needed, just compute the low half.
2437 bool HiExists = N->hasAnyUseOfValue(1);
2439 (!LegalOperations ||
2440 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2441 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2442 return CombineTo(N, Res, Res);
2445 // If the low half is not needed, just compute the high half.
2446 bool LoExists = N->hasAnyUseOfValue(0);
2448 (!LegalOperations ||
2449 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2450 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2451 return CombineTo(N, Res, Res);
2454 // If both halves are used, return as it is.
2455 if (LoExists && HiExists)
2458 // If the two computed results can be simplified separately, separate them.
2460 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2461 AddToWorklist(Lo.getNode());
2462 SDValue LoOpt = combine(Lo.getNode());
2463 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2464 (!LegalOperations ||
2465 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2466 return CombineTo(N, LoOpt, LoOpt);
2470 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2471 AddToWorklist(Hi.getNode());
2472 SDValue HiOpt = combine(Hi.getNode());
2473 if (HiOpt.getNode() && HiOpt != Hi &&
2474 (!LegalOperations ||
2475 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2476 return CombineTo(N, HiOpt, HiOpt);
2482 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2483 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2484 if (Res.getNode()) return Res;
2486 EVT VT = N->getValueType(0);
2489 // If the type is twice as wide is legal, transform the mulhu to a wider
2490 // multiply plus a shift.
2491 if (VT.isSimple() && !VT.isVector()) {
2492 MVT Simple = VT.getSimpleVT();
2493 unsigned SimpleSize = Simple.getSizeInBits();
2494 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2495 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2496 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2497 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2498 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2499 // Compute the high part as N1.
2500 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2501 DAG.getConstant(SimpleSize, DL,
2502 getShiftAmountTy(Lo.getValueType())));
2503 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2504 // Compute the low part as N0.
2505 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2506 return CombineTo(N, Lo, Hi);
2513 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2514 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2515 if (Res.getNode()) return Res;
2517 EVT VT = N->getValueType(0);
2520 // If the type is twice as wide is legal, transform the mulhu to a wider
2521 // multiply plus a shift.
2522 if (VT.isSimple() && !VT.isVector()) {
2523 MVT Simple = VT.getSimpleVT();
2524 unsigned SimpleSize = Simple.getSizeInBits();
2525 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2526 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2527 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2528 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2529 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2530 // Compute the high part as N1.
2531 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2532 DAG.getConstant(SimpleSize, DL,
2533 getShiftAmountTy(Lo.getValueType())));
2534 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2535 // Compute the low part as N0.
2536 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2537 return CombineTo(N, Lo, Hi);
2544 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2545 // (smulo x, 2) -> (saddo x, x)
2546 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2547 if (C2->getAPIntValue() == 2)
2548 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2549 N->getOperand(0), N->getOperand(0));
2554 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2555 // (umulo x, 2) -> (uaddo x, x)
2556 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2557 if (C2->getAPIntValue() == 2)
2558 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2559 N->getOperand(0), N->getOperand(0));
2564 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2565 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2566 if (Res.getNode()) return Res;
2571 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2572 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2573 if (Res.getNode()) return Res;
2578 /// If this is a binary operator with two operands of the same opcode, try to
2580 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2581 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2582 EVT VT = N0.getValueType();
2583 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2585 // Bail early if none of these transforms apply.
2586 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2588 // For each of OP in AND/OR/XOR:
2589 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2590 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2591 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2592 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2593 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2595 // do not sink logical op inside of a vector extend, since it may combine
2597 EVT Op0VT = N0.getOperand(0).getValueType();
2598 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2599 N0.getOpcode() == ISD::SIGN_EXTEND ||
2600 N0.getOpcode() == ISD::BSWAP ||
2601 // Avoid infinite looping with PromoteIntBinOp.
2602 (N0.getOpcode() == ISD::ANY_EXTEND &&
2603 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2604 (N0.getOpcode() == ISD::TRUNCATE &&
2605 (!TLI.isZExtFree(VT, Op0VT) ||
2606 !TLI.isTruncateFree(Op0VT, VT)) &&
2607 TLI.isTypeLegal(Op0VT))) &&
2609 Op0VT == N1.getOperand(0).getValueType() &&
2610 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2611 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2612 N0.getOperand(0).getValueType(),
2613 N0.getOperand(0), N1.getOperand(0));
2614 AddToWorklist(ORNode.getNode());
2615 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2618 // For each of OP in SHL/SRL/SRA/AND...
2619 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2620 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2621 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2622 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2623 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2624 N0.getOperand(1) == N1.getOperand(1)) {
2625 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2626 N0.getOperand(0).getValueType(),
2627 N0.getOperand(0), N1.getOperand(0));
2628 AddToWorklist(ORNode.getNode());
2629 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2630 ORNode, N0.getOperand(1));
2633 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2634 // Only perform this optimization after type legalization and before
2635 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2636 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2637 // we don't want to undo this promotion.
2638 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2640 if ((N0.getOpcode() == ISD::BITCAST ||
2641 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2642 Level == AfterLegalizeTypes) {
2643 SDValue In0 = N0.getOperand(0);
2644 SDValue In1 = N1.getOperand(0);
2645 EVT In0Ty = In0.getValueType();
2646 EVT In1Ty = In1.getValueType();
2648 // If both incoming values are integers, and the original types are the
2650 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2651 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2652 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2653 AddToWorklist(Op.getNode());
2658 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2659 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2660 // If both shuffles use the same mask, and both shuffle within a single
2661 // vector, then it is worthwhile to move the swizzle after the operation.
2662 // The type-legalizer generates this pattern when loading illegal
2663 // vector types from memory. In many cases this allows additional shuffle
2665 // There are other cases where moving the shuffle after the xor/and/or
2666 // is profitable even if shuffles don't perform a swizzle.
2667 // If both shuffles use the same mask, and both shuffles have the same first
2668 // or second operand, then it might still be profitable to move the shuffle
2669 // after the xor/and/or operation.
2670 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2671 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2672 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2674 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2675 "Inputs to shuffles are not the same type");
2677 // Check that both shuffles use the same mask. The masks are known to be of
2678 // the same length because the result vector type is the same.
2679 // Check also that shuffles have only one use to avoid introducing extra
2681 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2682 SVN0->getMask().equals(SVN1->getMask())) {
2683 SDValue ShOp = N0->getOperand(1);
2685 // Don't try to fold this node if it requires introducing a
2686 // build vector of all zeros that might be illegal at this stage.
2687 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2689 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2694 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2695 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2696 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2697 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2698 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2699 N0->getOperand(0), N1->getOperand(0));
2700 AddToWorklist(NewNode.getNode());
2701 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2702 &SVN0->getMask()[0]);
2705 // Don't try to fold this node if it requires introducing a
2706 // build vector of all zeros that might be illegal at this stage.
2707 ShOp = N0->getOperand(0);
2708 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2710 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2715 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2716 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2717 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2718 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2719 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2720 N0->getOperand(1), N1->getOperand(1));
2721 AddToWorklist(NewNode.getNode());
2722 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2723 &SVN0->getMask()[0]);
2731 /// This contains all DAGCombine rules which reduce two values combined by
2732 /// an And operation to a single value. This makes them reusable in the context
2733 /// of visitSELECT(). Rules involving constants are not included as
2734 /// visitSELECT() already handles those cases.
2735 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2736 SDNode *LocReference) {
2737 EVT VT = N1.getValueType();
2739 // fold (and x, undef) -> 0
2740 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2741 return DAG.getConstant(0, SDLoc(LocReference), VT);
2742 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2743 SDValue LL, LR, RL, RR, CC0, CC1;
2744 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2745 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2746 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2748 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2749 LL.getValueType().isInteger()) {
2750 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2751 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2752 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2753 LR.getValueType(), LL, RL);
2754 AddToWorklist(ORNode.getNode());
2755 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2757 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2758 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2759 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2760 LR.getValueType(), LL, RL);
2761 AddToWorklist(ANDNode.getNode());
2762 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2764 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2765 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2766 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2767 LR.getValueType(), LL, RL);
2768 AddToWorklist(ORNode.getNode());
2769 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2772 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2773 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2774 Op0 == Op1 && LL.getValueType().isInteger() &&
2775 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2776 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2777 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2778 cast<ConstantSDNode>(RR)->isNullValue()))) {
2780 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2781 LL, DAG.getConstant(1, DL,
2782 LL.getValueType()));
2783 AddToWorklist(ADDNode.getNode());
2784 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2785 DAG.getConstant(2, DL, LL.getValueType()),
2788 // canonicalize equivalent to ll == rl
2789 if (LL == RR && LR == RL) {
2790 Op1 = ISD::getSetCCSwappedOperands(Op1);
2793 if (LL == RL && LR == RR) {
2794 bool isInteger = LL.getValueType().isInteger();
2795 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2796 if (Result != ISD::SETCC_INVALID &&
2797 (!LegalOperations ||
2798 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2799 TLI.isOperationLegal(ISD::SETCC,
2800 getSetCCResultType(N0.getSimpleValueType())))))
2801 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2806 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2807 VT.getSizeInBits() <= 64) {
2808 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2809 APInt ADDC = ADDI->getAPIntValue();
2810 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2811 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2812 // immediate for an add, but it is legal if its top c2 bits are set,
2813 // transform the ADD so the immediate doesn't need to be materialized
2815 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2816 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2817 SRLI->getZExtValue());
2818 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2820 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2823 DAG.getNode(ISD::ADD, DL, VT,
2824 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2825 CombineTo(N0.getNode(), NewAdd);
2826 // Return N so it doesn't get rechecked!
2827 return SDValue(LocReference, 0);
2838 SDValue DAGCombiner::visitAND(SDNode *N) {
2839 SDValue N0 = N->getOperand(0);
2840 SDValue N1 = N->getOperand(1);
2841 EVT VT = N1.getValueType();
2844 if (VT.isVector()) {
2845 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2848 // fold (and x, 0) -> 0, vector edition
2849 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2850 // do not return N0, because undef node may exist in N0
2851 return DAG.getConstant(
2852 APInt::getNullValue(
2853 N0.getValueType().getScalarType().getSizeInBits()),
2854 SDLoc(N), N0.getValueType());
2855 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2856 // do not return N1, because undef node may exist in N1
2857 return DAG.getConstant(
2858 APInt::getNullValue(
2859 N1.getValueType().getScalarType().getSizeInBits()),
2860 SDLoc(N), N1.getValueType());
2862 // fold (and x, -1) -> x, vector edition
2863 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2865 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2869 // fold (and c1, c2) -> c1&c2
2870 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2871 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2873 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2874 // canonicalize constant to RHS
2875 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2876 !isConstantIntBuildVectorOrConstantInt(N1))
2877 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2878 // fold (and x, -1) -> x
2879 if (N1C && N1C->isAllOnesValue())
2881 // if (and x, c) is known to be zero, return 0
2882 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2883 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2884 APInt::getAllOnesValue(BitWidth)))
2885 return DAG.getConstant(0, SDLoc(N), VT);
2887 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2889 // fold (and (or x, C), D) -> D if (C & D) == D
2890 if (N1C && N0.getOpcode() == ISD::OR)
2891 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2892 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2894 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2895 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2896 SDValue N0Op0 = N0.getOperand(0);
2897 APInt Mask = ~N1C->getAPIntValue();
2898 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2899 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2900 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2901 N0.getValueType(), N0Op0);
2903 // Replace uses of the AND with uses of the Zero extend node.
2906 // We actually want to replace all uses of the any_extend with the
2907 // zero_extend, to avoid duplicating things. This will later cause this
2908 // AND to be folded.
2909 CombineTo(N0.getNode(), Zext);
2910 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2913 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2914 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2915 // already be zero by virtue of the width of the base type of the load.
2917 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2919 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2920 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2921 N0.getOpcode() == ISD::LOAD) {
2922 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2923 N0 : N0.getOperand(0) );
2925 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2926 // This can be a pure constant or a vector splat, in which case we treat the
2927 // vector as a scalar and use the splat value.
2928 APInt Constant = APInt::getNullValue(1);
2929 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2930 Constant = C->getAPIntValue();
2931 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2932 APInt SplatValue, SplatUndef;
2933 unsigned SplatBitSize;
2935 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2936 SplatBitSize, HasAnyUndefs);
2938 // Undef bits can contribute to a possible optimisation if set, so
2940 SplatValue |= SplatUndef;
2942 // The splat value may be something like "0x00FFFFFF", which means 0 for
2943 // the first vector value and FF for the rest, repeating. We need a mask
2944 // that will apply equally to all members of the vector, so AND all the
2945 // lanes of the constant together.
2946 EVT VT = Vector->getValueType(0);
2947 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2949 // If the splat value has been compressed to a bitlength lower
2950 // than the size of the vector lane, we need to re-expand it to
2952 if (BitWidth > SplatBitSize)
2953 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2954 SplatBitSize < BitWidth;
2955 SplatBitSize = SplatBitSize * 2)
2956 SplatValue |= SplatValue.shl(SplatBitSize);
2958 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2959 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2960 if (SplatBitSize % BitWidth == 0) {
2961 Constant = APInt::getAllOnesValue(BitWidth);
2962 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2963 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2968 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2969 // actually legal and isn't going to get expanded, else this is a false
2971 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2972 Load->getValueType(0),
2973 Load->getMemoryVT());
2975 // Resize the constant to the same size as the original memory access before
2976 // extension. If it is still the AllOnesValue then this AND is completely
2979 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2982 switch (Load->getExtensionType()) {
2983 default: B = false; break;
2984 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2986 case ISD::NON_EXTLOAD: B = true; break;
2989 if (B && Constant.isAllOnesValue()) {
2990 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2991 // preserve semantics once we get rid of the AND.
2992 SDValue NewLoad(Load, 0);
2993 if (Load->getExtensionType() == ISD::EXTLOAD) {
2994 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2995 Load->getValueType(0), SDLoc(Load),
2996 Load->getChain(), Load->getBasePtr(),
2997 Load->getOffset(), Load->getMemoryVT(),
2998 Load->getMemOperand());
2999 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3000 if (Load->getNumValues() == 3) {
3001 // PRE/POST_INC loads have 3 values.
3002 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3003 NewLoad.getValue(2) };
3004 CombineTo(Load, To, 3, true);
3006 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3010 // Fold the AND away, taking care not to fold to the old load node if we
3012 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3014 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3018 // fold (and (load x), 255) -> (zextload x, i8)
3019 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3020 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3021 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3022 (N0.getOpcode() == ISD::ANY_EXTEND &&
3023 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3024 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3025 LoadSDNode *LN0 = HasAnyExt
3026 ? cast<LoadSDNode>(N0.getOperand(0))
3027 : cast<LoadSDNode>(N0);
3028 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3029 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3030 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3031 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3032 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3033 EVT LoadedVT = LN0->getMemoryVT();
3034 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3036 if (ExtVT == LoadedVT &&
3037 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3041 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3042 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3043 LN0->getMemOperand());
3045 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3046 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3049 // Do not change the width of a volatile load.
3050 // Do not generate loads of non-round integer types since these can
3051 // be expensive (and would be wrong if the type is not byte sized).
3052 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3053 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3055 EVT PtrType = LN0->getOperand(1).getValueType();
3057 unsigned Alignment = LN0->getAlignment();
3058 SDValue NewPtr = LN0->getBasePtr();
3060 // For big endian targets, we need to add an offset to the pointer
3061 // to load the correct bytes. For little endian systems, we merely
3062 // need to read fewer bytes from the same pointer.
3063 if (TLI.isBigEndian()) {
3064 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3065 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3066 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3068 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3069 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3070 Alignment = MinAlign(Alignment, PtrOff);
3073 AddToWorklist(NewPtr.getNode());
3076 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3077 LN0->getChain(), NewPtr,
3078 LN0->getPointerInfo(),
3079 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3080 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3082 CombineTo(LN0, Load, Load.getValue(1));
3083 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3089 if (SDValue Combined = visitANDLike(N0, N1, N))
3092 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3093 if (N0.getOpcode() == N1.getOpcode()) {
3094 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3095 if (Tmp.getNode()) return Tmp;
3098 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3099 // fold (and (sra)) -> (and (srl)) when possible.
3100 if (!VT.isVector() &&
3101 SimplifyDemandedBits(SDValue(N, 0)))
3102 return SDValue(N, 0);
3104 // fold (zext_inreg (extload x)) -> (zextload x)
3105 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3106 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3107 EVT MemVT = LN0->getMemoryVT();
3108 // If we zero all the possible extended bits, then we can turn this into
3109 // a zextload if we are running before legalize or the operation is legal.
3110 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3111 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3112 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3113 ((!LegalOperations && !LN0->isVolatile()) ||
3114 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3115 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3116 LN0->getChain(), LN0->getBasePtr(),
3117 MemVT, LN0->getMemOperand());
3119 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3120 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3123 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3124 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3126 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3127 EVT MemVT = LN0->getMemoryVT();
3128 // If we zero all the possible extended bits, then we can turn this into
3129 // a zextload if we are running before legalize or the operation is legal.
3130 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3131 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3132 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3133 ((!LegalOperations && !LN0->isVolatile()) ||
3134 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3135 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3136 LN0->getChain(), LN0->getBasePtr(),
3137 MemVT, LN0->getMemOperand());
3139 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3140 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3143 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3144 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3145 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3146 N0.getOperand(1), false);
3147 if (BSwap.getNode())
3154 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3155 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3156 bool DemandHighBits) {
3157 if (!LegalOperations)
3160 EVT VT = N->getValueType(0);
3161 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3163 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3166 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3167 bool LookPassAnd0 = false;
3168 bool LookPassAnd1 = false;
3169 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3171 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3173 if (N0.getOpcode() == ISD::AND) {
3174 if (!N0.getNode()->hasOneUse())
3176 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3177 if (!N01C || N01C->getZExtValue() != 0xFF00)
3179 N0 = N0.getOperand(0);
3180 LookPassAnd0 = true;
3183 if (N1.getOpcode() == ISD::AND) {
3184 if (!N1.getNode()->hasOneUse())
3186 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3187 if (!N11C || N11C->getZExtValue() != 0xFF)
3189 N1 = N1.getOperand(0);
3190 LookPassAnd1 = true;
3193 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3195 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3197 if (!N0.getNode()->hasOneUse() ||
3198 !N1.getNode()->hasOneUse())
3201 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3202 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3205 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3208 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3209 SDValue N00 = N0->getOperand(0);
3210 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3211 if (!N00.getNode()->hasOneUse())
3213 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3214 if (!N001C || N001C->getZExtValue() != 0xFF)
3216 N00 = N00.getOperand(0);
3217 LookPassAnd0 = true;
3220 SDValue N10 = N1->getOperand(0);
3221 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3222 if (!N10.getNode()->hasOneUse())
3224 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3225 if (!N101C || N101C->getZExtValue() != 0xFF00)
3227 N10 = N10.getOperand(0);
3228 LookPassAnd1 = true;
3234 // Make sure everything beyond the low halfword gets set to zero since the SRL
3235 // 16 will clear the top bits.
3236 unsigned OpSizeInBits = VT.getSizeInBits();
3237 if (DemandHighBits && OpSizeInBits > 16) {
3238 // If the left-shift isn't masked out then the only way this is a bswap is
3239 // if all bits beyond the low 8 are 0. In that case the entire pattern
3240 // reduces to a left shift anyway: leave it for other parts of the combiner.
3244 // However, if the right shift isn't masked out then it might be because
3245 // it's not needed. See if we can spot that too.
3246 if (!LookPassAnd1 &&
3247 !DAG.MaskedValueIsZero(
3248 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3252 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3253 if (OpSizeInBits > 16) {
3255 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3256 DAG.getConstant(OpSizeInBits - 16, DL,
3257 getShiftAmountTy(VT)));
3262 /// Return true if the specified node is an element that makes up a 32-bit
3263 /// packed halfword byteswap.
3264 /// ((x & 0x000000ff) << 8) |
3265 /// ((x & 0x0000ff00) >> 8) |
3266 /// ((x & 0x00ff0000) << 8) |
3267 /// ((x & 0xff000000) >> 8)
3268 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3269 if (!N.getNode()->hasOneUse())
3272 unsigned Opc = N.getOpcode();
3273 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3276 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3281 switch (N1C->getZExtValue()) {
3284 case 0xFF: Num = 0; break;
3285 case 0xFF00: Num = 1; break;
3286 case 0xFF0000: Num = 2; break;
3287 case 0xFF000000: Num = 3; break;
3290 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3291 SDValue N0 = N.getOperand(0);
3292 if (Opc == ISD::AND) {
3293 if (Num == 0 || Num == 2) {
3295 // (x >> 8) & 0xff0000
3296 if (N0.getOpcode() != ISD::SRL)
3298 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3299 if (!C || C->getZExtValue() != 8)
3302 // (x << 8) & 0xff00
3303 // (x << 8) & 0xff000000
3304 if (N0.getOpcode() != ISD::SHL)
3306 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3307 if (!C || C->getZExtValue() != 8)
3310 } else if (Opc == ISD::SHL) {
3312 // (x & 0xff0000) << 8
3313 if (Num != 0 && Num != 2)
3315 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3316 if (!C || C->getZExtValue() != 8)
3318 } else { // Opc == ISD::SRL
3319 // (x & 0xff00) >> 8
3320 // (x & 0xff000000) >> 8
3321 if (Num != 1 && Num != 3)
3323 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3324 if (!C || C->getZExtValue() != 8)
3331 Parts[Num] = N0.getOperand(0).getNode();
3335 /// Match a 32-bit packed halfword bswap. That is
3336 /// ((x & 0x000000ff) << 8) |
3337 /// ((x & 0x0000ff00) >> 8) |
3338 /// ((x & 0x00ff0000) << 8) |
3339 /// ((x & 0xff000000) >> 8)
3340 /// => (rotl (bswap x), 16)
3341 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3342 if (!LegalOperations)
3345 EVT VT = N->getValueType(0);
3348 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3352 // (or (or (and), (and)), (or (and), (and)))
3353 // (or (or (or (and), (and)), (and)), (and))
3354 if (N0.getOpcode() != ISD::OR)
3356 SDValue N00 = N0.getOperand(0);
3357 SDValue N01 = N0.getOperand(1);
3358 SDNode *Parts[4] = {};
3360 if (N1.getOpcode() == ISD::OR &&
3361 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3362 // (or (or (and), (and)), (or (and), (and)))
3363 SDValue N000 = N00.getOperand(0);
3364 if (!isBSwapHWordElement(N000, Parts))
3367 SDValue N001 = N00.getOperand(1);
3368 if (!isBSwapHWordElement(N001, Parts))
3370 SDValue N010 = N01.getOperand(0);
3371 if (!isBSwapHWordElement(N010, Parts))
3373 SDValue N011 = N01.getOperand(1);
3374 if (!isBSwapHWordElement(N011, Parts))
3377 // (or (or (or (and), (and)), (and)), (and))
3378 if (!isBSwapHWordElement(N1, Parts))
3380 if (!isBSwapHWordElement(N01, Parts))
3382 if (N00.getOpcode() != ISD::OR)
3384 SDValue N000 = N00.getOperand(0);
3385 if (!isBSwapHWordElement(N000, Parts))
3387 SDValue N001 = N00.getOperand(1);
3388 if (!isBSwapHWordElement(N001, Parts))
3392 // Make sure the parts are all coming from the same node.
3393 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3397 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3398 SDValue(Parts[0], 0));
3400 // Result of the bswap should be rotated by 16. If it's not legal, then
3401 // do (x << 16) | (x >> 16).
3402 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3403 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3404 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3405 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3406 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3407 return DAG.getNode(ISD::OR, DL, VT,
3408 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3409 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3412 /// This contains all DAGCombine rules which reduce two values combined by
3413 /// an Or operation to a single value \see visitANDLike().
3414 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3415 EVT VT = N1.getValueType();
3416 // fold (or x, undef) -> -1
3417 if (!LegalOperations &&
3418 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3419 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3420 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3421 SDLoc(LocReference), VT);
3423 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3424 SDValue LL, LR, RL, RR, CC0, CC1;
3425 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3426 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3427 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3429 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3430 LL.getValueType().isInteger()) {
3431 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3432 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3433 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3434 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3435 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3436 LR.getValueType(), LL, RL);
3437 AddToWorklist(ORNode.getNode());
3438 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3440 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3441 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3442 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3443 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3444 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3445 LR.getValueType(), LL, RL);
3446 AddToWorklist(ANDNode.getNode());
3447 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3450 // canonicalize equivalent to ll == rl
3451 if (LL == RR && LR == RL) {
3452 Op1 = ISD::getSetCCSwappedOperands(Op1);
3455 if (LL == RL && LR == RR) {
3456 bool isInteger = LL.getValueType().isInteger();
3457 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3458 if (Result != ISD::SETCC_INVALID &&
3459 (!LegalOperations ||
3460 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3461 TLI.isOperationLegal(ISD::SETCC,
3462 getSetCCResultType(N0.getValueType())))))
3463 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3468 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3469 if (N0.getOpcode() == ISD::AND &&
3470 N1.getOpcode() == ISD::AND &&
3471 N0.getOperand(1).getOpcode() == ISD::Constant &&
3472 N1.getOperand(1).getOpcode() == ISD::Constant &&
3473 // Don't increase # computations.
3474 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3475 // We can only do this xform if we know that bits from X that are set in C2
3476 // but not in C1 are already zero. Likewise for Y.
3477 const APInt &LHSMask =
3478 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3479 const APInt &RHSMask =
3480 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3482 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3483 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3484 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3485 N0.getOperand(0), N1.getOperand(0));
3486 SDLoc DL(LocReference);
3487 return DAG.getNode(ISD::AND, DL, VT, X,
3488 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3492 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3493 if (N0.getOpcode() == ISD::AND &&
3494 N1.getOpcode() == ISD::AND &&
3495 N0.getOperand(0) == N1.getOperand(0) &&
3496 // Don't increase # computations.
3497 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3498 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3499 N0.getOperand(1), N1.getOperand(1));
3500 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3506 SDValue DAGCombiner::visitOR(SDNode *N) {
3507 SDValue N0 = N->getOperand(0);
3508 SDValue N1 = N->getOperand(1);
3509 EVT VT = N1.getValueType();
3512 if (VT.isVector()) {
3513 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3516 // fold (or x, 0) -> x, vector edition
3517 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3519 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3522 // fold (or x, -1) -> -1, vector edition
3523 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3524 // do not return N0, because undef node may exist in N0
3525 return DAG.getConstant(
3526 APInt::getAllOnesValue(
3527 N0.getValueType().getScalarType().getSizeInBits()),
3528 SDLoc(N), N0.getValueType());
3529 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3530 // do not return N1, because undef node may exist in N1
3531 return DAG.getConstant(
3532 APInt::getAllOnesValue(
3533 N1.getValueType().getScalarType().getSizeInBits()),
3534 SDLoc(N), N1.getValueType());
3536 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3537 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3538 // Do this only if the resulting shuffle is legal.
3539 if (isa<ShuffleVectorSDNode>(N0) &&
3540 isa<ShuffleVectorSDNode>(N1) &&
3541 // Avoid folding a node with illegal type.
3542 TLI.isTypeLegal(VT) &&
3543 N0->getOperand(1) == N1->getOperand(1) &&
3544 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3545 bool CanFold = true;
3546 unsigned NumElts = VT.getVectorNumElements();
3547 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3548 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3549 // We construct two shuffle masks:
3550 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3551 // and N1 as the second operand.
3552 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3553 // and N0 as the second operand.
3554 // We do this because OR is commutable and therefore there might be
3555 // two ways to fold this node into a shuffle.
3556 SmallVector<int,4> Mask1;
3557 SmallVector<int,4> Mask2;
3559 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3560 int M0 = SV0->getMaskElt(i);
3561 int M1 = SV1->getMaskElt(i);
3563 // Both shuffle indexes are undef. Propagate Undef.
3564 if (M0 < 0 && M1 < 0) {
3565 Mask1.push_back(M0);
3566 Mask2.push_back(M0);
3570 if (M0 < 0 || M1 < 0 ||
3571 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3572 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3577 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3578 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3582 // Fold this sequence only if the resulting shuffle is 'legal'.
3583 if (TLI.isShuffleMaskLegal(Mask1, VT))
3584 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3585 N1->getOperand(0), &Mask1[0]);
3586 if (TLI.isShuffleMaskLegal(Mask2, VT))
3587 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3588 N0->getOperand(0), &Mask2[0]);
3593 // fold (or c1, c2) -> c1|c2
3594 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3595 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3597 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3598 // canonicalize constant to RHS
3599 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3600 !isConstantIntBuildVectorOrConstantInt(N1))
3601 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3602 // fold (or x, 0) -> x
3603 if (N1C && N1C->isNullValue())
3605 // fold (or x, -1) -> -1
3606 if (N1C && N1C->isAllOnesValue())
3608 // fold (or x, c) -> c iff (x & ~c) == 0
3609 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3612 if (SDValue Combined = visitORLike(N0, N1, N))
3615 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3616 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3617 if (BSwap.getNode())
3619 BSwap = MatchBSwapHWordLow(N, N0, N1);
3620 if (BSwap.getNode())
3624 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3626 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3627 // iff (c1 & c2) == 0.
3628 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3629 isa<ConstantSDNode>(N0.getOperand(1))) {
3630 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3631 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3632 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3635 ISD::AND, SDLoc(N), VT,
3636 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3640 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3641 if (N0.getOpcode() == N1.getOpcode()) {
3642 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3643 if (Tmp.getNode()) return Tmp;
3646 // See if this is some rotate idiom.
3647 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3648 return SDValue(Rot, 0);
3650 // Simplify the operands using demanded-bits information.
3651 if (!VT.isVector() &&
3652 SimplifyDemandedBits(SDValue(N, 0)))
3653 return SDValue(N, 0);
3658 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3659 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3660 if (Op.getOpcode() == ISD::AND) {
3661 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3662 Mask = Op.getOperand(1);
3663 Op = Op.getOperand(0);
3669 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3677 // Return true if we can prove that, whenever Neg and Pos are both in the
3678 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3679 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3681 // (or (shift1 X, Neg), (shift2 X, Pos))
3683 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3684 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3685 // to consider shift amounts with defined behavior.
3686 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3687 // If OpSize is a power of 2 then:
3689 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3690 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3692 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3693 // for the stronger condition:
3695 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3697 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3698 // we can just replace Neg with Neg' for the rest of the function.
3700 // In other cases we check for the even stronger condition:
3702 // Neg == OpSize - Pos [B]
3704 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3705 // behavior if Pos == 0 (and consequently Neg == OpSize).
3707 // We could actually use [A] whenever OpSize is a power of 2, but the
3708 // only extra cases that it would match are those uninteresting ones
3709 // where Neg and Pos are never in range at the same time. E.g. for
3710 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3711 // as well as (sub 32, Pos), but:
3713 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3715 // always invokes undefined behavior for 32-bit X.
3717 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3718 unsigned MaskLoBits = 0;
3719 if (Neg.getOpcode() == ISD::AND &&
3720 isPowerOf2_64(OpSize) &&
3721 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3722 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3723 Neg = Neg.getOperand(0);
3724 MaskLoBits = Log2_64(OpSize);
3727 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3728 if (Neg.getOpcode() != ISD::SUB)
3730 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3733 SDValue NegOp1 = Neg.getOperand(1);
3735 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3736 // Pos'. The truncation is redundant for the purpose of the equality.
3738 Pos.getOpcode() == ISD::AND &&
3739 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3740 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3741 Pos = Pos.getOperand(0);
3743 // The condition we need is now:
3745 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3747 // If NegOp1 == Pos then we need:
3749 // OpSize & Mask == NegC & Mask
3751 // (because "x & Mask" is a truncation and distributes through subtraction).
3754 Width = NegC->getAPIntValue();
3755 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3756 // Then the condition we want to prove becomes:
3758 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3760 // which, again because "x & Mask" is a truncation, becomes:
3762 // NegC & Mask == (OpSize - PosC) & Mask
3763 // OpSize & Mask == (NegC + PosC) & Mask
3764 else if (Pos.getOpcode() == ISD::ADD &&
3765 Pos.getOperand(0) == NegOp1 &&
3766 Pos.getOperand(1).getOpcode() == ISD::Constant)
3767 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3768 NegC->getAPIntValue());
3772 // Now we just need to check that OpSize & Mask == Width & Mask.
3774 // Opsize & Mask is 0 since Mask is Opsize - 1.
3775 return Width.getLoBits(MaskLoBits) == 0;
3776 return Width == OpSize;
3779 // A subroutine of MatchRotate used once we have found an OR of two opposite
3780 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3781 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3782 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3783 // Neg with outer conversions stripped away.
3784 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3785 SDValue Neg, SDValue InnerPos,
3786 SDValue InnerNeg, unsigned PosOpcode,
3787 unsigned NegOpcode, SDLoc DL) {
3788 // fold (or (shl x, (*ext y)),
3789 // (srl x, (*ext (sub 32, y)))) ->
3790 // (rotl x, y) or (rotr x, (sub 32, y))
3792 // fold (or (shl x, (*ext (sub 32, y))),
3793 // (srl x, (*ext y))) ->
3794 // (rotr x, y) or (rotl x, (sub 32, y))
3795 EVT VT = Shifted.getValueType();
3796 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3797 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3798 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3799 HasPos ? Pos : Neg).getNode();
3805 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3806 // idioms for rotate, and if the target supports rotation instructions, generate
3808 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3809 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3810 EVT VT = LHS.getValueType();
3811 if (!TLI.isTypeLegal(VT)) return nullptr;
3813 // The target must have at least one rotate flavor.
3814 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3815 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3816 if (!HasROTL && !HasROTR) return nullptr;
3818 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3819 SDValue LHSShift; // The shift.
3820 SDValue LHSMask; // AND value if any.
3821 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3822 return nullptr; // Not part of a rotate.
3824 SDValue RHSShift; // The shift.
3825 SDValue RHSMask; // AND value if any.
3826 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3827 return nullptr; // Not part of a rotate.
3829 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3830 return nullptr; // Not shifting the same value.
3832 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3833 return nullptr; // Shifts must disagree.
3835 // Canonicalize shl to left side in a shl/srl pair.
3836 if (RHSShift.getOpcode() == ISD::SHL) {
3837 std::swap(LHS, RHS);
3838 std::swap(LHSShift, RHSShift);
3839 std::swap(LHSMask , RHSMask );
3842 unsigned OpSizeInBits = VT.getSizeInBits();
3843 SDValue LHSShiftArg = LHSShift.getOperand(0);
3844 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3845 SDValue RHSShiftArg = RHSShift.getOperand(0);
3846 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3848 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3849 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3850 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3851 RHSShiftAmt.getOpcode() == ISD::Constant) {
3852 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3853 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3854 if ((LShVal + RShVal) != OpSizeInBits)
3857 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3858 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3860 // If there is an AND of either shifted operand, apply it to the result.
3861 if (LHSMask.getNode() || RHSMask.getNode()) {
3862 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3864 if (LHSMask.getNode()) {
3865 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3866 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3868 if (RHSMask.getNode()) {
3869 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3870 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3873 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3876 return Rot.getNode();
3879 // If there is a mask here, and we have a variable shift, we can't be sure
3880 // that we're masking out the right stuff.
3881 if (LHSMask.getNode() || RHSMask.getNode())
3884 // If the shift amount is sign/zext/any-extended just peel it off.
3885 SDValue LExtOp0 = LHSShiftAmt;
3886 SDValue RExtOp0 = RHSShiftAmt;
3887 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3888 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3889 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3890 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3891 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3892 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3893 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3894 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3895 LExtOp0 = LHSShiftAmt.getOperand(0);
3896 RExtOp0 = RHSShiftAmt.getOperand(0);
3899 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3900 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3904 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3905 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3912 SDValue DAGCombiner::visitXOR(SDNode *N) {
3913 SDValue N0 = N->getOperand(0);
3914 SDValue N1 = N->getOperand(1);
3915 EVT VT = N0.getValueType();
3918 if (VT.isVector()) {
3919 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3922 // fold (xor x, 0) -> x, vector edition
3923 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3925 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3929 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3930 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3931 return DAG.getConstant(0, SDLoc(N), VT);
3932 // fold (xor x, undef) -> undef
3933 if (N0.getOpcode() == ISD::UNDEF)
3935 if (N1.getOpcode() == ISD::UNDEF)
3937 // fold (xor c1, c2) -> c1^c2
3938 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3939 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3941 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3942 // canonicalize constant to RHS
3943 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3944 !isConstantIntBuildVectorOrConstantInt(N1))
3945 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3946 // fold (xor x, 0) -> x
3947 if (N1C && N1C->isNullValue())
3950 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3953 // fold !(x cc y) -> (x !cc y)
3954 SDValue LHS, RHS, CC;
3955 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3956 bool isInt = LHS.getValueType().isInteger();
3957 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3960 if (!LegalOperations ||
3961 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3962 switch (N0.getOpcode()) {
3964 llvm_unreachable("Unhandled SetCC Equivalent!");
3966 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3967 case ISD::SELECT_CC:
3968 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3969 N0.getOperand(3), NotCC);
3974 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3975 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3976 N0.getNode()->hasOneUse() &&
3977 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3978 SDValue V = N0.getOperand(0);
3980 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3981 DAG.getConstant(1, DL, V.getValueType()));
3982 AddToWorklist(V.getNode());
3983 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3986 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3987 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3988 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3989 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3990 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3991 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3992 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3993 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3994 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3995 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3998 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3999 if (N1C && N1C->isAllOnesValue() &&
4000 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4001 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4002 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4003 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4004 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4005 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4006 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4007 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4010 // fold (xor (and x, y), y) -> (and (not x), y)
4011 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4012 N0->getOperand(1) == N1) {
4013 SDValue X = N0->getOperand(0);
4014 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4015 AddToWorklist(NotX.getNode());
4016 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4018 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4019 if (N1C && N0.getOpcode() == ISD::XOR) {
4020 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4021 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4024 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4025 DAG.getConstant(N1C->getAPIntValue() ^
4026 N00C->getAPIntValue(), DL, VT));
4030 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4031 DAG.getConstant(N1C->getAPIntValue() ^
4032 N01C->getAPIntValue(), DL, VT));
4035 // fold (xor x, x) -> 0
4037 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4039 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4040 // Here is a concrete example of this equivalence:
4042 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4043 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4047 // i16 ~1 == 0b1111111111111110
4048 // i16 rol(~1, 14) == 0b1011111111111111
4050 // Some additional tips to help conceptualize this transform:
4051 // - Try to see the operation as placing a single zero in a value of all ones.
4052 // - There exists no value for x which would allow the result to contain zero.
4053 // - Values of x larger than the bitwidth are undefined and do not require a
4054 // consistent result.
4055 // - Pushing the zero left requires shifting one bits in from the right.
4056 // A rotate left of ~1 is a nice way of achieving the desired result.
4057 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4058 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4059 if (N0.getOpcode() == ISD::SHL)
4060 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4061 if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4063 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4067 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4068 if (N0.getOpcode() == N1.getOpcode()) {
4069 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4070 if (Tmp.getNode()) return Tmp;
4073 // Simplify the expression using non-local knowledge.
4074 if (!VT.isVector() &&
4075 SimplifyDemandedBits(SDValue(N, 0)))
4076 return SDValue(N, 0);
4081 /// Handle transforms common to the three shifts, when the shift amount is a
4083 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4084 // We can't and shouldn't fold opaque constants.
4085 if (Amt->isOpaque())
4088 SDNode *LHS = N->getOperand(0).getNode();
4089 if (!LHS->hasOneUse()) return SDValue();
4091 // We want to pull some binops through shifts, so that we have (and (shift))
4092 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4093 // thing happens with address calculations, so it's important to canonicalize
4095 bool HighBitSet = false; // Can we transform this if the high bit is set?
4097 switch (LHS->getOpcode()) {
4098 default: return SDValue();
4101 HighBitSet = false; // We can only transform sra if the high bit is clear.
4104 HighBitSet = true; // We can only transform sra if the high bit is set.
4107 if (N->getOpcode() != ISD::SHL)
4108 return SDValue(); // only shl(add) not sr[al](add).
4109 HighBitSet = false; // We can only transform sra if the high bit is clear.
4113 // We require the RHS of the binop to be a constant and not opaque as well.
4114 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4115 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4117 // FIXME: disable this unless the input to the binop is a shift by a constant.
4118 // If it is not a shift, it pessimizes some common cases like:
4120 // void foo(int *X, int i) { X[i & 1235] = 1; }
4121 // int bar(int *X, int i) { return X[i & 255]; }
4122 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4123 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4124 BinOpLHSVal->getOpcode() != ISD::SRA &&
4125 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4126 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4129 EVT VT = N->getValueType(0);
4131 // If this is a signed shift right, and the high bit is modified by the
4132 // logical operation, do not perform the transformation. The highBitSet
4133 // boolean indicates the value of the high bit of the constant which would
4134 // cause it to be modified for this operation.
4135 if (N->getOpcode() == ISD::SRA) {
4136 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4137 if (BinOpRHSSignSet != HighBitSet)
4141 if (!TLI.isDesirableToCommuteWithShift(LHS))
4144 // Fold the constants, shifting the binop RHS by the shift amount.
4145 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4147 LHS->getOperand(1), N->getOperand(1));
4148 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4150 // Create the new shift.
4151 SDValue NewShift = DAG.getNode(N->getOpcode(),
4152 SDLoc(LHS->getOperand(0)),
4153 VT, LHS->getOperand(0), N->getOperand(1));
4155 // Create the new binop.
4156 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4159 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4160 assert(N->getOpcode() == ISD::TRUNCATE);
4161 assert(N->getOperand(0).getOpcode() == ISD::AND);
4163 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4164 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4165 SDValue N01 = N->getOperand(0).getOperand(1);
4167 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4168 EVT TruncVT = N->getValueType(0);
4169 SDValue N00 = N->getOperand(0).getOperand(0);
4170 APInt TruncC = N01C->getAPIntValue();
4171 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4174 return DAG.getNode(ISD::AND, DL, TruncVT,
4175 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4176 DAG.getConstant(TruncC, DL, TruncVT));
4183 SDValue DAGCombiner::visitRotate(SDNode *N) {
4184 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4185 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4186 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4187 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4188 if (NewOp1.getNode())
4189 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4190 N->getOperand(0), NewOp1);
4195 SDValue DAGCombiner::visitSHL(SDNode *N) {
4196 SDValue N0 = N->getOperand(0);
4197 SDValue N1 = N->getOperand(1);
4198 EVT VT = N0.getValueType();
4199 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4202 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4203 if (VT.isVector()) {
4204 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4207 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4208 // If setcc produces all-one true value then:
4209 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4210 if (N1CV && N1CV->isConstant()) {
4211 if (N0.getOpcode() == ISD::AND) {
4212 SDValue N00 = N0->getOperand(0);
4213 SDValue N01 = N0->getOperand(1);
4214 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4216 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4217 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4218 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4219 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4221 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4224 N1C = isConstOrConstSplat(N1);
4229 // fold (shl c1, c2) -> c1<<c2
4230 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4232 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4233 // fold (shl 0, x) -> 0
4234 if (N0C && N0C->isNullValue())
4236 // fold (shl x, c >= size(x)) -> undef
4237 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4238 return DAG.getUNDEF(VT);
4239 // fold (shl x, 0) -> x
4240 if (N1C && N1C->isNullValue())
4242 // fold (shl undef, x) -> 0
4243 if (N0.getOpcode() == ISD::UNDEF)
4244 return DAG.getConstant(0, SDLoc(N), VT);
4245 // if (shl x, c) is known to be zero, return 0
4246 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4247 APInt::getAllOnesValue(OpSizeInBits)))
4248 return DAG.getConstant(0, SDLoc(N), VT);
4249 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4250 if (N1.getOpcode() == ISD::TRUNCATE &&
4251 N1.getOperand(0).getOpcode() == ISD::AND) {
4252 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4253 if (NewOp1.getNode())
4254 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4257 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4258 return SDValue(N, 0);
4260 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4261 if (N1C && N0.getOpcode() == ISD::SHL) {
4262 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4263 uint64_t c1 = N0C1->getZExtValue();
4264 uint64_t c2 = N1C->getZExtValue();
4266 if (c1 + c2 >= OpSizeInBits)
4267 return DAG.getConstant(0, DL, VT);
4268 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4269 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4273 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4274 // For this to be valid, the second form must not preserve any of the bits
4275 // that are shifted out by the inner shift in the first form. This means
4276 // the outer shift size must be >= the number of bits added by the ext.
4277 // As a corollary, we don't care what kind of ext it is.
4278 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4279 N0.getOpcode() == ISD::ANY_EXTEND ||
4280 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4281 N0.getOperand(0).getOpcode() == ISD::SHL) {
4282 SDValue N0Op0 = N0.getOperand(0);
4283 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4284 uint64_t c1 = N0Op0C1->getZExtValue();
4285 uint64_t c2 = N1C->getZExtValue();
4286 EVT InnerShiftVT = N0Op0.getValueType();
4287 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4288 if (c2 >= OpSizeInBits - InnerShiftSize) {
4290 if (c1 + c2 >= OpSizeInBits)
4291 return DAG.getConstant(0, DL, VT);
4292 return DAG.getNode(ISD::SHL, DL, VT,
4293 DAG.getNode(N0.getOpcode(), DL, VT,
4294 N0Op0->getOperand(0)),
4295 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4300 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4301 // Only fold this if the inner zext has no other uses to avoid increasing
4302 // the total number of instructions.
4303 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4304 N0.getOperand(0).getOpcode() == ISD::SRL) {
4305 SDValue N0Op0 = N0.getOperand(0);
4306 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4307 uint64_t c1 = N0Op0C1->getZExtValue();
4308 if (c1 < VT.getScalarSizeInBits()) {
4309 uint64_t c2 = N1C->getZExtValue();
4311 SDValue NewOp0 = N0.getOperand(0);
4312 EVT CountVT = NewOp0.getOperand(1).getValueType();
4314 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4316 DAG.getConstant(c2, DL, CountVT));
4317 AddToWorklist(NewSHL.getNode());
4318 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4324 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4325 // (and (srl x, (sub c1, c2), MASK)
4326 // Only fold this if the inner shift has no other uses -- if it does, folding
4327 // this will increase the total number of instructions.
4328 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4329 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4330 uint64_t c1 = N0C1->getZExtValue();
4331 if (c1 < OpSizeInBits) {
4332 uint64_t c2 = N1C->getZExtValue();
4333 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4336 Mask = Mask.shl(c2 - c1);
4338 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4339 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4341 Mask = Mask.lshr(c1 - c2);
4343 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4344 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4347 return DAG.getNode(ISD::AND, DL, VT, Shift,
4348 DAG.getConstant(Mask, DL, VT));
4352 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4353 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4354 unsigned BitSize = VT.getScalarSizeInBits();
4356 SDValue HiBitsMask =
4357 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4358 BitSize - N1C->getZExtValue()),
4360 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4364 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4365 // Variant of version done on multiply, except mul by a power of 2 is turned
4368 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4369 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4370 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4371 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4372 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4373 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4377 SDValue NewSHL = visitShiftByConstant(N, N1C);
4378 if (NewSHL.getNode())
4385 SDValue DAGCombiner::visitSRA(SDNode *N) {
4386 SDValue N0 = N->getOperand(0);
4387 SDValue N1 = N->getOperand(1);
4388 EVT VT = N0.getValueType();
4389 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4392 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4393 if (VT.isVector()) {
4394 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4397 N1C = isConstOrConstSplat(N1);
4400 // fold (sra c1, c2) -> (sra c1, c2)
4401 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4403 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4404 // fold (sra 0, x) -> 0
4405 if (N0C && N0C->isNullValue())
4407 // fold (sra -1, x) -> -1
4408 if (N0C && N0C->isAllOnesValue())
4410 // fold (sra x, (setge c, size(x))) -> undef
4411 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4412 return DAG.getUNDEF(VT);
4413 // fold (sra x, 0) -> x
4414 if (N1C && N1C->isNullValue())
4416 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4418 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4419 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4420 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4422 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4423 ExtVT, VT.getVectorNumElements());
4424 if ((!LegalOperations ||
4425 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4426 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4427 N0.getOperand(0), DAG.getValueType(ExtVT));
4430 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4431 if (N1C && N0.getOpcode() == ISD::SRA) {
4432 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4433 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4434 if (Sum >= OpSizeInBits)
4435 Sum = OpSizeInBits - 1;
4437 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4438 DAG.getConstant(Sum, DL, N1.getValueType()));
4442 // fold (sra (shl X, m), (sub result_size, n))
4443 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4444 // result_size - n != m.
4445 // If truncate is free for the target sext(shl) is likely to result in better
4447 if (N0.getOpcode() == ISD::SHL && N1C) {
4448 // Get the two constanst of the shifts, CN0 = m, CN = n.
4449 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4451 LLVMContext &Ctx = *DAG.getContext();
4452 // Determine what the truncate's result bitsize and type would be.
4453 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4456 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4458 // Determine the residual right-shift amount.
4459 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4461 // If the shift is not a no-op (in which case this should be just a sign
4462 // extend already), the truncated to type is legal, sign_extend is legal
4463 // on that type, and the truncate to that type is both legal and free,
4464 // perform the transform.
4465 if ((ShiftAmt > 0) &&
4466 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4467 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4468 TLI.isTruncateFree(VT, TruncVT)) {
4471 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4472 getShiftAmountTy(N0.getOperand(0).getValueType()));
4473 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4474 N0.getOperand(0), Amt);
4475 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4477 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4478 N->getValueType(0), Trunc);
4483 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4484 if (N1.getOpcode() == ISD::TRUNCATE &&
4485 N1.getOperand(0).getOpcode() == ISD::AND) {
4486 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4487 if (NewOp1.getNode())
4488 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4491 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4492 // if c1 is equal to the number of bits the trunc removes
4493 if (N0.getOpcode() == ISD::TRUNCATE &&
4494 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4495 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4496 N0.getOperand(0).hasOneUse() &&
4497 N0.getOperand(0).getOperand(1).hasOneUse() &&
4499 SDValue N0Op0 = N0.getOperand(0);
4500 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4501 unsigned LargeShiftVal = LargeShift->getZExtValue();
4502 EVT LargeVT = N0Op0.getValueType();
4504 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4507 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4508 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4509 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4510 N0Op0.getOperand(0), Amt);
4511 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4516 // Simplify, based on bits shifted out of the LHS.
4517 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4518 return SDValue(N, 0);
4521 // If the sign bit is known to be zero, switch this to a SRL.
4522 if (DAG.SignBitIsZero(N0))
4523 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4526 SDValue NewSRA = visitShiftByConstant(N, N1C);
4527 if (NewSRA.getNode())
4534 SDValue DAGCombiner::visitSRL(SDNode *N) {
4535 SDValue N0 = N->getOperand(0);
4536 SDValue N1 = N->getOperand(1);
4537 EVT VT = N0.getValueType();
4538 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4541 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4542 if (VT.isVector()) {
4543 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4546 N1C = isConstOrConstSplat(N1);
4549 // fold (srl c1, c2) -> c1 >>u c2
4550 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4552 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4553 // fold (srl 0, x) -> 0
4554 if (N0C && N0C->isNullValue())
4556 // fold (srl x, c >= size(x)) -> undef
4557 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4558 return DAG.getUNDEF(VT);
4559 // fold (srl x, 0) -> x
4560 if (N1C && N1C->isNullValue())
4562 // if (srl x, c) is known to be zero, return 0
4563 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4564 APInt::getAllOnesValue(OpSizeInBits)))
4565 return DAG.getConstant(0, SDLoc(N), VT);
4567 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4568 if (N1C && N0.getOpcode() == ISD::SRL) {
4569 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4570 uint64_t c1 = N01C->getZExtValue();
4571 uint64_t c2 = N1C->getZExtValue();
4573 if (c1 + c2 >= OpSizeInBits)
4574 return DAG.getConstant(0, DL, VT);
4575 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4576 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4580 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4581 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4582 N0.getOperand(0).getOpcode() == ISD::SRL &&
4583 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4585 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4586 uint64_t c2 = N1C->getZExtValue();
4587 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4588 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4589 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4590 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4591 if (c1 + OpSizeInBits == InnerShiftSize) {
4593 if (c1 + c2 >= InnerShiftSize)
4594 return DAG.getConstant(0, DL, VT);
4595 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4596 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4597 N0.getOperand(0)->getOperand(0),
4598 DAG.getConstant(c1 + c2, DL,
4603 // fold (srl (shl x, c), c) -> (and x, cst2)
4604 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4605 unsigned BitSize = N0.getScalarValueSizeInBits();
4606 if (BitSize <= 64) {
4607 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4609 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4610 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4614 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4615 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4616 // Shifting in all undef bits?
4617 EVT SmallVT = N0.getOperand(0).getValueType();
4618 unsigned BitSize = SmallVT.getScalarSizeInBits();
4619 if (N1C->getZExtValue() >= BitSize)
4620 return DAG.getUNDEF(VT);
4622 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4623 uint64_t ShiftAmt = N1C->getZExtValue();
4625 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4627 DAG.getConstant(ShiftAmt, DL0,
4628 getShiftAmountTy(SmallVT)));
4629 AddToWorklist(SmallShift.getNode());
4630 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4632 return DAG.getNode(ISD::AND, DL, VT,
4633 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4634 DAG.getConstant(Mask, DL, VT));
4638 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4639 // bit, which is unmodified by sra.
4640 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4641 if (N0.getOpcode() == ISD::SRA)
4642 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4645 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4646 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4647 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4648 APInt KnownZero, KnownOne;
4649 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4651 // If any of the input bits are KnownOne, then the input couldn't be all
4652 // zeros, thus the result of the srl will always be zero.
4653 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4655 // If all of the bits input the to ctlz node are known to be zero, then
4656 // the result of the ctlz is "32" and the result of the shift is one.
4657 APInt UnknownBits = ~KnownZero;
4658 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4660 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4661 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4662 // Okay, we know that only that the single bit specified by UnknownBits
4663 // could be set on input to the CTLZ node. If this bit is set, the SRL
4664 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4665 // to an SRL/XOR pair, which is likely to simplify more.
4666 unsigned ShAmt = UnknownBits.countTrailingZeros();
4667 SDValue Op = N0.getOperand(0);
4671 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4672 DAG.getConstant(ShAmt, DL,
4673 getShiftAmountTy(Op.getValueType())));
4674 AddToWorklist(Op.getNode());
4678 return DAG.getNode(ISD::XOR, DL, VT,
4679 Op, DAG.getConstant(1, DL, VT));
4683 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4684 if (N1.getOpcode() == ISD::TRUNCATE &&
4685 N1.getOperand(0).getOpcode() == ISD::AND) {
4686 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4687 if (NewOp1.getNode())
4688 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4691 // fold operands of srl based on knowledge that the low bits are not
4693 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4694 return SDValue(N, 0);
4697 SDValue NewSRL = visitShiftByConstant(N, N1C);
4698 if (NewSRL.getNode())
4702 // Attempt to convert a srl of a load into a narrower zero-extending load.
4703 SDValue NarrowLoad = ReduceLoadWidth(N);
4704 if (NarrowLoad.getNode())
4707 // Here is a common situation. We want to optimize:
4710 // %b = and i32 %a, 2
4711 // %c = srl i32 %b, 1
4712 // brcond i32 %c ...
4718 // %c = setcc eq %b, 0
4721 // However when after the source operand of SRL is optimized into AND, the SRL
4722 // itself may not be optimized further. Look for it and add the BRCOND into
4724 if (N->hasOneUse()) {
4725 SDNode *Use = *N->use_begin();
4726 if (Use->getOpcode() == ISD::BRCOND)
4728 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4729 // Also look pass the truncate.
4730 Use = *Use->use_begin();
4731 if (Use->getOpcode() == ISD::BRCOND)
4739 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4740 SDValue N0 = N->getOperand(0);
4741 EVT VT = N->getValueType(0);
4743 // fold (ctlz c1) -> c2
4744 if (isa<ConstantSDNode>(N0))
4745 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4749 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4750 SDValue N0 = N->getOperand(0);
4751 EVT VT = N->getValueType(0);
4753 // fold (ctlz_zero_undef c1) -> c2
4754 if (isa<ConstantSDNode>(N0))
4755 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4759 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4760 SDValue N0 = N->getOperand(0);
4761 EVT VT = N->getValueType(0);
4763 // fold (cttz c1) -> c2
4764 if (isa<ConstantSDNode>(N0))
4765 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4769 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4770 SDValue N0 = N->getOperand(0);
4771 EVT VT = N->getValueType(0);
4773 // fold (cttz_zero_undef c1) -> c2
4774 if (isa<ConstantSDNode>(N0))
4775 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4779 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4780 SDValue N0 = N->getOperand(0);
4781 EVT VT = N->getValueType(0);
4783 // fold (ctpop c1) -> c2
4784 if (isa<ConstantSDNode>(N0))
4785 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4790 /// \brief Generate Min/Max node
4791 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4792 SDValue True, SDValue False,
4793 ISD::CondCode CC, const TargetLowering &TLI,
4794 SelectionDAG &DAG) {
4795 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4805 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4806 if (TLI.isOperationLegal(Opcode, VT))
4807 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4816 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4817 if (TLI.isOperationLegal(Opcode, VT))
4818 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4826 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4827 SDValue N0 = N->getOperand(0);
4828 SDValue N1 = N->getOperand(1);
4829 SDValue N2 = N->getOperand(2);
4830 EVT VT = N->getValueType(0);
4831 EVT VT0 = N0.getValueType();
4833 // fold (select C, X, X) -> X
4836 // fold (select true, X, Y) -> X
4837 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4838 if (N0C && !N0C->isNullValue())
4840 // fold (select false, X, Y) -> Y
4841 if (N0C && N0C->isNullValue())
4843 // fold (select C, 1, X) -> (or C, X)
4844 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4845 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4846 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4847 // fold (select C, 0, 1) -> (xor C, 1)
4848 // We can't do this reliably if integer based booleans have different contents
4849 // to floating point based booleans. This is because we can't tell whether we
4850 // have an integer-based boolean or a floating-point-based boolean unless we
4851 // can find the SETCC that produced it and inspect its operands. This is
4852 // fairly easy if C is the SETCC node, but it can potentially be
4853 // undiscoverable (or not reasonably discoverable). For example, it could be
4854 // in another basic block or it could require searching a complicated
4856 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4857 if (VT.isInteger() &&
4858 (VT0 == MVT::i1 || (VT0.isInteger() &&
4859 TLI.getBooleanContents(false, false) ==
4860 TLI.getBooleanContents(false, true) &&
4861 TLI.getBooleanContents(false, false) ==
4862 TargetLowering::ZeroOrOneBooleanContent)) &&
4863 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4867 return DAG.getNode(ISD::XOR, DL, VT0,
4868 N0, DAG.getConstant(1, DL, VT0));
4871 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4872 N0, DAG.getConstant(1, DL0, VT0));
4873 AddToWorklist(XORNode.getNode());
4875 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4876 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4878 // fold (select C, 0, X) -> (and (not C), X)
4879 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4880 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4881 AddToWorklist(NOTNode.getNode());
4882 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4884 // fold (select C, X, 1) -> (or (not C), X)
4885 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4886 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4887 AddToWorklist(NOTNode.getNode());
4888 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4890 // fold (select C, X, 0) -> (and C, X)
4891 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4892 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4893 // fold (select X, X, Y) -> (or X, Y)
4894 // fold (select X, 1, Y) -> (or X, Y)
4895 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4896 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4897 // fold (select X, Y, X) -> (and X, Y)
4898 // fold (select X, Y, 0) -> (and X, Y)
4899 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4900 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4902 // If we can fold this based on the true/false value, do so.
4903 if (SimplifySelectOps(N, N1, N2))
4904 return SDValue(N, 0); // Don't revisit N.
4906 // fold selects based on a setcc into other things, such as min/max/abs
4907 if (N0.getOpcode() == ISD::SETCC) {
4908 // select x, y (fcmp lt x, y) -> fminnum x, y
4909 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4911 // This is OK if we don't care about what happens if either operand is a
4915 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4916 // no signed zeros as well as no nans.
4917 const TargetOptions &Options = DAG.getTarget().Options;
4918 if (Options.UnsafeFPMath &&
4919 VT.isFloatingPoint() && N0.hasOneUse() &&
4920 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4921 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4924 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4925 N1, N2, CC, TLI, DAG);
4930 if ((!LegalOperations &&
4931 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4932 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4933 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4934 N0.getOperand(0), N0.getOperand(1),
4935 N1, N2, N0.getOperand(2));
4936 return SimplifySelect(SDLoc(N), N0, N1, N2);
4939 if (VT0 == MVT::i1) {
4940 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4941 // select (and Cond0, Cond1), X, Y
4942 // -> select Cond0, (select Cond1, X, Y), Y
4943 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4944 SDValue Cond0 = N0->getOperand(0);
4945 SDValue Cond1 = N0->getOperand(1);
4946 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4947 N1.getValueType(), Cond1, N1, N2);
4948 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4951 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4952 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4953 SDValue Cond0 = N0->getOperand(0);
4954 SDValue Cond1 = N0->getOperand(1);
4955 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4956 N1.getValueType(), Cond1, N1, N2);
4957 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4962 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4963 if (N1->getOpcode() == ISD::SELECT) {
4964 SDValue N1_0 = N1->getOperand(0);
4965 SDValue N1_1 = N1->getOperand(1);
4966 SDValue N1_2 = N1->getOperand(2);
4967 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4968 // Create the actual and node if we can generate good code for it.
4969 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4970 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4972 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4975 // Otherwise see if we can optimize the "and" to a better pattern.
4976 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4977 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4981 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4982 if (N2->getOpcode() == ISD::SELECT) {
4983 SDValue N2_0 = N2->getOperand(0);
4984 SDValue N2_1 = N2->getOperand(1);
4985 SDValue N2_2 = N2->getOperand(2);
4986 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4987 // Create the actual or node if we can generate good code for it.
4988 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4989 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4991 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4994 // Otherwise see if we can optimize to a better pattern.
4995 if (SDValue Combined = visitORLike(N0, N2_0, N))
4996 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5006 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5009 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5011 // Split the inputs.
5012 SDValue Lo, Hi, LL, LH, RL, RH;
5013 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5014 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5016 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5017 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5019 return std::make_pair(Lo, Hi);
5022 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5023 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5024 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5026 SDValue Cond = N->getOperand(0);
5027 SDValue LHS = N->getOperand(1);
5028 SDValue RHS = N->getOperand(2);
5029 EVT VT = N->getValueType(0);
5030 int NumElems = VT.getVectorNumElements();
5031 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5032 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5033 Cond.getOpcode() == ISD::BUILD_VECTOR);
5035 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5036 // binary ones here.
5037 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5040 // We're sure we have an even number of elements due to the
5041 // concat_vectors we have as arguments to vselect.
5042 // Skip BV elements until we find one that's not an UNDEF
5043 // After we find an UNDEF element, keep looping until we get to half the
5044 // length of the BV and see if all the non-undef nodes are the same.
5045 ConstantSDNode *BottomHalf = nullptr;
5046 for (int i = 0; i < NumElems / 2; ++i) {
5047 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5050 if (BottomHalf == nullptr)
5051 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5052 else if (Cond->getOperand(i).getNode() != BottomHalf)
5056 // Do the same for the second half of the BuildVector
5057 ConstantSDNode *TopHalf = nullptr;
5058 for (int i = NumElems / 2; i < NumElems; ++i) {
5059 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5062 if (TopHalf == nullptr)
5063 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5064 else if (Cond->getOperand(i).getNode() != TopHalf)
5068 assert(TopHalf && BottomHalf &&
5069 "One half of the selector was all UNDEFs and the other was all the "
5070 "same value. This should have been addressed before this function.");
5072 ISD::CONCAT_VECTORS, dl, VT,
5073 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5074 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5077 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5079 if (Level >= AfterLegalizeTypes)
5082 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5083 SDValue Mask = MSC->getMask();
5084 SDValue Data = MSC->getValue();
5087 // If the MSCATTER data type requires splitting and the mask is provided by a
5088 // SETCC, then split both nodes and its operands before legalization. This
5089 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5090 // and enables future optimizations (e.g. min/max pattern matching on X86).
5091 if (Mask.getOpcode() != ISD::SETCC)
5094 // Check if any splitting is required.
5095 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5096 TargetLowering::TypeSplitVector)
5098 SDValue MaskLo, MaskHi, Lo, Hi;
5099 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5102 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5104 SDValue Chain = MSC->getChain();
5106 EVT MemoryVT = MSC->getMemoryVT();
5107 unsigned Alignment = MSC->getOriginalAlignment();
5109 EVT LoMemVT, HiMemVT;
5110 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5112 SDValue DataLo, DataHi;
5113 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5115 SDValue BasePtr = MSC->getBasePtr();
5116 SDValue IndexLo, IndexHi;
5117 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5119 MachineMemOperand *MMO = DAG.getMachineFunction().
5120 getMachineMemOperand(MSC->getPointerInfo(),
5121 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5122 Alignment, MSC->getAAInfo(), MSC->getRanges());
5124 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5125 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5128 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5129 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5132 AddToWorklist(Lo.getNode());
5133 AddToWorklist(Hi.getNode());
5135 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5138 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5140 if (Level >= AfterLegalizeTypes)
5143 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5144 SDValue Mask = MST->getMask();
5145 SDValue Data = MST->getValue();
5148 // If the MSTORE data type requires splitting and the mask is provided by a
5149 // SETCC, then split both nodes and its operands before legalization. This
5150 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5151 // and enables future optimizations (e.g. min/max pattern matching on X86).
5152 if (Mask.getOpcode() == ISD::SETCC) {
5154 // Check if any splitting is required.
5155 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5156 TargetLowering::TypeSplitVector)
5159 SDValue MaskLo, MaskHi, Lo, Hi;
5160 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5163 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5165 SDValue Chain = MST->getChain();
5166 SDValue Ptr = MST->getBasePtr();
5168 EVT MemoryVT = MST->getMemoryVT();
5169 unsigned Alignment = MST->getOriginalAlignment();
5171 // if Alignment is equal to the vector size,
5172 // take the half of it for the second part
5173 unsigned SecondHalfAlignment =
5174 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5175 Alignment/2 : Alignment;
5177 EVT LoMemVT, HiMemVT;
5178 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5180 SDValue DataLo, DataHi;
5181 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5183 MachineMemOperand *MMO = DAG.getMachineFunction().
5184 getMachineMemOperand(MST->getPointerInfo(),
5185 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5186 Alignment, MST->getAAInfo(), MST->getRanges());
5188 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5189 MST->isTruncatingStore());
5191 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5192 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5193 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5195 MMO = DAG.getMachineFunction().
5196 getMachineMemOperand(MST->getPointerInfo(),
5197 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5198 SecondHalfAlignment, MST->getAAInfo(),
5201 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5202 MST->isTruncatingStore());
5204 AddToWorklist(Lo.getNode());
5205 AddToWorklist(Hi.getNode());
5207 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5212 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5214 if (Level >= AfterLegalizeTypes)
5217 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5218 SDValue Mask = MGT->getMask();
5221 // If the MGATHER result requires splitting and the mask is provided by a
5222 // SETCC, then split both nodes and its operands before legalization. This
5223 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5224 // and enables future optimizations (e.g. min/max pattern matching on X86).
5226 if (Mask.getOpcode() != ISD::SETCC)
5229 EVT VT = N->getValueType(0);
5231 // Check if any splitting is required.
5232 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5233 TargetLowering::TypeSplitVector)
5236 SDValue MaskLo, MaskHi, Lo, Hi;
5237 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5239 SDValue Src0 = MGT->getValue();
5240 SDValue Src0Lo, Src0Hi;
5241 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5244 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5246 SDValue Chain = MGT->getChain();
5247 EVT MemoryVT = MGT->getMemoryVT();
5248 unsigned Alignment = MGT->getOriginalAlignment();
5250 EVT LoMemVT, HiMemVT;
5251 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5253 SDValue BasePtr = MGT->getBasePtr();
5254 SDValue Index = MGT->getIndex();
5255 SDValue IndexLo, IndexHi;
5256 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5258 MachineMemOperand *MMO = DAG.getMachineFunction().
5259 getMachineMemOperand(MGT->getPointerInfo(),
5260 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5261 Alignment, MGT->getAAInfo(), MGT->getRanges());
5263 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5264 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5267 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5268 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5271 AddToWorklist(Lo.getNode());
5272 AddToWorklist(Hi.getNode());
5274 // Build a factor node to remember that this load is independent of the
5276 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5279 // Legalized the chain result - switch anything that used the old chain to
5281 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5283 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5285 SDValue RetOps[] = { GatherRes, Chain };
5286 return DAG.getMergeValues(RetOps, DL);
5289 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5291 if (Level >= AfterLegalizeTypes)
5294 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5295 SDValue Mask = MLD->getMask();
5298 // If the MLOAD result requires splitting and the mask is provided by a
5299 // SETCC, then split both nodes and its operands before legalization. This
5300 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5301 // and enables future optimizations (e.g. min/max pattern matching on X86).
5303 if (Mask.getOpcode() == ISD::SETCC) {
5304 EVT VT = N->getValueType(0);
5306 // Check if any splitting is required.
5307 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5308 TargetLowering::TypeSplitVector)
5311 SDValue MaskLo, MaskHi, Lo, Hi;
5312 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5314 SDValue Src0 = MLD->getSrc0();
5315 SDValue Src0Lo, Src0Hi;
5316 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5319 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5321 SDValue Chain = MLD->getChain();
5322 SDValue Ptr = MLD->getBasePtr();
5323 EVT MemoryVT = MLD->getMemoryVT();
5324 unsigned Alignment = MLD->getOriginalAlignment();
5326 // if Alignment is equal to the vector size,
5327 // take the half of it for the second part
5328 unsigned SecondHalfAlignment =
5329 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5330 Alignment/2 : Alignment;
5332 EVT LoMemVT, HiMemVT;
5333 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5335 MachineMemOperand *MMO = DAG.getMachineFunction().
5336 getMachineMemOperand(MLD->getPointerInfo(),
5337 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5338 Alignment, MLD->getAAInfo(), MLD->getRanges());
5340 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5343 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5344 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5345 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5347 MMO = DAG.getMachineFunction().
5348 getMachineMemOperand(MLD->getPointerInfo(),
5349 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5350 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5352 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5355 AddToWorklist(Lo.getNode());
5356 AddToWorklist(Hi.getNode());
5358 // Build a factor node to remember that this load is independent of the
5360 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5363 // Legalized the chain result - switch anything that used the old chain to
5365 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5367 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5369 SDValue RetOps[] = { LoadRes, Chain };
5370 return DAG.getMergeValues(RetOps, DL);
5375 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5376 SDValue N0 = N->getOperand(0);
5377 SDValue N1 = N->getOperand(1);
5378 SDValue N2 = N->getOperand(2);
5381 // Canonicalize integer abs.
5382 // vselect (setg[te] X, 0), X, -X ->
5383 // vselect (setgt X, -1), X, -X ->
5384 // vselect (setl[te] X, 0), -X, X ->
5385 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5386 if (N0.getOpcode() == ISD::SETCC) {
5387 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5388 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5390 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5392 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5393 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5394 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5395 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5396 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5397 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5398 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5401 EVT VT = LHS.getValueType();
5402 SDValue Shift = DAG.getNode(
5403 ISD::SRA, DL, VT, LHS,
5404 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5405 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5406 AddToWorklist(Shift.getNode());
5407 AddToWorklist(Add.getNode());
5408 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5412 if (SimplifySelectOps(N, N1, N2))
5413 return SDValue(N, 0); // Don't revisit N.
5415 // If the VSELECT result requires splitting and the mask is provided by a
5416 // SETCC, then split both nodes and its operands before legalization. This
5417 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5418 // and enables future optimizations (e.g. min/max pattern matching on X86).
5419 if (N0.getOpcode() == ISD::SETCC) {
5420 EVT VT = N->getValueType(0);
5422 // Check if any splitting is required.
5423 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5424 TargetLowering::TypeSplitVector)
5427 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5428 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5429 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5430 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5432 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5433 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5435 // Add the new VSELECT nodes to the work list in case they need to be split
5437 AddToWorklist(Lo.getNode());
5438 AddToWorklist(Hi.getNode());
5440 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5443 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5444 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5446 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5447 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5450 // The ConvertSelectToConcatVector function is assuming both the above
5451 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5453 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5454 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5455 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5456 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5464 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5465 SDValue N0 = N->getOperand(0);
5466 SDValue N1 = N->getOperand(1);
5467 SDValue N2 = N->getOperand(2);
5468 SDValue N3 = N->getOperand(3);
5469 SDValue N4 = N->getOperand(4);
5470 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5472 // fold select_cc lhs, rhs, x, x, cc -> x
5476 // Determine if the condition we're dealing with is constant
5477 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5478 N0, N1, CC, SDLoc(N), false);
5479 if (SCC.getNode()) {
5480 AddToWorklist(SCC.getNode());
5482 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5483 if (!SCCC->isNullValue())
5484 return N2; // cond always true -> true val
5486 return N3; // cond always false -> false val
5487 } else if (SCC->getOpcode() == ISD::UNDEF) {
5488 // When the condition is UNDEF, just return the first operand. This is
5489 // coherent the DAG creation, no setcc node is created in this case
5491 } else if (SCC.getOpcode() == ISD::SETCC) {
5492 // Fold to a simpler select_cc
5493 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5494 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5499 // If we can fold this based on the true/false value, do so.
5500 if (SimplifySelectOps(N, N2, N3))
5501 return SDValue(N, 0); // Don't revisit N.
5503 // fold select_cc into other things, such as min/max/abs
5504 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5507 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5508 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5509 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5513 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5514 // dag node into a ConstantSDNode or a build_vector of constants.
5515 // This function is called by the DAGCombiner when visiting sext/zext/aext
5516 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5517 // Vector extends are not folded if operations are legal; this is to
5518 // avoid introducing illegal build_vector dag nodes.
5519 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5520 SelectionDAG &DAG, bool LegalTypes,
5521 bool LegalOperations) {
5522 unsigned Opcode = N->getOpcode();
5523 SDValue N0 = N->getOperand(0);
5524 EVT VT = N->getValueType(0);
5526 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5527 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5529 // fold (sext c1) -> c1
5530 // fold (zext c1) -> c1
5531 // fold (aext c1) -> c1
5532 if (isa<ConstantSDNode>(N0))
5533 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5535 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5536 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5537 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5538 EVT SVT = VT.getScalarType();
5539 if (!(VT.isVector() &&
5540 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5541 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5544 // We can fold this node into a build_vector.
5545 unsigned VTBits = SVT.getSizeInBits();
5546 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5547 unsigned ShAmt = VTBits - EVTBits;
5548 SmallVector<SDValue, 8> Elts;
5549 unsigned NumElts = N0->getNumOperands();
5552 for (unsigned i=0; i != NumElts; ++i) {
5553 SDValue Op = N0->getOperand(i);
5554 if (Op->getOpcode() == ISD::UNDEF) {
5555 Elts.push_back(DAG.getUNDEF(SVT));
5560 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5561 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5562 if (Opcode == ISD::SIGN_EXTEND)
5563 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5566 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5570 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5573 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5574 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5575 // transformation. Returns true if extension are possible and the above
5576 // mentioned transformation is profitable.
5577 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5579 SmallVectorImpl<SDNode *> &ExtendNodes,
5580 const TargetLowering &TLI) {
5581 bool HasCopyToRegUses = false;
5582 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5583 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5584 UE = N0.getNode()->use_end();
5589 if (UI.getUse().getResNo() != N0.getResNo())
5591 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5592 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5593 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5594 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5595 // Sign bits will be lost after a zext.
5598 for (unsigned i = 0; i != 2; ++i) {
5599 SDValue UseOp = User->getOperand(i);
5602 if (!isa<ConstantSDNode>(UseOp))
5607 ExtendNodes.push_back(User);
5610 // If truncates aren't free and there are users we can't
5611 // extend, it isn't worthwhile.
5614 // Remember if this value is live-out.
5615 if (User->getOpcode() == ISD::CopyToReg)
5616 HasCopyToRegUses = true;
5619 if (HasCopyToRegUses) {
5620 bool BothLiveOut = false;
5621 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5623 SDUse &Use = UI.getUse();
5624 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5630 // Both unextended and extended values are live out. There had better be
5631 // a good reason for the transformation.
5632 return ExtendNodes.size();
5637 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5638 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5639 ISD::NodeType ExtType) {
5640 // Extend SetCC uses if necessary.
5641 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5642 SDNode *SetCC = SetCCs[i];
5643 SmallVector<SDValue, 4> Ops;
5645 for (unsigned j = 0; j != 2; ++j) {
5646 SDValue SOp = SetCC->getOperand(j);
5648 Ops.push_back(ExtLoad);
5650 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5653 Ops.push_back(SetCC->getOperand(2));
5654 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5658 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5659 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5660 SDValue N0 = N->getOperand(0);
5661 EVT DstVT = N->getValueType(0);
5662 EVT SrcVT = N0.getValueType();
5664 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5665 N->getOpcode() == ISD::ZERO_EXTEND) &&
5666 "Unexpected node type (not an extend)!");
5668 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5669 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5670 // (v8i32 (sext (v8i16 (load x))))
5672 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5673 // (v4i32 (sextload (x + 16)))))
5674 // Where uses of the original load, i.e.:
5676 // are replaced with:
5678 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5679 // (v4i32 (sextload (x + 16)))))))
5681 // This combine is only applicable to illegal, but splittable, vectors.
5682 // All legal types, and illegal non-vector types, are handled elsewhere.
5683 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5685 if (N0->getOpcode() != ISD::LOAD)
5688 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5690 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5691 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5692 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5695 SmallVector<SDNode *, 4> SetCCs;
5696 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5699 ISD::LoadExtType ExtType =
5700 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5702 // Try to split the vector types to get down to legal types.
5703 EVT SplitSrcVT = SrcVT;
5704 EVT SplitDstVT = DstVT;
5705 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5706 SplitSrcVT.getVectorNumElements() > 1) {
5707 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5708 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5711 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5715 const unsigned NumSplits =
5716 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5717 const unsigned Stride = SplitSrcVT.getStoreSize();
5718 SmallVector<SDValue, 4> Loads;
5719 SmallVector<SDValue, 4> Chains;
5721 SDValue BasePtr = LN0->getBasePtr();
5722 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5723 const unsigned Offset = Idx * Stride;
5724 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5726 SDValue SplitLoad = DAG.getExtLoad(
5727 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5728 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5729 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5730 Align, LN0->getAAInfo());
5732 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5733 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5735 Loads.push_back(SplitLoad.getValue(0));
5736 Chains.push_back(SplitLoad.getValue(1));
5739 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5740 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5742 CombineTo(N, NewValue);
5744 // Replace uses of the original load (before extension)
5745 // with a truncate of the concatenated sextloaded vectors.
5747 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5748 CombineTo(N0.getNode(), Trunc, NewChain);
5749 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5750 (ISD::NodeType)N->getOpcode());
5751 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5754 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5755 SDValue N0 = N->getOperand(0);
5756 EVT VT = N->getValueType(0);
5758 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5760 return SDValue(Res, 0);
5762 // fold (sext (sext x)) -> (sext x)
5763 // fold (sext (aext x)) -> (sext x)
5764 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5765 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5768 if (N0.getOpcode() == ISD::TRUNCATE) {
5769 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5770 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5771 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5772 if (NarrowLoad.getNode()) {
5773 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5774 if (NarrowLoad.getNode() != N0.getNode()) {
5775 CombineTo(N0.getNode(), NarrowLoad);
5776 // CombineTo deleted the truncate, if needed, but not what's under it.
5779 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5782 // See if the value being truncated is already sign extended. If so, just
5783 // eliminate the trunc/sext pair.
5784 SDValue Op = N0.getOperand(0);
5785 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5786 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5787 unsigned DestBits = VT.getScalarType().getSizeInBits();
5788 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5790 if (OpBits == DestBits) {
5791 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5792 // bits, it is already ready.
5793 if (NumSignBits > DestBits-MidBits)
5795 } else if (OpBits < DestBits) {
5796 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5797 // bits, just sext from i32.
5798 if (NumSignBits > OpBits-MidBits)
5799 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5801 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5802 // bits, just truncate to i32.
5803 if (NumSignBits > OpBits-MidBits)
5804 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5807 // fold (sext (truncate x)) -> (sextinreg x).
5808 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5809 N0.getValueType())) {
5810 if (OpBits < DestBits)
5811 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5812 else if (OpBits > DestBits)
5813 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5814 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5815 DAG.getValueType(N0.getValueType()));
5819 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5820 // Only generate vector extloads when 1) they're legal, and 2) they are
5821 // deemed desirable by the target.
5822 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5823 ((!LegalOperations && !VT.isVector() &&
5824 !cast<LoadSDNode>(N0)->isVolatile()) ||
5825 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5826 bool DoXform = true;
5827 SmallVector<SDNode*, 4> SetCCs;
5828 if (!N0.hasOneUse())
5829 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5831 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5833 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5834 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5836 LN0->getBasePtr(), N0.getValueType(),
5837 LN0->getMemOperand());
5838 CombineTo(N, ExtLoad);
5839 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5840 N0.getValueType(), ExtLoad);
5841 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5842 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5844 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5848 // fold (sext (load x)) to multiple smaller sextloads.
5849 // Only on illegal but splittable vectors.
5850 if (SDValue ExtLoad = CombineExtLoad(N))
5853 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5854 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5855 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5856 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5857 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5858 EVT MemVT = LN0->getMemoryVT();
5859 if ((!LegalOperations && !LN0->isVolatile()) ||
5860 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5861 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5863 LN0->getBasePtr(), MemVT,
5864 LN0->getMemOperand());
5865 CombineTo(N, ExtLoad);
5866 CombineTo(N0.getNode(),
5867 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5868 N0.getValueType(), ExtLoad),
5869 ExtLoad.getValue(1));
5870 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5874 // fold (sext (and/or/xor (load x), cst)) ->
5875 // (and/or/xor (sextload x), (sext cst))
5876 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5877 N0.getOpcode() == ISD::XOR) &&
5878 isa<LoadSDNode>(N0.getOperand(0)) &&
5879 N0.getOperand(1).getOpcode() == ISD::Constant &&
5880 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5881 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5882 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5883 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5884 bool DoXform = true;
5885 SmallVector<SDNode*, 4> SetCCs;
5886 if (!N0.hasOneUse())
5887 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5890 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5891 LN0->getChain(), LN0->getBasePtr(),
5893 LN0->getMemOperand());
5894 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5895 Mask = Mask.sext(VT.getSizeInBits());
5897 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5898 ExtLoad, DAG.getConstant(Mask, DL, VT));
5899 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5900 SDLoc(N0.getOperand(0)),
5901 N0.getOperand(0).getValueType(), ExtLoad);
5903 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5904 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5906 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5911 if (N0.getOpcode() == ISD::SETCC) {
5912 EVT N0VT = N0.getOperand(0).getValueType();
5913 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5914 // Only do this before legalize for now.
5915 if (VT.isVector() && !LegalOperations &&
5916 TLI.getBooleanContents(N0VT) ==
5917 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5918 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5919 // of the same size as the compared operands. Only optimize sext(setcc())
5920 // if this is the case.
5921 EVT SVT = getSetCCResultType(N0VT);
5923 // We know that the # elements of the results is the same as the
5924 // # elements of the compare (and the # elements of the compare result
5925 // for that matter). Check to see that they are the same size. If so,
5926 // we know that the element size of the sext'd result matches the
5927 // element size of the compare operands.
5928 if (VT.getSizeInBits() == SVT.getSizeInBits())
5929 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5931 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5933 // If the desired elements are smaller or larger than the source
5934 // elements we can use a matching integer vector type and then
5935 // truncate/sign extend
5936 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5937 if (SVT == MatchingVectorType) {
5938 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5939 N0.getOperand(0), N0.getOperand(1),
5940 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5941 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5945 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5946 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5949 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5951 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5952 NegOne, DAG.getConstant(0, DL, VT),
5953 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5954 if (SCC.getNode()) return SCC;
5956 if (!VT.isVector()) {
5957 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5958 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5960 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5961 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5962 N0.getOperand(0), N0.getOperand(1), CC);
5963 return DAG.getSelect(DL, VT, SetCC,
5964 NegOne, DAG.getConstant(0, DL, VT));
5969 // fold (sext x) -> (zext x) if the sign bit is known zero.
5970 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5971 DAG.SignBitIsZero(N0))
5972 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5977 // isTruncateOf - If N is a truncate of some other value, return true, record
5978 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5979 // This function computes KnownZero to avoid a duplicated call to
5980 // computeKnownBits in the caller.
5981 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5984 if (N->getOpcode() == ISD::TRUNCATE) {
5985 Op = N->getOperand(0);
5986 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5990 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5991 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5994 SDValue Op0 = N->getOperand(0);
5995 SDValue Op1 = N->getOperand(1);
5996 assert(Op0.getValueType() == Op1.getValueType());
5998 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5999 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
6000 if (COp0 && COp0->isNullValue())
6002 else if (COp1 && COp1->isNullValue())
6007 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6009 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6015 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6016 SDValue N0 = N->getOperand(0);
6017 EVT VT = N->getValueType(0);
6019 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6021 return SDValue(Res, 0);
6023 // fold (zext (zext x)) -> (zext x)
6024 // fold (zext (aext x)) -> (zext x)
6025 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6026 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6029 // fold (zext (truncate x)) -> (zext x) or
6030 // (zext (truncate x)) -> (truncate x)
6031 // This is valid when the truncated bits of x are already zero.
6032 // FIXME: We should extend this to work for vectors too.
6035 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6036 APInt TruncatedBits =
6037 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6038 APInt(Op.getValueSizeInBits(), 0) :
6039 APInt::getBitsSet(Op.getValueSizeInBits(),
6040 N0.getValueSizeInBits(),
6041 std::min(Op.getValueSizeInBits(),
6042 VT.getSizeInBits()));
6043 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6044 if (VT.bitsGT(Op.getValueType()))
6045 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6046 if (VT.bitsLT(Op.getValueType()))
6047 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6053 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6054 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6055 if (N0.getOpcode() == ISD::TRUNCATE) {
6056 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6057 if (NarrowLoad.getNode()) {
6058 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6059 if (NarrowLoad.getNode() != N0.getNode()) {
6060 CombineTo(N0.getNode(), NarrowLoad);
6061 // CombineTo deleted the truncate, if needed, but not what's under it.
6064 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6068 // fold (zext (truncate x)) -> (and x, mask)
6069 if (N0.getOpcode() == ISD::TRUNCATE &&
6070 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6072 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6073 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6074 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6075 if (NarrowLoad.getNode()) {
6076 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6077 if (NarrowLoad.getNode() != N0.getNode()) {
6078 CombineTo(N0.getNode(), NarrowLoad);
6079 // CombineTo deleted the truncate, if needed, but not what's under it.
6082 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6085 SDValue Op = N0.getOperand(0);
6086 if (Op.getValueType().bitsLT(VT)) {
6087 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6088 AddToWorklist(Op.getNode());
6089 } else if (Op.getValueType().bitsGT(VT)) {
6090 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6091 AddToWorklist(Op.getNode());
6093 return DAG.getZeroExtendInReg(Op, SDLoc(N),
6094 N0.getValueType().getScalarType());
6097 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6098 // if either of the casts is not free.
6099 if (N0.getOpcode() == ISD::AND &&
6100 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6101 N0.getOperand(1).getOpcode() == ISD::Constant &&
6102 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6103 N0.getValueType()) ||
6104 !TLI.isZExtFree(N0.getValueType(), VT))) {
6105 SDValue X = N0.getOperand(0).getOperand(0);
6106 if (X.getValueType().bitsLT(VT)) {
6107 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6108 } else if (X.getValueType().bitsGT(VT)) {
6109 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6111 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6112 Mask = Mask.zext(VT.getSizeInBits());
6114 return DAG.getNode(ISD::AND, DL, VT,
6115 X, DAG.getConstant(Mask, DL, VT));
6118 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6119 // Only generate vector extloads when 1) they're legal, and 2) they are
6120 // deemed desirable by the target.
6121 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6122 ((!LegalOperations && !VT.isVector() &&
6123 !cast<LoadSDNode>(N0)->isVolatile()) ||
6124 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6125 bool DoXform = true;
6126 SmallVector<SDNode*, 4> SetCCs;
6127 if (!N0.hasOneUse())
6128 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6130 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6132 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6133 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6135 LN0->getBasePtr(), N0.getValueType(),
6136 LN0->getMemOperand());
6137 CombineTo(N, ExtLoad);
6138 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6139 N0.getValueType(), ExtLoad);
6140 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6142 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6144 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6148 // fold (zext (load x)) to multiple smaller zextloads.
6149 // Only on illegal but splittable vectors.
6150 if (SDValue ExtLoad = CombineExtLoad(N))
6153 // fold (zext (and/or/xor (load x), cst)) ->
6154 // (and/or/xor (zextload x), (zext cst))
6155 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6156 N0.getOpcode() == ISD::XOR) &&
6157 isa<LoadSDNode>(N0.getOperand(0)) &&
6158 N0.getOperand(1).getOpcode() == ISD::Constant &&
6159 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6160 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6161 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6162 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6163 bool DoXform = true;
6164 SmallVector<SDNode*, 4> SetCCs;
6165 if (!N0.hasOneUse())
6166 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6169 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6170 LN0->getChain(), LN0->getBasePtr(),
6172 LN0->getMemOperand());
6173 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6174 Mask = Mask.zext(VT.getSizeInBits());
6176 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6177 ExtLoad, DAG.getConstant(Mask, DL, VT));
6178 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6179 SDLoc(N0.getOperand(0)),
6180 N0.getOperand(0).getValueType(), ExtLoad);
6182 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6183 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6185 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6190 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6191 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6192 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6193 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6194 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6195 EVT MemVT = LN0->getMemoryVT();
6196 if ((!LegalOperations && !LN0->isVolatile()) ||
6197 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6198 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6200 LN0->getBasePtr(), MemVT,
6201 LN0->getMemOperand());
6202 CombineTo(N, ExtLoad);
6203 CombineTo(N0.getNode(),
6204 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6206 ExtLoad.getValue(1));
6207 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6211 if (N0.getOpcode() == ISD::SETCC) {
6212 if (!LegalOperations && VT.isVector() &&
6213 N0.getValueType().getVectorElementType() == MVT::i1) {
6214 EVT N0VT = N0.getOperand(0).getValueType();
6215 if (getSetCCResultType(N0VT) == N0.getValueType())
6218 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6219 // Only do this before legalize for now.
6220 EVT EltVT = VT.getVectorElementType();
6222 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6223 DAG.getConstant(1, DL, EltVT));
6224 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6225 // We know that the # elements of the results is the same as the
6226 // # elements of the compare (and the # elements of the compare result
6227 // for that matter). Check to see that they are the same size. If so,
6228 // we know that the element size of the sext'd result matches the
6229 // element size of the compare operands.
6230 return DAG.getNode(ISD::AND, DL, VT,
6231 DAG.getSetCC(DL, VT, N0.getOperand(0),
6233 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6234 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6237 // If the desired elements are smaller or larger than the source
6238 // elements we can use a matching integer vector type and then
6239 // truncate/sign extend
6240 EVT MatchingElementType =
6241 EVT::getIntegerVT(*DAG.getContext(),
6242 N0VT.getScalarType().getSizeInBits());
6243 EVT MatchingVectorType =
6244 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6245 N0VT.getVectorNumElements());
6247 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6249 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6250 return DAG.getNode(ISD::AND, DL, VT,
6251 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6252 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6255 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6258 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6259 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6260 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6261 if (SCC.getNode()) return SCC;
6264 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6265 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6266 isa<ConstantSDNode>(N0.getOperand(1)) &&
6267 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6269 SDValue ShAmt = N0.getOperand(1);
6270 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6271 if (N0.getOpcode() == ISD::SHL) {
6272 SDValue InnerZExt = N0.getOperand(0);
6273 // If the original shl may be shifting out bits, do not perform this
6275 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6276 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6277 if (ShAmtVal > KnownZeroBits)
6283 // Ensure that the shift amount is wide enough for the shifted value.
6284 if (VT.getSizeInBits() >= 256)
6285 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6287 return DAG.getNode(N0.getOpcode(), DL, VT,
6288 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6295 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6296 SDValue N0 = N->getOperand(0);
6297 EVT VT = N->getValueType(0);
6299 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6301 return SDValue(Res, 0);
6303 // fold (aext (aext x)) -> (aext x)
6304 // fold (aext (zext x)) -> (zext x)
6305 // fold (aext (sext x)) -> (sext x)
6306 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6307 N0.getOpcode() == ISD::ZERO_EXTEND ||
6308 N0.getOpcode() == ISD::SIGN_EXTEND)
6309 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6311 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6312 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6313 if (N0.getOpcode() == ISD::TRUNCATE) {
6314 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6315 if (NarrowLoad.getNode()) {
6316 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6317 if (NarrowLoad.getNode() != N0.getNode()) {
6318 CombineTo(N0.getNode(), NarrowLoad);
6319 // CombineTo deleted the truncate, if needed, but not what's under it.
6322 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6326 // fold (aext (truncate x))
6327 if (N0.getOpcode() == ISD::TRUNCATE) {
6328 SDValue TruncOp = N0.getOperand(0);
6329 if (TruncOp.getValueType() == VT)
6330 return TruncOp; // x iff x size == zext size.
6331 if (TruncOp.getValueType().bitsGT(VT))
6332 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6333 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6336 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6337 // if the trunc is not free.
6338 if (N0.getOpcode() == ISD::AND &&
6339 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6340 N0.getOperand(1).getOpcode() == ISD::Constant &&
6341 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6342 N0.getValueType())) {
6343 SDValue X = N0.getOperand(0).getOperand(0);
6344 if (X.getValueType().bitsLT(VT)) {
6345 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6346 } else if (X.getValueType().bitsGT(VT)) {
6347 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6349 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6350 Mask = Mask.zext(VT.getSizeInBits());
6352 return DAG.getNode(ISD::AND, DL, VT,
6353 X, DAG.getConstant(Mask, DL, VT));
6356 // fold (aext (load x)) -> (aext (truncate (extload x)))
6357 // None of the supported targets knows how to perform load and any_ext
6358 // on vectors in one instruction. We only perform this transformation on
6360 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6361 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6362 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6363 bool DoXform = true;
6364 SmallVector<SDNode*, 4> SetCCs;
6365 if (!N0.hasOneUse())
6366 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6368 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6369 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6371 LN0->getBasePtr(), N0.getValueType(),
6372 LN0->getMemOperand());
6373 CombineTo(N, ExtLoad);
6374 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6375 N0.getValueType(), ExtLoad);
6376 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6377 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6379 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6383 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6384 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6385 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6386 if (N0.getOpcode() == ISD::LOAD &&
6387 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6389 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6390 ISD::LoadExtType ExtType = LN0->getExtensionType();
6391 EVT MemVT = LN0->getMemoryVT();
6392 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6393 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6394 VT, LN0->getChain(), LN0->getBasePtr(),
6395 MemVT, LN0->getMemOperand());
6396 CombineTo(N, ExtLoad);
6397 CombineTo(N0.getNode(),
6398 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6399 N0.getValueType(), ExtLoad),
6400 ExtLoad.getValue(1));
6401 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6405 if (N0.getOpcode() == ISD::SETCC) {
6407 // aext(setcc) -> vsetcc
6408 // aext(setcc) -> truncate(vsetcc)
6409 // aext(setcc) -> aext(vsetcc)
6410 // Only do this before legalize for now.
6411 if (VT.isVector() && !LegalOperations) {
6412 EVT N0VT = N0.getOperand(0).getValueType();
6413 // We know that the # elements of the results is the same as the
6414 // # elements of the compare (and the # elements of the compare result
6415 // for that matter). Check to see that they are the same size. If so,
6416 // we know that the element size of the sext'd result matches the
6417 // element size of the compare operands.
6418 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6419 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6421 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6422 // If the desired elements are smaller or larger than the source
6423 // elements we can use a matching integer vector type and then
6424 // truncate/any extend
6426 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6428 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6430 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6431 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6435 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6438 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6439 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6440 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6448 /// See if the specified operand can be simplified with the knowledge that only
6449 /// the bits specified by Mask are used. If so, return the simpler operand,
6450 /// otherwise return a null SDValue.
6451 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6452 switch (V.getOpcode()) {
6454 case ISD::Constant: {
6455 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6456 assert(CV && "Const value should be ConstSDNode.");
6457 const APInt &CVal = CV->getAPIntValue();
6458 APInt NewVal = CVal & Mask;
6460 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6465 // If the LHS or RHS don't contribute bits to the or, drop them.
6466 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6467 return V.getOperand(1);
6468 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6469 return V.getOperand(0);
6472 // Only look at single-use SRLs.
6473 if (!V.getNode()->hasOneUse())
6475 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6476 // See if we can recursively simplify the LHS.
6477 unsigned Amt = RHSC->getZExtValue();
6479 // Watch out for shift count overflow though.
6480 if (Amt >= Mask.getBitWidth()) break;
6481 APInt NewMask = Mask << Amt;
6482 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6483 if (SimplifyLHS.getNode())
6484 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6485 SimplifyLHS, V.getOperand(1));
6491 /// If the result of a wider load is shifted to right of N bits and then
6492 /// truncated to a narrower type and where N is a multiple of number of bits of
6493 /// the narrower type, transform it to a narrower load from address + N / num of
6494 /// bits of new type. If the result is to be extended, also fold the extension
6495 /// to form a extending load.
6496 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6497 unsigned Opc = N->getOpcode();
6499 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6500 SDValue N0 = N->getOperand(0);
6501 EVT VT = N->getValueType(0);
6504 // This transformation isn't valid for vector loads.
6508 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6510 if (Opc == ISD::SIGN_EXTEND_INREG) {
6511 ExtType = ISD::SEXTLOAD;
6512 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6513 } else if (Opc == ISD::SRL) {
6514 // Another special-case: SRL is basically zero-extending a narrower value.
6515 ExtType = ISD::ZEXTLOAD;
6517 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6518 if (!N01) return SDValue();
6519 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6520 VT.getSizeInBits() - N01->getZExtValue());
6522 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6525 unsigned EVTBits = ExtVT.getSizeInBits();
6527 // Do not generate loads of non-round integer types since these can
6528 // be expensive (and would be wrong if the type is not byte sized).
6529 if (!ExtVT.isRound())
6533 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6534 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6535 ShAmt = N01->getZExtValue();
6536 // Is the shift amount a multiple of size of VT?
6537 if ((ShAmt & (EVTBits-1)) == 0) {
6538 N0 = N0.getOperand(0);
6539 // Is the load width a multiple of size of VT?
6540 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6544 // At this point, we must have a load or else we can't do the transform.
6545 if (!isa<LoadSDNode>(N0)) return SDValue();
6547 // Because a SRL must be assumed to *need* to zero-extend the high bits
6548 // (as opposed to anyext the high bits), we can't combine the zextload
6549 // lowering of SRL and an sextload.
6550 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6553 // If the shift amount is larger than the input type then we're not
6554 // accessing any of the loaded bytes. If the load was a zextload/extload
6555 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6556 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6561 // If the load is shifted left (and the result isn't shifted back right),
6562 // we can fold the truncate through the shift.
6563 unsigned ShLeftAmt = 0;
6564 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6565 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6566 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6567 ShLeftAmt = N01->getZExtValue();
6568 N0 = N0.getOperand(0);
6572 // If we haven't found a load, we can't narrow it. Don't transform one with
6573 // multiple uses, this would require adding a new load.
6574 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6577 // Don't change the width of a volatile load.
6578 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6579 if (LN0->isVolatile())
6582 // Verify that we are actually reducing a load width here.
6583 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6586 // For the transform to be legal, the load must produce only two values
6587 // (the value loaded and the chain). Don't transform a pre-increment
6588 // load, for example, which produces an extra value. Otherwise the
6589 // transformation is not equivalent, and the downstream logic to replace
6590 // uses gets things wrong.
6591 if (LN0->getNumValues() > 2)
6594 // If the load that we're shrinking is an extload and we're not just
6595 // discarding the extension we can't simply shrink the load. Bail.
6596 // TODO: It would be possible to merge the extensions in some cases.
6597 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6598 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6601 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6604 EVT PtrType = N0.getOperand(1).getValueType();
6606 if (PtrType == MVT::Untyped || PtrType.isExtended())
6607 // It's not possible to generate a constant of extended or untyped type.
6610 // For big endian targets, we need to adjust the offset to the pointer to
6611 // load the correct bytes.
6612 if (TLI.isBigEndian()) {
6613 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6614 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6615 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6618 uint64_t PtrOff = ShAmt / 8;
6619 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6621 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6622 PtrType, LN0->getBasePtr(),
6623 DAG.getConstant(PtrOff, DL, PtrType));
6624 AddToWorklist(NewPtr.getNode());
6627 if (ExtType == ISD::NON_EXTLOAD)
6628 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6629 LN0->getPointerInfo().getWithOffset(PtrOff),
6630 LN0->isVolatile(), LN0->isNonTemporal(),
6631 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6633 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6634 LN0->getPointerInfo().getWithOffset(PtrOff),
6635 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6636 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6638 // Replace the old load's chain with the new load's chain.
6639 WorklistRemover DeadNodes(*this);
6640 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6642 // Shift the result left, if we've swallowed a left shift.
6643 SDValue Result = Load;
6644 if (ShLeftAmt != 0) {
6645 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6646 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6648 // If the shift amount is as large as the result size (but, presumably,
6649 // no larger than the source) then the useful bits of the result are
6650 // zero; we can't simply return the shortened shift, because the result
6651 // of that operation is undefined.
6653 if (ShLeftAmt >= VT.getSizeInBits())
6654 Result = DAG.getConstant(0, DL, VT);
6656 Result = DAG.getNode(ISD::SHL, DL, VT,
6657 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6660 // Return the new loaded value.
6664 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6665 SDValue N0 = N->getOperand(0);
6666 SDValue N1 = N->getOperand(1);
6667 EVT VT = N->getValueType(0);
6668 EVT EVT = cast<VTSDNode>(N1)->getVT();
6669 unsigned VTBits = VT.getScalarType().getSizeInBits();
6670 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6672 // fold (sext_in_reg c1) -> c1
6673 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6674 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6676 // If the input is already sign extended, just drop the extension.
6677 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6680 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6681 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6682 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6683 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6684 N0.getOperand(0), N1);
6686 // fold (sext_in_reg (sext x)) -> (sext x)
6687 // fold (sext_in_reg (aext x)) -> (sext x)
6688 // if x is small enough.
6689 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6690 SDValue N00 = N0.getOperand(0);
6691 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6692 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6693 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6696 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6697 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6698 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6700 // fold operands of sext_in_reg based on knowledge that the top bits are not
6702 if (SimplifyDemandedBits(SDValue(N, 0)))
6703 return SDValue(N, 0);
6705 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6706 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6707 SDValue NarrowLoad = ReduceLoadWidth(N);
6708 if (NarrowLoad.getNode())
6711 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6712 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6713 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6714 if (N0.getOpcode() == ISD::SRL) {
6715 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6716 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6717 // We can turn this into an SRA iff the input to the SRL is already sign
6719 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6720 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6721 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6722 N0.getOperand(0), N0.getOperand(1));
6726 // fold (sext_inreg (extload x)) -> (sextload x)
6727 if (ISD::isEXTLoad(N0.getNode()) &&
6728 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6729 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6730 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6731 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6732 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6733 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6735 LN0->getBasePtr(), EVT,
6736 LN0->getMemOperand());
6737 CombineTo(N, ExtLoad);
6738 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6739 AddToWorklist(ExtLoad.getNode());
6740 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6742 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6743 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6745 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6746 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6747 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6748 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6749 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6751 LN0->getBasePtr(), EVT,
6752 LN0->getMemOperand());
6753 CombineTo(N, ExtLoad);
6754 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6755 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6758 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6759 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6760 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6761 N0.getOperand(1), false);
6762 if (BSwap.getNode())
6763 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6767 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6768 // into a build_vector.
6769 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6770 SmallVector<SDValue, 8> Elts;
6771 unsigned NumElts = N0->getNumOperands();
6772 unsigned ShAmt = VTBits - EVTBits;
6774 for (unsigned i = 0; i != NumElts; ++i) {
6775 SDValue Op = N0->getOperand(i);
6776 if (Op->getOpcode() == ISD::UNDEF) {
6781 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6782 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6783 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6784 SDLoc(Op), Op.getValueType()));
6787 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6793 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6794 SDValue N0 = N->getOperand(0);
6795 EVT VT = N->getValueType(0);
6796 bool isLE = TLI.isLittleEndian();
6799 if (N0.getValueType() == N->getValueType(0))
6801 // fold (truncate c1) -> c1
6802 if (isConstantIntBuildVectorOrConstantInt(N0))
6803 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6804 // fold (truncate (truncate x)) -> (truncate x)
6805 if (N0.getOpcode() == ISD::TRUNCATE)
6806 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6807 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6808 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6809 N0.getOpcode() == ISD::SIGN_EXTEND ||
6810 N0.getOpcode() == ISD::ANY_EXTEND) {
6811 if (N0.getOperand(0).getValueType().bitsLT(VT))
6812 // if the source is smaller than the dest, we still need an extend
6813 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6815 if (N0.getOperand(0).getValueType().bitsGT(VT))
6816 // if the source is larger than the dest, than we just need the truncate
6817 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6818 // if the source and dest are the same type, we can drop both the extend
6819 // and the truncate.
6820 return N0.getOperand(0);
6823 // Fold extract-and-trunc into a narrow extract. For example:
6824 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6825 // i32 y = TRUNCATE(i64 x)
6827 // v16i8 b = BITCAST (v2i64 val)
6828 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6830 // Note: We only run this optimization after type legalization (which often
6831 // creates this pattern) and before operation legalization after which
6832 // we need to be more careful about the vector instructions that we generate.
6833 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6834 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6836 EVT VecTy = N0.getOperand(0).getValueType();
6837 EVT ExTy = N0.getValueType();
6838 EVT TrTy = N->getValueType(0);
6840 unsigned NumElem = VecTy.getVectorNumElements();
6841 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6843 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6844 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6846 SDValue EltNo = N0->getOperand(1);
6847 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6848 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6849 EVT IndexTy = TLI.getVectorIdxTy();
6850 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6852 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6853 NVT, N0.getOperand(0));
6856 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6858 DAG.getConstant(Index, DL, IndexTy));
6862 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6863 if (N0.getOpcode() == ISD::SELECT) {
6864 EVT SrcVT = N0.getValueType();
6865 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6866 TLI.isTruncateFree(SrcVT, VT)) {
6868 SDValue Cond = N0.getOperand(0);
6869 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6870 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6871 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6875 // Fold a series of buildvector, bitcast, and truncate if possible.
6877 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6878 // (2xi32 (buildvector x, y)).
6879 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6880 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6881 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6882 N0.getOperand(0).hasOneUse()) {
6884 SDValue BuildVect = N0.getOperand(0);
6885 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6886 EVT TruncVecEltTy = VT.getVectorElementType();
6888 // Check that the element types match.
6889 if (BuildVectEltTy == TruncVecEltTy) {
6890 // Now we only need to compute the offset of the truncated elements.
6891 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6892 unsigned TruncVecNumElts = VT.getVectorNumElements();
6893 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6895 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6896 "Invalid number of elements");
6898 SmallVector<SDValue, 8> Opnds;
6899 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6900 Opnds.push_back(BuildVect.getOperand(i));
6902 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6906 // See if we can simplify the input to this truncate through knowledge that
6907 // only the low bits are being used.
6908 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6909 // Currently we only perform this optimization on scalars because vectors
6910 // may have different active low bits.
6911 if (!VT.isVector()) {
6913 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6914 VT.getSizeInBits()));
6915 if (Shorter.getNode())
6916 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6918 // fold (truncate (load x)) -> (smaller load x)
6919 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6920 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6921 SDValue Reduced = ReduceLoadWidth(N);
6922 if (Reduced.getNode())
6924 // Handle the case where the load remains an extending load even
6925 // after truncation.
6926 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6927 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6928 if (!LN0->isVolatile() &&
6929 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6930 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6931 VT, LN0->getChain(), LN0->getBasePtr(),
6933 LN0->getMemOperand());
6934 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6939 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6940 // where ... are all 'undef'.
6941 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6942 SmallVector<EVT, 8> VTs;
6945 unsigned NumDefs = 0;
6947 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6948 SDValue X = N0.getOperand(i);
6949 if (X.getOpcode() != ISD::UNDEF) {
6954 // Stop if more than one members are non-undef.
6957 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6958 VT.getVectorElementType(),
6959 X.getValueType().getVectorNumElements()));
6963 return DAG.getUNDEF(VT);
6966 assert(V.getNode() && "The single defined operand is empty!");
6967 SmallVector<SDValue, 8> Opnds;
6968 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6970 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6973 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6974 AddToWorklist(NV.getNode());
6975 Opnds.push_back(NV);
6977 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6981 // Simplify the operands using demanded-bits information.
6982 if (!VT.isVector() &&
6983 SimplifyDemandedBits(SDValue(N, 0)))
6984 return SDValue(N, 0);
6989 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6990 SDValue Elt = N->getOperand(i);
6991 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6992 return Elt.getNode();
6993 return Elt.getOperand(Elt.getResNo()).getNode();
6996 /// build_pair (load, load) -> load
6997 /// if load locations are consecutive.
6998 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6999 assert(N->getOpcode() == ISD::BUILD_PAIR);
7001 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7002 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7003 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7004 LD1->getAddressSpace() != LD2->getAddressSpace())
7006 EVT LD1VT = LD1->getValueType(0);
7008 if (ISD::isNON_EXTLoad(LD2) &&
7010 // If both are volatile this would reduce the number of volatile loads.
7011 // If one is volatile it might be ok, but play conservative and bail out.
7012 !LD1->isVolatile() &&
7013 !LD2->isVolatile() &&
7014 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7015 unsigned Align = LD1->getAlignment();
7016 unsigned NewAlign = TLI.getDataLayout()->
7017 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7019 if (NewAlign <= Align &&
7020 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7021 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7022 LD1->getBasePtr(), LD1->getPointerInfo(),
7023 false, false, false, Align);
7029 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7030 SDValue N0 = N->getOperand(0);
7031 EVT VT = N->getValueType(0);
7033 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7034 // Only do this before legalize, since afterward the target may be depending
7035 // on the bitconvert.
7036 // First check to see if this is all constant.
7038 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7040 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7042 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7043 assert(!DestEltVT.isVector() &&
7044 "Element type of vector ValueType must not be vector!");
7046 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7049 // If the input is a constant, let getNode fold it.
7050 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7051 // If we can't allow illegal operations, we need to check that this is just
7052 // a fp -> int or int -> conversion and that the resulting operation will
7054 if (!LegalOperations ||
7055 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7056 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7057 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7058 TLI.isOperationLegal(ISD::Constant, VT)))
7059 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7062 // (conv (conv x, t1), t2) -> (conv x, t2)
7063 if (N0.getOpcode() == ISD::BITCAST)
7064 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7067 // fold (conv (load x)) -> (load (conv*)x)
7068 // If the resultant load doesn't need a higher alignment than the original!
7069 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7070 // Do not change the width of a volatile load.
7071 !cast<LoadSDNode>(N0)->isVolatile() &&
7072 // Do not remove the cast if the types differ in endian layout.
7073 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7074 TLI.hasBigEndianPartOrdering(VT) &&
7075 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7076 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7077 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7078 unsigned Align = TLI.getDataLayout()->
7079 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7080 unsigned OrigAlign = LN0->getAlignment();
7082 if (Align <= OrigAlign) {
7083 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7084 LN0->getBasePtr(), LN0->getPointerInfo(),
7085 LN0->isVolatile(), LN0->isNonTemporal(),
7086 LN0->isInvariant(), OrigAlign,
7088 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7093 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7094 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7095 // This often reduces constant pool loads.
7096 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7097 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7098 N0.getNode()->hasOneUse() && VT.isInteger() &&
7099 !VT.isVector() && !N0.getValueType().isVector()) {
7100 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7102 AddToWorklist(NewConv.getNode());
7105 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7106 if (N0.getOpcode() == ISD::FNEG)
7107 return DAG.getNode(ISD::XOR, DL, VT,
7108 NewConv, DAG.getConstant(SignBit, DL, VT));
7109 assert(N0.getOpcode() == ISD::FABS);
7110 return DAG.getNode(ISD::AND, DL, VT,
7111 NewConv, DAG.getConstant(~SignBit, DL, VT));
7114 // fold (bitconvert (fcopysign cst, x)) ->
7115 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7116 // Note that we don't handle (copysign x, cst) because this can always be
7117 // folded to an fneg or fabs.
7118 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7119 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7120 VT.isInteger() && !VT.isVector()) {
7121 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7122 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7123 if (isTypeLegal(IntXVT)) {
7124 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7125 IntXVT, N0.getOperand(1));
7126 AddToWorklist(X.getNode());
7128 // If X has a different width than the result/lhs, sext it or truncate it.
7129 unsigned VTWidth = VT.getSizeInBits();
7130 if (OrigXWidth < VTWidth) {
7131 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7132 AddToWorklist(X.getNode());
7133 } else if (OrigXWidth > VTWidth) {
7134 // To get the sign bit in the right place, we have to shift it right
7135 // before truncating.
7137 X = DAG.getNode(ISD::SRL, DL,
7138 X.getValueType(), X,
7139 DAG.getConstant(OrigXWidth-VTWidth, DL,
7141 AddToWorklist(X.getNode());
7142 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7143 AddToWorklist(X.getNode());
7146 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7147 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7148 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7149 AddToWorklist(X.getNode());
7151 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7152 VT, N0.getOperand(0));
7153 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7154 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7155 AddToWorklist(Cst.getNode());
7157 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7161 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7162 if (N0.getOpcode() == ISD::BUILD_PAIR) {
7163 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7164 if (CombineLD.getNode())
7168 // Remove double bitcasts from shuffles - this is often a legacy of
7169 // XformToShuffleWithZero being used to combine bitmaskings (of
7170 // float vectors bitcast to integer vectors) into shuffles.
7171 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7172 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7173 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7174 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7175 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7176 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7178 // If operands are a bitcast, peek through if it casts the original VT.
7179 // If operands are a UNDEF or constant, just bitcast back to original VT.
7180 auto PeekThroughBitcast = [&](SDValue Op) {
7181 if (Op.getOpcode() == ISD::BITCAST &&
7182 Op.getOperand(0)->getValueType(0) == VT)
7183 return SDValue(Op.getOperand(0));
7184 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7185 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7186 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7190 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7191 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7196 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7197 SmallVector<int, 8> NewMask;
7198 for (int M : SVN->getMask())
7199 for (int i = 0; i != MaskScale; ++i)
7200 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7202 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7204 std::swap(SV0, SV1);
7205 ShuffleVectorSDNode::commuteMask(NewMask);
7206 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7210 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7216 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7217 EVT VT = N->getValueType(0);
7218 return CombineConsecutiveLoads(N, VT);
7221 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7222 /// operands. DstEltVT indicates the destination element value type.
7223 SDValue DAGCombiner::
7224 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7225 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7227 // If this is already the right type, we're done.
7228 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7230 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7231 unsigned DstBitSize = DstEltVT.getSizeInBits();
7233 // If this is a conversion of N elements of one type to N elements of another
7234 // type, convert each element. This handles FP<->INT cases.
7235 if (SrcBitSize == DstBitSize) {
7236 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7237 BV->getValueType(0).getVectorNumElements());
7239 // Due to the FP element handling below calling this routine recursively,
7240 // we can end up with a scalar-to-vector node here.
7241 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7242 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7243 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7244 DstEltVT, BV->getOperand(0)));
7246 SmallVector<SDValue, 8> Ops;
7247 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7248 SDValue Op = BV->getOperand(i);
7249 // If the vector element type is not legal, the BUILD_VECTOR operands
7250 // are promoted and implicitly truncated. Make that explicit here.
7251 if (Op.getValueType() != SrcEltVT)
7252 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7253 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7255 AddToWorklist(Ops.back().getNode());
7257 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7260 // Otherwise, we're growing or shrinking the elements. To avoid having to
7261 // handle annoying details of growing/shrinking FP values, we convert them to
7263 if (SrcEltVT.isFloatingPoint()) {
7264 // Convert the input float vector to a int vector where the elements are the
7266 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7267 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7271 // Now we know the input is an integer vector. If the output is a FP type,
7272 // convert to integer first, then to FP of the right size.
7273 if (DstEltVT.isFloatingPoint()) {
7274 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7275 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7277 // Next, convert to FP elements of the same size.
7278 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7283 // Okay, we know the src/dst types are both integers of differing types.
7284 // Handling growing first.
7285 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7286 if (SrcBitSize < DstBitSize) {
7287 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7289 SmallVector<SDValue, 8> Ops;
7290 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7291 i += NumInputsPerOutput) {
7292 bool isLE = TLI.isLittleEndian();
7293 APInt NewBits = APInt(DstBitSize, 0);
7294 bool EltIsUndef = true;
7295 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7296 // Shift the previously computed bits over.
7297 NewBits <<= SrcBitSize;
7298 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7299 if (Op.getOpcode() == ISD::UNDEF) continue;
7302 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7303 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7307 Ops.push_back(DAG.getUNDEF(DstEltVT));
7309 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7312 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7313 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7316 // Finally, this must be the case where we are shrinking elements: each input
7317 // turns into multiple outputs.
7318 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7319 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7320 NumOutputsPerInput*BV->getNumOperands());
7321 SmallVector<SDValue, 8> Ops;
7323 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7324 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7325 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7329 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7330 getAPIntValue().zextOrTrunc(SrcBitSize);
7332 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7333 APInt ThisVal = OpVal.trunc(DstBitSize);
7334 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7335 OpVal = OpVal.lshr(DstBitSize);
7338 // For big endian targets, swap the order of the pieces of each element.
7339 if (TLI.isBigEndian())
7340 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7343 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7346 /// Try to perform FMA combining on a given FADD node.
7347 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7348 SDValue N0 = N->getOperand(0);
7349 SDValue N1 = N->getOperand(1);
7350 EVT VT = N->getValueType(0);
7353 const TargetOptions &Options = DAG.getTarget().Options;
7354 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7355 Options.UnsafeFPMath);
7357 // Floating-point multiply-add with intermediate rounding.
7358 bool HasFMAD = (LegalOperations &&
7359 TLI.isOperationLegal(ISD::FMAD, VT));
7361 // Floating-point multiply-add without intermediate rounding.
7362 bool HasFMA = ((!LegalOperations ||
7363 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7364 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7367 // No valid opcode, do not combine.
7368 if (!HasFMAD && !HasFMA)
7371 // Always prefer FMAD to FMA for precision.
7372 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7373 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7374 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7376 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7377 if (N0.getOpcode() == ISD::FMUL &&
7378 (Aggressive || N0->hasOneUse())) {
7379 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7380 N0.getOperand(0), N0.getOperand(1), N1);
7383 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7384 // Note: Commutes FADD operands.
7385 if (N1.getOpcode() == ISD::FMUL &&
7386 (Aggressive || N1->hasOneUse())) {
7387 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7388 N1.getOperand(0), N1.getOperand(1), N0);
7391 // Look through FP_EXTEND nodes to do more combining.
7392 if (UnsafeFPMath && LookThroughFPExt) {
7393 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7394 if (N0.getOpcode() == ISD::FP_EXTEND) {
7395 SDValue N00 = N0.getOperand(0);
7396 if (N00.getOpcode() == ISD::FMUL)
7397 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7398 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7400 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7401 N00.getOperand(1)), N1);
7404 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7405 // Note: Commutes FADD operands.
7406 if (N1.getOpcode() == ISD::FP_EXTEND) {
7407 SDValue N10 = N1.getOperand(0);
7408 if (N10.getOpcode() == ISD::FMUL)
7409 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7410 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7412 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7413 N10.getOperand(1)), N0);
7417 // More folding opportunities when target permits.
7418 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7419 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7420 if (N0.getOpcode() == PreferredFusedOpcode &&
7421 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7422 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7423 N0.getOperand(0), N0.getOperand(1),
7424 DAG.getNode(PreferredFusedOpcode, SL, VT,
7425 N0.getOperand(2).getOperand(0),
7426 N0.getOperand(2).getOperand(1),
7430 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7431 if (N1->getOpcode() == PreferredFusedOpcode &&
7432 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7433 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7434 N1.getOperand(0), N1.getOperand(1),
7435 DAG.getNode(PreferredFusedOpcode, SL, VT,
7436 N1.getOperand(2).getOperand(0),
7437 N1.getOperand(2).getOperand(1),
7441 if (UnsafeFPMath && LookThroughFPExt) {
7442 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7443 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7444 auto FoldFAddFMAFPExtFMul = [&] (
7445 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7446 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7447 DAG.getNode(PreferredFusedOpcode, SL, VT,
7448 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7449 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7452 if (N0.getOpcode() == PreferredFusedOpcode) {
7453 SDValue N02 = N0.getOperand(2);
7454 if (N02.getOpcode() == ISD::FP_EXTEND) {
7455 SDValue N020 = N02.getOperand(0);
7456 if (N020.getOpcode() == ISD::FMUL)
7457 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7458 N020.getOperand(0), N020.getOperand(1),
7463 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7464 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7465 // FIXME: This turns two single-precision and one double-precision
7466 // operation into two double-precision operations, which might not be
7467 // interesting for all targets, especially GPUs.
7468 auto FoldFAddFPExtFMAFMul = [&] (
7469 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7470 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7471 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7472 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7473 DAG.getNode(PreferredFusedOpcode, SL, VT,
7474 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7475 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7478 if (N0.getOpcode() == ISD::FP_EXTEND) {
7479 SDValue N00 = N0.getOperand(0);
7480 if (N00.getOpcode() == PreferredFusedOpcode) {
7481 SDValue N002 = N00.getOperand(2);
7482 if (N002.getOpcode() == ISD::FMUL)
7483 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7484 N002.getOperand(0), N002.getOperand(1),
7489 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7490 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7491 if (N1.getOpcode() == PreferredFusedOpcode) {
7492 SDValue N12 = N1.getOperand(2);
7493 if (N12.getOpcode() == ISD::FP_EXTEND) {
7494 SDValue N120 = N12.getOperand(0);
7495 if (N120.getOpcode() == ISD::FMUL)
7496 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7497 N120.getOperand(0), N120.getOperand(1),
7502 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7503 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7504 // FIXME: This turns two single-precision and one double-precision
7505 // operation into two double-precision operations, which might not be
7506 // interesting for all targets, especially GPUs.
7507 if (N1.getOpcode() == ISD::FP_EXTEND) {
7508 SDValue N10 = N1.getOperand(0);
7509 if (N10.getOpcode() == PreferredFusedOpcode) {
7510 SDValue N102 = N10.getOperand(2);
7511 if (N102.getOpcode() == ISD::FMUL)
7512 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7513 N102.getOperand(0), N102.getOperand(1),
7523 /// Try to perform FMA combining on a given FSUB node.
7524 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7525 SDValue N0 = N->getOperand(0);
7526 SDValue N1 = N->getOperand(1);
7527 EVT VT = N->getValueType(0);
7530 const TargetOptions &Options = DAG.getTarget().Options;
7531 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7532 Options.UnsafeFPMath);
7534 // Floating-point multiply-add with intermediate rounding.
7535 bool HasFMAD = (LegalOperations &&
7536 TLI.isOperationLegal(ISD::FMAD, VT));
7538 // Floating-point multiply-add without intermediate rounding.
7539 bool HasFMA = ((!LegalOperations ||
7540 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7541 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7544 // No valid opcode, do not combine.
7545 if (!HasFMAD && !HasFMA)
7548 // Always prefer FMAD to FMA for precision.
7549 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7550 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7551 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7553 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7554 if (N0.getOpcode() == ISD::FMUL &&
7555 (Aggressive || N0->hasOneUse())) {
7556 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7557 N0.getOperand(0), N0.getOperand(1),
7558 DAG.getNode(ISD::FNEG, SL, VT, N1));
7561 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7562 // Note: Commutes FSUB operands.
7563 if (N1.getOpcode() == ISD::FMUL &&
7564 (Aggressive || N1->hasOneUse()))
7565 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7566 DAG.getNode(ISD::FNEG, SL, VT,
7568 N1.getOperand(1), N0);
7570 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7571 if (N0.getOpcode() == ISD::FNEG &&
7572 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7573 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7574 SDValue N00 = N0.getOperand(0).getOperand(0);
7575 SDValue N01 = N0.getOperand(0).getOperand(1);
7576 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7577 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7578 DAG.getNode(ISD::FNEG, SL, VT, N1));
7581 // Look through FP_EXTEND nodes to do more combining.
7582 if (UnsafeFPMath && LookThroughFPExt) {
7583 // fold (fsub (fpext (fmul x, y)), z)
7584 // -> (fma (fpext x), (fpext y), (fneg z))
7585 if (N0.getOpcode() == ISD::FP_EXTEND) {
7586 SDValue N00 = N0.getOperand(0);
7587 if (N00.getOpcode() == ISD::FMUL)
7588 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7589 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7591 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7593 DAG.getNode(ISD::FNEG, SL, VT, N1));
7596 // fold (fsub x, (fpext (fmul y, z)))
7597 // -> (fma (fneg (fpext y)), (fpext z), x)
7598 // Note: Commutes FSUB operands.
7599 if (N1.getOpcode() == ISD::FP_EXTEND) {
7600 SDValue N10 = N1.getOperand(0);
7601 if (N10.getOpcode() == ISD::FMUL)
7602 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7603 DAG.getNode(ISD::FNEG, SL, VT,
7604 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7605 N10.getOperand(0))),
7606 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7611 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7612 // -> (fneg (fma (fpext x), (fpext y), z))
7613 // Note: This could be removed with appropriate canonicalization of the
7614 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7615 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7616 // from implementing the canonicalization in visitFSUB.
7617 if (N0.getOpcode() == ISD::FP_EXTEND) {
7618 SDValue N00 = N0.getOperand(0);
7619 if (N00.getOpcode() == ISD::FNEG) {
7620 SDValue N000 = N00.getOperand(0);
7621 if (N000.getOpcode() == ISD::FMUL) {
7622 return DAG.getNode(ISD::FNEG, SL, VT,
7623 DAG.getNode(PreferredFusedOpcode, SL, VT,
7624 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7625 N000.getOperand(0)),
7626 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7627 N000.getOperand(1)),
7633 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7634 // -> (fneg (fma (fpext x)), (fpext y), z)
7635 // Note: This could be removed with appropriate canonicalization of the
7636 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7637 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7638 // from implementing the canonicalization in visitFSUB.
7639 if (N0.getOpcode() == ISD::FNEG) {
7640 SDValue N00 = N0.getOperand(0);
7641 if (N00.getOpcode() == ISD::FP_EXTEND) {
7642 SDValue N000 = N00.getOperand(0);
7643 if (N000.getOpcode() == ISD::FMUL) {
7644 return DAG.getNode(ISD::FNEG, SL, VT,
7645 DAG.getNode(PreferredFusedOpcode, SL, VT,
7646 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7647 N000.getOperand(0)),
7648 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7649 N000.getOperand(1)),
7657 // More folding opportunities when target permits.
7658 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7659 // fold (fsub (fma x, y, (fmul u, v)), z)
7660 // -> (fma x, y (fma u, v, (fneg z)))
7661 if (N0.getOpcode() == PreferredFusedOpcode &&
7662 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7663 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7664 N0.getOperand(0), N0.getOperand(1),
7665 DAG.getNode(PreferredFusedOpcode, SL, VT,
7666 N0.getOperand(2).getOperand(0),
7667 N0.getOperand(2).getOperand(1),
7668 DAG.getNode(ISD::FNEG, SL, VT,
7672 // fold (fsub x, (fma y, z, (fmul u, v)))
7673 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7674 if (N1.getOpcode() == PreferredFusedOpcode &&
7675 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7676 SDValue N20 = N1.getOperand(2).getOperand(0);
7677 SDValue N21 = N1.getOperand(2).getOperand(1);
7678 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7679 DAG.getNode(ISD::FNEG, SL, VT,
7682 DAG.getNode(PreferredFusedOpcode, SL, VT,
7683 DAG.getNode(ISD::FNEG, SL, VT, N20),
7688 if (UnsafeFPMath && LookThroughFPExt) {
7689 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7690 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7691 if (N0.getOpcode() == PreferredFusedOpcode) {
7692 SDValue N02 = N0.getOperand(2);
7693 if (N02.getOpcode() == ISD::FP_EXTEND) {
7694 SDValue N020 = N02.getOperand(0);
7695 if (N020.getOpcode() == ISD::FMUL)
7696 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7697 N0.getOperand(0), N0.getOperand(1),
7698 DAG.getNode(PreferredFusedOpcode, SL, VT,
7699 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7700 N020.getOperand(0)),
7701 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7702 N020.getOperand(1)),
7703 DAG.getNode(ISD::FNEG, SL, VT,
7708 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7709 // -> (fma (fpext x), (fpext y),
7710 // (fma (fpext u), (fpext v), (fneg z)))
7711 // FIXME: This turns two single-precision and one double-precision
7712 // operation into two double-precision operations, which might not be
7713 // interesting for all targets, especially GPUs.
7714 if (N0.getOpcode() == ISD::FP_EXTEND) {
7715 SDValue N00 = N0.getOperand(0);
7716 if (N00.getOpcode() == PreferredFusedOpcode) {
7717 SDValue N002 = N00.getOperand(2);
7718 if (N002.getOpcode() == ISD::FMUL)
7719 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7720 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7722 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7724 DAG.getNode(PreferredFusedOpcode, SL, VT,
7725 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7726 N002.getOperand(0)),
7727 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7728 N002.getOperand(1)),
7729 DAG.getNode(ISD::FNEG, SL, VT,
7734 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7735 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7736 if (N1.getOpcode() == PreferredFusedOpcode &&
7737 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7738 SDValue N120 = N1.getOperand(2).getOperand(0);
7739 if (N120.getOpcode() == ISD::FMUL) {
7740 SDValue N1200 = N120.getOperand(0);
7741 SDValue N1201 = N120.getOperand(1);
7742 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7743 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7745 DAG.getNode(PreferredFusedOpcode, SL, VT,
7746 DAG.getNode(ISD::FNEG, SL, VT,
7747 DAG.getNode(ISD::FP_EXTEND, SL,
7749 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7755 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7756 // -> (fma (fneg (fpext y)), (fpext z),
7757 // (fma (fneg (fpext u)), (fpext v), x))
7758 // FIXME: This turns two single-precision and one double-precision
7759 // operation into two double-precision operations, which might not be
7760 // interesting for all targets, especially GPUs.
7761 if (N1.getOpcode() == ISD::FP_EXTEND &&
7762 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7763 SDValue N100 = N1.getOperand(0).getOperand(0);
7764 SDValue N101 = N1.getOperand(0).getOperand(1);
7765 SDValue N102 = N1.getOperand(0).getOperand(2);
7766 if (N102.getOpcode() == ISD::FMUL) {
7767 SDValue N1020 = N102.getOperand(0);
7768 SDValue N1021 = N102.getOperand(1);
7769 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7770 DAG.getNode(ISD::FNEG, SL, VT,
7771 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7773 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7774 DAG.getNode(PreferredFusedOpcode, SL, VT,
7775 DAG.getNode(ISD::FNEG, SL, VT,
7776 DAG.getNode(ISD::FP_EXTEND, SL,
7778 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7789 SDValue DAGCombiner::visitFADD(SDNode *N) {
7790 SDValue N0 = N->getOperand(0);
7791 SDValue N1 = N->getOperand(1);
7792 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7793 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7794 EVT VT = N->getValueType(0);
7796 const TargetOptions &Options = DAG.getTarget().Options;
7800 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7803 // fold (fadd c1, c2) -> c1 + c2
7805 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7807 // canonicalize constant to RHS
7808 if (N0CFP && !N1CFP)
7809 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7811 // fold (fadd A, (fneg B)) -> (fsub A, B)
7812 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7813 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7814 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7815 GetNegatedExpression(N1, DAG, LegalOperations));
7817 // fold (fadd (fneg A), B) -> (fsub B, A)
7818 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7819 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7820 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7821 GetNegatedExpression(N0, DAG, LegalOperations));
7823 // If 'unsafe math' is enabled, fold lots of things.
7824 if (Options.UnsafeFPMath) {
7825 // No FP constant should be created after legalization as Instruction
7826 // Selection pass has a hard time dealing with FP constants.
7827 bool AllowNewConst = (Level < AfterLegalizeDAG);
7829 // fold (fadd A, 0) -> A
7830 if (N1CFP && N1CFP->getValueAPF().isZero())
7833 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7834 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7835 isa<ConstantFPSDNode>(N0.getOperand(1)))
7836 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7837 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7839 // If allowed, fold (fadd (fneg x), x) -> 0.0
7840 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7841 return DAG.getConstantFP(0.0, DL, VT);
7843 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7844 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7845 return DAG.getConstantFP(0.0, DL, VT);
7847 // We can fold chains of FADD's of the same value into multiplications.
7848 // This transform is not safe in general because we are reducing the number
7849 // of rounding steps.
7850 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7851 if (N0.getOpcode() == ISD::FMUL) {
7852 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7853 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7855 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7856 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7857 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7858 DAG.getConstantFP(1.0, DL, VT));
7859 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7862 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7863 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7864 N1.getOperand(0) == N1.getOperand(1) &&
7865 N0.getOperand(0) == N1.getOperand(0)) {
7866 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7867 DAG.getConstantFP(2.0, DL, VT));
7868 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7872 if (N1.getOpcode() == ISD::FMUL) {
7873 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7874 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7876 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7877 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7878 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7879 DAG.getConstantFP(1.0, DL, VT));
7880 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7883 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7884 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7885 N0.getOperand(0) == N0.getOperand(1) &&
7886 N1.getOperand(0) == N0.getOperand(0)) {
7887 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7888 DAG.getConstantFP(2.0, DL, VT));
7889 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7893 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7894 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7895 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7896 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7897 (N0.getOperand(0) == N1)) {
7898 return DAG.getNode(ISD::FMUL, DL, VT,
7899 N1, DAG.getConstantFP(3.0, DL, VT));
7903 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7904 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7905 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7906 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7907 N1.getOperand(0) == N0) {
7908 return DAG.getNode(ISD::FMUL, DL, VT,
7909 N0, DAG.getConstantFP(3.0, DL, VT));
7913 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7914 if (AllowNewConst &&
7915 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7916 N0.getOperand(0) == N0.getOperand(1) &&
7917 N1.getOperand(0) == N1.getOperand(1) &&
7918 N0.getOperand(0) == N1.getOperand(0)) {
7919 return DAG.getNode(ISD::FMUL, DL, VT,
7920 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7923 } // enable-unsafe-fp-math
7925 // FADD -> FMA combines:
7926 SDValue Fused = visitFADDForFMACombine(N);
7928 AddToWorklist(Fused.getNode());
7935 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7936 SDValue N0 = N->getOperand(0);
7937 SDValue N1 = N->getOperand(1);
7938 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7939 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7940 EVT VT = N->getValueType(0);
7942 const TargetOptions &Options = DAG.getTarget().Options;
7946 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7949 // fold (fsub c1, c2) -> c1-c2
7951 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7953 // fold (fsub A, (fneg B)) -> (fadd A, B)
7954 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7955 return DAG.getNode(ISD::FADD, dl, VT, N0,
7956 GetNegatedExpression(N1, DAG, LegalOperations));
7958 // If 'unsafe math' is enabled, fold lots of things.
7959 if (Options.UnsafeFPMath) {
7961 if (N1CFP && N1CFP->getValueAPF().isZero())
7964 // (fsub 0, B) -> -B
7965 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7966 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7967 return GetNegatedExpression(N1, DAG, LegalOperations);
7968 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7969 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7972 // (fsub x, x) -> 0.0
7974 return DAG.getConstantFP(0.0f, dl, VT);
7976 // (fsub x, (fadd x, y)) -> (fneg y)
7977 // (fsub x, (fadd y, x)) -> (fneg y)
7978 if (N1.getOpcode() == ISD::FADD) {
7979 SDValue N10 = N1->getOperand(0);
7980 SDValue N11 = N1->getOperand(1);
7982 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7983 return GetNegatedExpression(N11, DAG, LegalOperations);
7985 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7986 return GetNegatedExpression(N10, DAG, LegalOperations);
7990 // FSUB -> FMA combines:
7991 SDValue Fused = visitFSUBForFMACombine(N);
7993 AddToWorklist(Fused.getNode());
8000 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8001 SDValue N0 = N->getOperand(0);
8002 SDValue N1 = N->getOperand(1);
8003 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8004 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8005 EVT VT = N->getValueType(0);
8007 const TargetOptions &Options = DAG.getTarget().Options;
8010 if (VT.isVector()) {
8011 // This just handles C1 * C2 for vectors. Other vector folds are below.
8012 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8016 // fold (fmul c1, c2) -> c1*c2
8018 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8020 // canonicalize constant to RHS
8021 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8022 !isConstantFPBuildVectorOrConstantFP(N1))
8023 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8025 // fold (fmul A, 1.0) -> A
8026 if (N1CFP && N1CFP->isExactlyValue(1.0))
8029 if (Options.UnsafeFPMath) {
8030 // fold (fmul A, 0) -> 0
8031 if (N1CFP && N1CFP->getValueAPF().isZero())
8034 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8035 if (N0.getOpcode() == ISD::FMUL) {
8036 // Fold scalars or any vector constants (not just splats).
8037 // This fold is done in general by InstCombine, but extra fmul insts
8038 // may have been generated during lowering.
8039 SDValue N00 = N0.getOperand(0);
8040 SDValue N01 = N0.getOperand(1);
8041 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8042 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8043 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8045 // Check 1: Make sure that the first operand of the inner multiply is NOT
8046 // a constant. Otherwise, we may induce infinite looping.
8047 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8048 // Check 2: Make sure that the second operand of the inner multiply and
8049 // the second operand of the outer multiply are constants.
8050 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8051 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8052 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8053 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8058 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8059 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8060 // during an early run of DAGCombiner can prevent folding with fmuls
8061 // inserted during lowering.
8062 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8063 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8064 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8065 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8069 // fold (fmul X, 2.0) -> (fadd X, X)
8070 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8071 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8073 // fold (fmul X, -1.0) -> (fneg X)
8074 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8075 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8076 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8078 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8079 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8080 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8081 // Both can be negated for free, check to see if at least one is cheaper
8083 if (LHSNeg == 2 || RHSNeg == 2)
8084 return DAG.getNode(ISD::FMUL, DL, VT,
8085 GetNegatedExpression(N0, DAG, LegalOperations),
8086 GetNegatedExpression(N1, DAG, LegalOperations));
8093 SDValue DAGCombiner::visitFMA(SDNode *N) {
8094 SDValue N0 = N->getOperand(0);
8095 SDValue N1 = N->getOperand(1);
8096 SDValue N2 = N->getOperand(2);
8097 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8098 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8099 EVT VT = N->getValueType(0);
8101 const TargetOptions &Options = DAG.getTarget().Options;
8103 // Constant fold FMA.
8104 if (isa<ConstantFPSDNode>(N0) &&
8105 isa<ConstantFPSDNode>(N1) &&
8106 isa<ConstantFPSDNode>(N2)) {
8107 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8110 if (Options.UnsafeFPMath) {
8111 if (N0CFP && N0CFP->isZero())
8113 if (N1CFP && N1CFP->isZero())
8116 if (N0CFP && N0CFP->isExactlyValue(1.0))
8117 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8118 if (N1CFP && N1CFP->isExactlyValue(1.0))
8119 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8121 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8122 if (N0CFP && !N1CFP)
8123 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8125 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8126 if (Options.UnsafeFPMath && N1CFP &&
8127 N2.getOpcode() == ISD::FMUL &&
8128 N0 == N2.getOperand(0) &&
8129 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8130 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8131 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8135 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8136 if (Options.UnsafeFPMath &&
8137 N0.getOpcode() == ISD::FMUL && N1CFP &&
8138 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8139 return DAG.getNode(ISD::FMA, dl, VT,
8141 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8145 // (fma x, 1, y) -> (fadd x, y)
8146 // (fma x, -1, y) -> (fadd (fneg x), y)
8148 if (N1CFP->isExactlyValue(1.0))
8149 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8151 if (N1CFP->isExactlyValue(-1.0) &&
8152 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8153 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8154 AddToWorklist(RHSNeg.getNode());
8155 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8159 // (fma x, c, x) -> (fmul x, (c+1))
8160 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8161 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8162 DAG.getNode(ISD::FADD, dl, VT,
8163 N1, DAG.getConstantFP(1.0, dl, VT)));
8165 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8166 if (Options.UnsafeFPMath && N1CFP &&
8167 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8168 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8169 DAG.getNode(ISD::FADD, dl, VT,
8170 N1, DAG.getConstantFP(-1.0, dl, VT)));
8176 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8177 SDValue N0 = N->getOperand(0);
8178 SDValue N1 = N->getOperand(1);
8179 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8180 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8181 EVT VT = N->getValueType(0);
8183 const TargetOptions &Options = DAG.getTarget().Options;
8187 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8190 // fold (fdiv c1, c2) -> c1/c2
8192 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8194 if (Options.UnsafeFPMath) {
8195 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8197 // Compute the reciprocal 1.0 / c2.
8198 APFloat N1APF = N1CFP->getValueAPF();
8199 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8200 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8201 // Only do the transform if the reciprocal is a legal fp immediate that
8202 // isn't too nasty (eg NaN, denormal, ...).
8203 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8204 (!LegalOperations ||
8205 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8206 // backend)... we should handle this gracefully after Legalize.
8207 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8208 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8209 TLI.isFPImmLegal(Recip, VT)))
8210 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8211 DAG.getConstantFP(Recip, DL, VT));
8214 // If this FDIV is part of a reciprocal square root, it may be folded
8215 // into a target-specific square root estimate instruction.
8216 if (N1.getOpcode() == ISD::FSQRT) {
8217 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8218 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8220 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8221 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8222 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8223 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8224 AddToWorklist(RV.getNode());
8225 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8227 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8228 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8229 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8230 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8231 AddToWorklist(RV.getNode());
8232 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8234 } else if (N1.getOpcode() == ISD::FMUL) {
8235 // Look through an FMUL. Even though this won't remove the FDIV directly,
8236 // it's still worthwhile to get rid of the FSQRT if possible.
8239 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8240 SqrtOp = N1.getOperand(0);
8241 OtherOp = N1.getOperand(1);
8242 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8243 SqrtOp = N1.getOperand(1);
8244 OtherOp = N1.getOperand(0);
8246 if (SqrtOp.getNode()) {
8247 // We found a FSQRT, so try to make this fold:
8248 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8249 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8250 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8251 AddToWorklist(RV.getNode());
8252 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8257 // Fold into a reciprocal estimate and multiply instead of a real divide.
8258 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8259 AddToWorklist(RV.getNode());
8260 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8264 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8265 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8266 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8267 // Both can be negated for free, check to see if at least one is cheaper
8269 if (LHSNeg == 2 || RHSNeg == 2)
8270 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8271 GetNegatedExpression(N0, DAG, LegalOperations),
8272 GetNegatedExpression(N1, DAG, LegalOperations));
8276 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8278 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8279 // Notice that this is not always beneficial. One reason is different target
8280 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8281 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8282 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8283 if (Options.UnsafeFPMath) {
8284 // Skip if current node is a reciprocal.
8285 if (N0CFP && N0CFP->isExactlyValue(1.0))
8288 SmallVector<SDNode *, 4> Users;
8289 // Find all FDIV users of the same divisor.
8290 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8291 UE = N1.getNode()->use_end();
8293 SDNode *User = UI.getUse().getUser();
8294 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8295 Users.push_back(User);
8298 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8300 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8301 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8303 // Dividend / Divisor -> Dividend * Reciprocal
8304 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8305 if ((*I)->getOperand(0) != FPOne) {
8306 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8307 (*I)->getOperand(0), Reciprocal);
8308 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8318 SDValue DAGCombiner::visitFREM(SDNode *N) {
8319 SDValue N0 = N->getOperand(0);
8320 SDValue N1 = N->getOperand(1);
8321 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8322 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8323 EVT VT = N->getValueType(0);
8325 // fold (frem c1, c2) -> fmod(c1,c2)
8327 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8332 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8333 if (DAG.getTarget().Options.UnsafeFPMath &&
8334 !TLI.isFsqrtCheap()) {
8335 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8336 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8337 EVT VT = RV.getValueType();
8339 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8340 AddToWorklist(RV.getNode());
8342 // Unfortunately, RV is now NaN if the input was exactly 0.
8343 // Select out this case and force the answer to 0.
8344 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8346 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8347 N->getOperand(0), Zero, ISD::SETEQ);
8348 AddToWorklist(ZeroCmp.getNode());
8349 AddToWorklist(RV.getNode());
8351 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8352 DL, VT, ZeroCmp, Zero, RV);
8359 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8360 SDValue N0 = N->getOperand(0);
8361 SDValue N1 = N->getOperand(1);
8362 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8363 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8364 EVT VT = N->getValueType(0);
8366 if (N0CFP && N1CFP) // Constant fold
8367 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8370 const APFloat& V = N1CFP->getValueAPF();
8371 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8372 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8373 if (!V.isNegative()) {
8374 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8375 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8377 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8378 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8379 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8383 // copysign(fabs(x), y) -> copysign(x, y)
8384 // copysign(fneg(x), y) -> copysign(x, y)
8385 // copysign(copysign(x,z), y) -> copysign(x, y)
8386 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8387 N0.getOpcode() == ISD::FCOPYSIGN)
8388 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8389 N0.getOperand(0), N1);
8391 // copysign(x, abs(y)) -> abs(x)
8392 if (N1.getOpcode() == ISD::FABS)
8393 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8395 // copysign(x, copysign(y,z)) -> copysign(x, z)
8396 if (N1.getOpcode() == ISD::FCOPYSIGN)
8397 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8398 N0, N1.getOperand(1));
8400 // copysign(x, fp_extend(y)) -> copysign(x, y)
8401 // copysign(x, fp_round(y)) -> copysign(x, y)
8402 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8403 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8404 N0, N1.getOperand(0));
8409 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8410 SDValue N0 = N->getOperand(0);
8411 EVT VT = N->getValueType(0);
8412 EVT OpVT = N0.getValueType();
8414 // fold (sint_to_fp c1) -> c1fp
8415 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8416 // ...but only if the target supports immediate floating-point values
8417 (!LegalOperations ||
8418 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8419 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8421 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8422 // but UINT_TO_FP is legal on this target, try to convert.
8423 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8424 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8425 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8426 if (DAG.SignBitIsZero(N0))
8427 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8430 // The next optimizations are desirable only if SELECT_CC can be lowered.
8431 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8432 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8433 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8435 (!LegalOperations ||
8436 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8439 { N0.getOperand(0), N0.getOperand(1),
8440 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8442 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8445 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8446 // (select_cc x, y, 1.0, 0.0,, cc)
8447 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8448 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8449 (!LegalOperations ||
8450 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8453 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8454 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8455 N0.getOperand(0).getOperand(2) };
8456 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8463 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8464 SDValue N0 = N->getOperand(0);
8465 EVT VT = N->getValueType(0);
8466 EVT OpVT = N0.getValueType();
8468 // fold (uint_to_fp c1) -> c1fp
8469 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8470 // ...but only if the target supports immediate floating-point values
8471 (!LegalOperations ||
8472 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8473 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8475 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8476 // but SINT_TO_FP is legal on this target, try to convert.
8477 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8478 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8479 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8480 if (DAG.SignBitIsZero(N0))
8481 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8484 // The next optimizations are desirable only if SELECT_CC can be lowered.
8485 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8486 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8488 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8489 (!LegalOperations ||
8490 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8493 { N0.getOperand(0), N0.getOperand(1),
8494 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8496 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8503 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8504 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8505 SDValue N0 = N->getOperand(0);
8506 EVT VT = N->getValueType(0);
8508 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8511 SDValue Src = N0.getOperand(0);
8512 EVT SrcVT = Src.getValueType();
8513 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8514 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8516 // We can safely assume the conversion won't overflow the output range,
8517 // because (for example) (uint8_t)18293.f is undefined behavior.
8519 // Since we can assume the conversion won't overflow, our decision as to
8520 // whether the input will fit in the float should depend on the minimum
8521 // of the input range and output range.
8523 // This means this is also safe for a signed input and unsigned output, since
8524 // a negative input would lead to undefined behavior.
8525 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8526 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8527 unsigned ActualSize = std::min(InputSize, OutputSize);
8528 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8530 // We can only fold away the float conversion if the input range can be
8531 // represented exactly in the float range.
8532 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8533 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8534 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8536 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8538 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8539 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8542 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8547 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8548 SDValue N0 = N->getOperand(0);
8549 EVT VT = N->getValueType(0);
8551 // fold (fp_to_sint c1fp) -> c1
8552 if (isConstantFPBuildVectorOrConstantFP(N0))
8553 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8555 return FoldIntToFPToInt(N, DAG);
8558 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8559 SDValue N0 = N->getOperand(0);
8560 EVT VT = N->getValueType(0);
8562 // fold (fp_to_uint c1fp) -> c1
8563 if (isConstantFPBuildVectorOrConstantFP(N0))
8564 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8566 return FoldIntToFPToInt(N, DAG);
8569 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8570 SDValue N0 = N->getOperand(0);
8571 SDValue N1 = N->getOperand(1);
8572 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8573 EVT VT = N->getValueType(0);
8575 // fold (fp_round c1fp) -> c1fp
8577 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8579 // fold (fp_round (fp_extend x)) -> x
8580 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8581 return N0.getOperand(0);
8583 // fold (fp_round (fp_round x)) -> (fp_round x)
8584 if (N0.getOpcode() == ISD::FP_ROUND) {
8585 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8586 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8587 // If the first fp_round isn't a value preserving truncation, it might
8588 // introduce a tie in the second fp_round, that wouldn't occur in the
8589 // single-step fp_round we want to fold to.
8590 // In other words, double rounding isn't the same as rounding.
8591 // Also, this is a value preserving truncation iff both fp_round's are.
8592 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8594 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8595 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8599 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8600 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8601 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8602 N0.getOperand(0), N1);
8603 AddToWorklist(Tmp.getNode());
8604 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8605 Tmp, N0.getOperand(1));
8611 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8612 SDValue N0 = N->getOperand(0);
8613 EVT VT = N->getValueType(0);
8614 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8615 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8617 // fold (fp_round_inreg c1fp) -> c1fp
8618 if (N0CFP && isTypeLegal(EVT)) {
8620 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8621 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8627 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8628 SDValue N0 = N->getOperand(0);
8629 EVT VT = N->getValueType(0);
8631 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8632 if (N->hasOneUse() &&
8633 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8636 // fold (fp_extend c1fp) -> c1fp
8637 if (isConstantFPBuildVectorOrConstantFP(N0))
8638 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8640 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8641 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8642 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8643 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8645 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8647 if (N0.getOpcode() == ISD::FP_ROUND
8648 && N0.getNode()->getConstantOperandVal(1) == 1) {
8649 SDValue In = N0.getOperand(0);
8650 if (In.getValueType() == VT) return In;
8651 if (VT.bitsLT(In.getValueType()))
8652 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8653 In, N0.getOperand(1));
8654 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8657 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8658 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8659 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8660 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8661 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8663 LN0->getBasePtr(), N0.getValueType(),
8664 LN0->getMemOperand());
8665 CombineTo(N, ExtLoad);
8666 CombineTo(N0.getNode(),
8667 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8668 N0.getValueType(), ExtLoad,
8669 DAG.getIntPtrConstant(1, SDLoc(N0))),
8670 ExtLoad.getValue(1));
8671 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8677 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8678 SDValue N0 = N->getOperand(0);
8679 EVT VT = N->getValueType(0);
8681 // fold (fceil c1) -> fceil(c1)
8682 if (isConstantFPBuildVectorOrConstantFP(N0))
8683 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8688 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8689 SDValue N0 = N->getOperand(0);
8690 EVT VT = N->getValueType(0);
8692 // fold (ftrunc c1) -> ftrunc(c1)
8693 if (isConstantFPBuildVectorOrConstantFP(N0))
8694 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8699 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8700 SDValue N0 = N->getOperand(0);
8701 EVT VT = N->getValueType(0);
8703 // fold (ffloor c1) -> ffloor(c1)
8704 if (isConstantFPBuildVectorOrConstantFP(N0))
8705 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8710 // FIXME: FNEG and FABS have a lot in common; refactor.
8711 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8712 SDValue N0 = N->getOperand(0);
8713 EVT VT = N->getValueType(0);
8715 // Constant fold FNEG.
8716 if (isConstantFPBuildVectorOrConstantFP(N0))
8717 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8719 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8720 &DAG.getTarget().Options))
8721 return GetNegatedExpression(N0, DAG, LegalOperations);
8723 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8724 // constant pool values.
8725 if (!TLI.isFNegFree(VT) &&
8726 N0.getOpcode() == ISD::BITCAST &&
8727 N0.getNode()->hasOneUse()) {
8728 SDValue Int = N0.getOperand(0);
8729 EVT IntVT = Int.getValueType();
8730 if (IntVT.isInteger() && !IntVT.isVector()) {
8732 if (N0.getValueType().isVector()) {
8733 // For a vector, get a mask such as 0x80... per scalar element
8735 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8736 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8738 // For a scalar, just generate 0x80...
8739 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8742 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8743 DAG.getConstant(SignMask, DL0, IntVT));
8744 AddToWorklist(Int.getNode());
8745 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8749 // (fneg (fmul c, x)) -> (fmul -c, x)
8750 if (N0.getOpcode() == ISD::FMUL) {
8751 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8753 APFloat CVal = CFP1->getValueAPF();
8755 if (Level >= AfterLegalizeDAG &&
8756 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8757 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8759 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8760 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8767 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8768 SDValue N0 = N->getOperand(0);
8769 SDValue N1 = N->getOperand(1);
8770 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8771 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8773 if (N0CFP && N1CFP) {
8774 const APFloat &C0 = N0CFP->getValueAPF();
8775 const APFloat &C1 = N1CFP->getValueAPF();
8776 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8780 EVT VT = N->getValueType(0);
8781 // Canonicalize to constant on RHS.
8782 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8788 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8789 SDValue N0 = N->getOperand(0);
8790 SDValue N1 = N->getOperand(1);
8791 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8792 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8794 if (N0CFP && N1CFP) {
8795 const APFloat &C0 = N0CFP->getValueAPF();
8796 const APFloat &C1 = N1CFP->getValueAPF();
8797 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8801 EVT VT = N->getValueType(0);
8802 // Canonicalize to constant on RHS.
8803 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8809 SDValue DAGCombiner::visitFABS(SDNode *N) {
8810 SDValue N0 = N->getOperand(0);
8811 EVT VT = N->getValueType(0);
8813 // fold (fabs c1) -> fabs(c1)
8814 if (isConstantFPBuildVectorOrConstantFP(N0))
8815 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8817 // fold (fabs (fabs x)) -> (fabs x)
8818 if (N0.getOpcode() == ISD::FABS)
8819 return N->getOperand(0);
8821 // fold (fabs (fneg x)) -> (fabs x)
8822 // fold (fabs (fcopysign x, y)) -> (fabs x)
8823 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8824 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8826 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8827 // constant pool values.
8828 if (!TLI.isFAbsFree(VT) &&
8829 N0.getOpcode() == ISD::BITCAST &&
8830 N0.getNode()->hasOneUse()) {
8831 SDValue Int = N0.getOperand(0);
8832 EVT IntVT = Int.getValueType();
8833 if (IntVT.isInteger() && !IntVT.isVector()) {
8835 if (N0.getValueType().isVector()) {
8836 // For a vector, get a mask such as 0x7f... per scalar element
8838 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8839 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8841 // For a scalar, just generate 0x7f...
8842 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8845 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8846 DAG.getConstant(SignMask, DL, IntVT));
8847 AddToWorklist(Int.getNode());
8848 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8855 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8856 SDValue Chain = N->getOperand(0);
8857 SDValue N1 = N->getOperand(1);
8858 SDValue N2 = N->getOperand(2);
8860 // If N is a constant we could fold this into a fallthrough or unconditional
8861 // branch. However that doesn't happen very often in normal code, because
8862 // Instcombine/SimplifyCFG should have handled the available opportunities.
8863 // If we did this folding here, it would be necessary to update the
8864 // MachineBasicBlock CFG, which is awkward.
8866 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8868 if (N1.getOpcode() == ISD::SETCC &&
8869 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8870 N1.getOperand(0).getValueType())) {
8871 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8872 Chain, N1.getOperand(2),
8873 N1.getOperand(0), N1.getOperand(1), N2);
8876 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8877 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8878 (N1.getOperand(0).hasOneUse() &&
8879 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8880 SDNode *Trunc = nullptr;
8881 if (N1.getOpcode() == ISD::TRUNCATE) {
8882 // Look pass the truncate.
8883 Trunc = N1.getNode();
8884 N1 = N1.getOperand(0);
8887 // Match this pattern so that we can generate simpler code:
8890 // %b = and i32 %a, 2
8891 // %c = srl i32 %b, 1
8892 // brcond i32 %c ...
8897 // %b = and i32 %a, 2
8898 // %c = setcc eq %b, 0
8901 // This applies only when the AND constant value has one bit set and the
8902 // SRL constant is equal to the log2 of the AND constant. The back-end is
8903 // smart enough to convert the result into a TEST/JMP sequence.
8904 SDValue Op0 = N1.getOperand(0);
8905 SDValue Op1 = N1.getOperand(1);
8907 if (Op0.getOpcode() == ISD::AND &&
8908 Op1.getOpcode() == ISD::Constant) {
8909 SDValue AndOp1 = Op0.getOperand(1);
8911 if (AndOp1.getOpcode() == ISD::Constant) {
8912 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8914 if (AndConst.isPowerOf2() &&
8915 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8919 getSetCCResultType(Op0.getValueType()),
8920 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8923 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8924 MVT::Other, Chain, SetCC, N2);
8925 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8926 // will convert it back to (X & C1) >> C2.
8927 CombineTo(N, NewBRCond, false);
8928 // Truncate is dead.
8930 deleteAndRecombine(Trunc);
8931 // Replace the uses of SRL with SETCC
8932 WorklistRemover DeadNodes(*this);
8933 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8934 deleteAndRecombine(N1.getNode());
8935 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8941 // Restore N1 if the above transformation doesn't match.
8942 N1 = N->getOperand(1);
8945 // Transform br(xor(x, y)) -> br(x != y)
8946 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8947 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8948 SDNode *TheXor = N1.getNode();
8949 SDValue Op0 = TheXor->getOperand(0);
8950 SDValue Op1 = TheXor->getOperand(1);
8951 if (Op0.getOpcode() == Op1.getOpcode()) {
8952 // Avoid missing important xor optimizations.
8953 SDValue Tmp = visitXOR(TheXor);
8954 if (Tmp.getNode()) {
8955 if (Tmp.getNode() != TheXor) {
8956 DEBUG(dbgs() << "\nReplacing.8 ";
8958 dbgs() << "\nWith: ";
8959 Tmp.getNode()->dump(&DAG);
8961 WorklistRemover DeadNodes(*this);
8962 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8963 deleteAndRecombine(TheXor);
8964 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8965 MVT::Other, Chain, Tmp, N2);
8968 // visitXOR has changed XOR's operands or replaced the XOR completely,
8970 return SDValue(N, 0);
8974 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8976 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8977 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8978 Op0.getOpcode() == ISD::XOR) {
8979 TheXor = Op0.getNode();
8983 EVT SetCCVT = N1.getValueType();
8985 SetCCVT = getSetCCResultType(SetCCVT);
8986 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8989 Equal ? ISD::SETEQ : ISD::SETNE);
8990 // Replace the uses of XOR with SETCC
8991 WorklistRemover DeadNodes(*this);
8992 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8993 deleteAndRecombine(N1.getNode());
8994 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8995 MVT::Other, Chain, SetCC, N2);
9002 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9004 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9005 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9006 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9008 // If N is a constant we could fold this into a fallthrough or unconditional
9009 // branch. However that doesn't happen very often in normal code, because
9010 // Instcombine/SimplifyCFG should have handled the available opportunities.
9011 // If we did this folding here, it would be necessary to update the
9012 // MachineBasicBlock CFG, which is awkward.
9014 // Use SimplifySetCC to simplify SETCC's.
9015 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9016 CondLHS, CondRHS, CC->get(), SDLoc(N),
9018 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9020 // fold to a simpler setcc
9021 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9022 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9023 N->getOperand(0), Simp.getOperand(2),
9024 Simp.getOperand(0), Simp.getOperand(1),
9030 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9031 /// and that N may be folded in the load / store addressing mode.
9032 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9034 const TargetLowering &TLI) {
9036 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9037 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9039 VT = LD->getMemoryVT();
9040 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9041 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9043 VT = ST->getMemoryVT();
9047 TargetLowering::AddrMode AM;
9048 if (N->getOpcode() == ISD::ADD) {
9049 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9052 AM.BaseOffs = Offset->getSExtValue();
9056 } else if (N->getOpcode() == ISD::SUB) {
9057 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9060 AM.BaseOffs = -Offset->getSExtValue();
9067 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9070 /// Try turning a load/store into a pre-indexed load/store when the base
9071 /// pointer is an add or subtract and it has other uses besides the load/store.
9072 /// After the transformation, the new indexed load/store has effectively folded
9073 /// the add/subtract in and all of its other uses are redirected to the
9075 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9076 if (Level < AfterLegalizeDAG)
9082 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9083 if (LD->isIndexed())
9085 VT = LD->getMemoryVT();
9086 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9087 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9089 Ptr = LD->getBasePtr();
9090 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9091 if (ST->isIndexed())
9093 VT = ST->getMemoryVT();
9094 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9095 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9097 Ptr = ST->getBasePtr();
9103 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9104 // out. There is no reason to make this a preinc/predec.
9105 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9106 Ptr.getNode()->hasOneUse())
9109 // Ask the target to do addressing mode selection.
9112 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9113 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9116 // Backends without true r+i pre-indexed forms may need to pass a
9117 // constant base with a variable offset so that constant coercion
9118 // will work with the patterns in canonical form.
9119 bool Swapped = false;
9120 if (isa<ConstantSDNode>(BasePtr)) {
9121 std::swap(BasePtr, Offset);
9125 // Don't create a indexed load / store with zero offset.
9126 if (isa<ConstantSDNode>(Offset) &&
9127 cast<ConstantSDNode>(Offset)->isNullValue())
9130 // Try turning it into a pre-indexed load / store except when:
9131 // 1) The new base ptr is a frame index.
9132 // 2) If N is a store and the new base ptr is either the same as or is a
9133 // predecessor of the value being stored.
9134 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9135 // that would create a cycle.
9136 // 4) All uses are load / store ops that use it as old base ptr.
9138 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9139 // (plus the implicit offset) to a register to preinc anyway.
9140 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9145 SDValue Val = cast<StoreSDNode>(N)->getValue();
9146 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9150 // If the offset is a constant, there may be other adds of constants that
9151 // can be folded with this one. We should do this to avoid having to keep
9152 // a copy of the original base pointer.
9153 SmallVector<SDNode *, 16> OtherUses;
9154 if (isa<ConstantSDNode>(Offset))
9155 for (SDNode *Use : BasePtr.getNode()->uses()) {
9156 if (Use == Ptr.getNode())
9159 if (Use->isPredecessorOf(N))
9162 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
9167 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
9168 if (Op1.getNode() == BasePtr.getNode())
9169 std::swap(Op0, Op1);
9170 assert(Op0.getNode() == BasePtr.getNode() &&
9171 "Use of ADD/SUB but not an operand");
9173 if (!isa<ConstantSDNode>(Op1)) {
9178 // FIXME: In some cases, we can be smarter about this.
9179 if (Op1.getValueType() != Offset.getValueType()) {
9184 OtherUses.push_back(Use);
9188 std::swap(BasePtr, Offset);
9190 // Now check for #3 and #4.
9191 bool RealUse = false;
9193 // Caches for hasPredecessorHelper
9194 SmallPtrSet<const SDNode *, 32> Visited;
9195 SmallVector<const SDNode *, 16> Worklist;
9197 for (SDNode *Use : Ptr.getNode()->uses()) {
9200 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9203 // If Ptr may be folded in addressing mode of other use, then it's
9204 // not profitable to do this transformation.
9205 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9214 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9215 BasePtr, Offset, AM);
9217 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9218 BasePtr, Offset, AM);
9221 DEBUG(dbgs() << "\nReplacing.4 ";
9223 dbgs() << "\nWith: ";
9224 Result.getNode()->dump(&DAG);
9226 WorklistRemover DeadNodes(*this);
9228 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9229 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9231 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9234 // Finally, since the node is now dead, remove it from the graph.
9235 deleteAndRecombine(N);
9238 std::swap(BasePtr, Offset);
9240 // Replace other uses of BasePtr that can be updated to use Ptr
9241 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9242 unsigned OffsetIdx = 1;
9243 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9245 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9246 BasePtr.getNode() && "Expected BasePtr operand");
9248 // We need to replace ptr0 in the following expression:
9249 // x0 * offset0 + y0 * ptr0 = t0
9251 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9253 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9254 // indexed load/store and the expresion that needs to be re-written.
9256 // Therefore, we have:
9257 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9259 ConstantSDNode *CN =
9260 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9262 APInt Offset0 = CN->getAPIntValue();
9263 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9265 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9266 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9267 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9268 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9270 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9272 APInt CNV = Offset0;
9273 if (X0 < 0) CNV = -CNV;
9274 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9275 else CNV = CNV - Offset1;
9277 SDLoc DL(OtherUses[i]);
9279 // We can now generate the new expression.
9280 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9281 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9283 SDValue NewUse = DAG.getNode(Opcode,
9285 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9286 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9287 deleteAndRecombine(OtherUses[i]);
9290 // Replace the uses of Ptr with uses of the updated base value.
9291 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9292 deleteAndRecombine(Ptr.getNode());
9297 /// Try to combine a load/store with a add/sub of the base pointer node into a
9298 /// post-indexed load/store. The transformation folded the add/subtract into the
9299 /// new indexed load/store effectively and all of its uses are redirected to the
9301 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9302 if (Level < AfterLegalizeDAG)
9308 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9309 if (LD->isIndexed())
9311 VT = LD->getMemoryVT();
9312 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9313 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9315 Ptr = LD->getBasePtr();
9316 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9317 if (ST->isIndexed())
9319 VT = ST->getMemoryVT();
9320 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9321 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9323 Ptr = ST->getBasePtr();
9329 if (Ptr.getNode()->hasOneUse())
9332 for (SDNode *Op : Ptr.getNode()->uses()) {
9334 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9339 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9340 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9341 // Don't create a indexed load / store with zero offset.
9342 if (isa<ConstantSDNode>(Offset) &&
9343 cast<ConstantSDNode>(Offset)->isNullValue())
9346 // Try turning it into a post-indexed load / store except when
9347 // 1) All uses are load / store ops that use it as base ptr (and
9348 // it may be folded as addressing mmode).
9349 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9350 // nor a successor of N. Otherwise, if Op is folded that would
9353 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9357 bool TryNext = false;
9358 for (SDNode *Use : BasePtr.getNode()->uses()) {
9359 if (Use == Ptr.getNode())
9362 // If all the uses are load / store addresses, then don't do the
9364 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9365 bool RealUse = false;
9366 for (SDNode *UseUse : Use->uses()) {
9367 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9382 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9383 SDValue Result = isLoad
9384 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9385 BasePtr, Offset, AM)
9386 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9387 BasePtr, Offset, AM);
9390 DEBUG(dbgs() << "\nReplacing.5 ";
9392 dbgs() << "\nWith: ";
9393 Result.getNode()->dump(&DAG);
9395 WorklistRemover DeadNodes(*this);
9397 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9398 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9400 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9403 // Finally, since the node is now dead, remove it from the graph.
9404 deleteAndRecombine(N);
9406 // Replace the uses of Use with uses of the updated base value.
9407 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9408 Result.getValue(isLoad ? 1 : 0));
9409 deleteAndRecombine(Op);
9418 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9419 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9420 ISD::MemIndexedMode AM = LD->getAddressingMode();
9421 assert(AM != ISD::UNINDEXED);
9422 SDValue BP = LD->getOperand(1);
9423 SDValue Inc = LD->getOperand(2);
9425 // Some backends use TargetConstants for load offsets, but don't expect
9426 // TargetConstants in general ADD nodes. We can convert these constants into
9427 // regular Constants (if the constant is not opaque).
9428 assert((Inc.getOpcode() != ISD::TargetConstant ||
9429 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9430 "Cannot split out indexing using opaque target constants");
9431 if (Inc.getOpcode() == ISD::TargetConstant) {
9432 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9433 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9434 ConstInc->getValueType(0));
9438 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9439 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9442 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9443 LoadSDNode *LD = cast<LoadSDNode>(N);
9444 SDValue Chain = LD->getChain();
9445 SDValue Ptr = LD->getBasePtr();
9447 // If load is not volatile and there are no uses of the loaded value (and
9448 // the updated indexed value in case of indexed loads), change uses of the
9449 // chain value into uses of the chain input (i.e. delete the dead load).
9450 if (!LD->isVolatile()) {
9451 if (N->getValueType(1) == MVT::Other) {
9453 if (!N->hasAnyUseOfValue(0)) {
9454 // It's not safe to use the two value CombineTo variant here. e.g.
9455 // v1, chain2 = load chain1, loc
9456 // v2, chain3 = load chain2, loc
9458 // Now we replace use of chain2 with chain1. This makes the second load
9459 // isomorphic to the one we are deleting, and thus makes this load live.
9460 DEBUG(dbgs() << "\nReplacing.6 ";
9462 dbgs() << "\nWith chain: ";
9463 Chain.getNode()->dump(&DAG);
9465 WorklistRemover DeadNodes(*this);
9466 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9469 deleteAndRecombine(N);
9471 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9475 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9477 // If this load has an opaque TargetConstant offset, then we cannot split
9478 // the indexing into an add/sub directly (that TargetConstant may not be
9479 // valid for a different type of node, and we cannot convert an opaque
9480 // target constant into a regular constant).
9481 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9482 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9484 if (!N->hasAnyUseOfValue(0) &&
9485 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9486 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9488 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9489 Index = SplitIndexingFromLoad(LD);
9490 // Try to fold the base pointer arithmetic into subsequent loads and
9492 AddUsersToWorklist(N);
9494 Index = DAG.getUNDEF(N->getValueType(1));
9495 DEBUG(dbgs() << "\nReplacing.7 ";
9497 dbgs() << "\nWith: ";
9498 Undef.getNode()->dump(&DAG);
9499 dbgs() << " and 2 other values\n");
9500 WorklistRemover DeadNodes(*this);
9501 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9502 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9503 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9504 deleteAndRecombine(N);
9505 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9510 // If this load is directly stored, replace the load value with the stored
9512 // TODO: Handle store large -> read small portion.
9513 // TODO: Handle TRUNCSTORE/LOADEXT
9514 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9515 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9516 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9517 if (PrevST->getBasePtr() == Ptr &&
9518 PrevST->getValue().getValueType() == N->getValueType(0))
9519 return CombineTo(N, Chain.getOperand(1), Chain);
9523 // Try to infer better alignment information than the load already has.
9524 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9525 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9526 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9528 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9529 LD->getValueType(0),
9530 Chain, Ptr, LD->getPointerInfo(),
9532 LD->isVolatile(), LD->isNonTemporal(),
9533 LD->isInvariant(), Align, LD->getAAInfo());
9534 if (NewLoad.getNode() != N)
9535 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9540 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9541 : DAG.getSubtarget().useAA();
9543 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9544 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9547 if (UseAA && LD->isUnindexed()) {
9548 // Walk up chain skipping non-aliasing memory nodes.
9549 SDValue BetterChain = FindBetterChain(N, Chain);
9551 // If there is a better chain.
9552 if (Chain != BetterChain) {
9555 // Replace the chain to void dependency.
9556 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9557 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9558 BetterChain, Ptr, LD->getMemOperand());
9560 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9561 LD->getValueType(0),
9562 BetterChain, Ptr, LD->getMemoryVT(),
9563 LD->getMemOperand());
9566 // Create token factor to keep old chain connected.
9567 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9568 MVT::Other, Chain, ReplLoad.getValue(1));
9570 // Make sure the new and old chains are cleaned up.
9571 AddToWorklist(Token.getNode());
9573 // Replace uses with load result and token factor. Don't add users
9575 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9579 // Try transforming N to an indexed load.
9580 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9581 return SDValue(N, 0);
9583 // Try to slice up N to more direct loads if the slices are mapped to
9584 // different register banks or pairing can take place.
9586 return SDValue(N, 0);
9592 /// \brief Helper structure used to slice a load in smaller loads.
9593 /// Basically a slice is obtained from the following sequence:
9594 /// Origin = load Ty1, Base
9595 /// Shift = srl Ty1 Origin, CstTy Amount
9596 /// Inst = trunc Shift to Ty2
9598 /// Then, it will be rewriten into:
9599 /// Slice = load SliceTy, Base + SliceOffset
9600 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9602 /// SliceTy is deduced from the number of bits that are actually used to
9604 struct LoadedSlice {
9605 /// \brief Helper structure used to compute the cost of a slice.
9607 /// Are we optimizing for code size.
9612 unsigned CrossRegisterBanksCopies;
9616 Cost(bool ForCodeSize = false)
9617 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9618 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9620 /// \brief Get the cost of one isolated slice.
9621 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9622 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9623 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9624 EVT TruncType = LS.Inst->getValueType(0);
9625 EVT LoadedType = LS.getLoadedType();
9626 if (TruncType != LoadedType &&
9627 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9631 /// \brief Account for slicing gain in the current cost.
9632 /// Slicing provide a few gains like removing a shift or a
9633 /// truncate. This method allows to grow the cost of the original
9634 /// load with the gain from this slice.
9635 void addSliceGain(const LoadedSlice &LS) {
9636 // Each slice saves a truncate.
9637 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9638 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9639 LS.Inst->getOperand(0).getValueType()))
9641 // If there is a shift amount, this slice gets rid of it.
9644 // If this slice can merge a cross register bank copy, account for it.
9645 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9646 ++CrossRegisterBanksCopies;
9649 Cost &operator+=(const Cost &RHS) {
9651 Truncates += RHS.Truncates;
9652 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9658 bool operator==(const Cost &RHS) const {
9659 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9660 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9661 ZExts == RHS.ZExts && Shift == RHS.Shift;
9664 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9666 bool operator<(const Cost &RHS) const {
9667 // Assume cross register banks copies are as expensive as loads.
9668 // FIXME: Do we want some more target hooks?
9669 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9670 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9671 // Unless we are optimizing for code size, consider the
9672 // expensive operation first.
9673 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9674 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9675 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9676 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9679 bool operator>(const Cost &RHS) const { return RHS < *this; }
9681 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9683 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9685 // The last instruction that represent the slice. This should be a
9686 // truncate instruction.
9688 // The original load instruction.
9690 // The right shift amount in bits from the original load.
9692 // The DAG from which Origin came from.
9693 // This is used to get some contextual information about legal types, etc.
9696 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9697 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9698 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9700 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9701 /// \return Result is \p BitWidth and has used bits set to 1 and
9702 /// not used bits set to 0.
9703 APInt getUsedBits() const {
9704 // Reproduce the trunc(lshr) sequence:
9705 // - Start from the truncated value.
9706 // - Zero extend to the desired bit width.
9708 assert(Origin && "No original load to compare against.");
9709 unsigned BitWidth = Origin->getValueSizeInBits(0);
9710 assert(Inst && "This slice is not bound to an instruction");
9711 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9712 "Extracted slice is bigger than the whole type!");
9713 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9714 UsedBits.setAllBits();
9715 UsedBits = UsedBits.zext(BitWidth);
9720 /// \brief Get the size of the slice to be loaded in bytes.
9721 unsigned getLoadedSize() const {
9722 unsigned SliceSize = getUsedBits().countPopulation();
9723 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9724 return SliceSize / 8;
9727 /// \brief Get the type that will be loaded for this slice.
9728 /// Note: This may not be the final type for the slice.
9729 EVT getLoadedType() const {
9730 assert(DAG && "Missing context");
9731 LLVMContext &Ctxt = *DAG->getContext();
9732 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9735 /// \brief Get the alignment of the load used for this slice.
9736 unsigned getAlignment() const {
9737 unsigned Alignment = Origin->getAlignment();
9738 unsigned Offset = getOffsetFromBase();
9740 Alignment = MinAlign(Alignment, Alignment + Offset);
9744 /// \brief Check if this slice can be rewritten with legal operations.
9745 bool isLegal() const {
9746 // An invalid slice is not legal.
9747 if (!Origin || !Inst || !DAG)
9750 // Offsets are for indexed load only, we do not handle that.
9751 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9754 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9756 // Check that the type is legal.
9757 EVT SliceType = getLoadedType();
9758 if (!TLI.isTypeLegal(SliceType))
9761 // Check that the load is legal for this type.
9762 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9765 // Check that the offset can be computed.
9766 // 1. Check its type.
9767 EVT PtrType = Origin->getBasePtr().getValueType();
9768 if (PtrType == MVT::Untyped || PtrType.isExtended())
9771 // 2. Check that it fits in the immediate.
9772 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9775 // 3. Check that the computation is legal.
9776 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9779 // Check that the zext is legal if it needs one.
9780 EVT TruncateType = Inst->getValueType(0);
9781 if (TruncateType != SliceType &&
9782 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9788 /// \brief Get the offset in bytes of this slice in the original chunk of
9790 /// \pre DAG != nullptr.
9791 uint64_t getOffsetFromBase() const {
9792 assert(DAG && "Missing context.");
9794 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9795 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9796 uint64_t Offset = Shift / 8;
9797 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9798 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9799 "The size of the original loaded type is not a multiple of a"
9801 // If Offset is bigger than TySizeInBytes, it means we are loading all
9802 // zeros. This should have been optimized before in the process.
9803 assert(TySizeInBytes > Offset &&
9804 "Invalid shift amount for given loaded size");
9806 Offset = TySizeInBytes - Offset - getLoadedSize();
9810 /// \brief Generate the sequence of instructions to load the slice
9811 /// represented by this object and redirect the uses of this slice to
9812 /// this new sequence of instructions.
9813 /// \pre this->Inst && this->Origin are valid Instructions and this
9814 /// object passed the legal check: LoadedSlice::isLegal returned true.
9815 /// \return The last instruction of the sequence used to load the slice.
9816 SDValue loadSlice() const {
9817 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9818 const SDValue &OldBaseAddr = Origin->getBasePtr();
9819 SDValue BaseAddr = OldBaseAddr;
9820 // Get the offset in that chunk of bytes w.r.t. the endianess.
9821 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9822 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9824 // BaseAddr = BaseAddr + Offset.
9825 EVT ArithType = BaseAddr.getValueType();
9827 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9828 DAG->getConstant(Offset, DL, ArithType));
9831 // Create the type of the loaded slice according to its size.
9832 EVT SliceType = getLoadedType();
9834 // Create the load for the slice.
9835 SDValue LastInst = DAG->getLoad(
9836 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9837 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9838 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9839 // If the final type is not the same as the loaded type, this means that
9840 // we have to pad with zero. Create a zero extend for that.
9841 EVT FinalType = Inst->getValueType(0);
9842 if (SliceType != FinalType)
9844 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9848 /// \brief Check if this slice can be merged with an expensive cross register
9849 /// bank copy. E.g.,
9851 /// f = bitcast i32 i to float
9852 bool canMergeExpensiveCrossRegisterBankCopy() const {
9853 if (!Inst || !Inst->hasOneUse())
9855 SDNode *Use = *Inst->use_begin();
9856 if (Use->getOpcode() != ISD::BITCAST)
9858 assert(DAG && "Missing context");
9859 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9860 EVT ResVT = Use->getValueType(0);
9861 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9862 const TargetRegisterClass *ArgRC =
9863 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9864 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9867 // At this point, we know that we perform a cross-register-bank copy.
9868 // Check if it is expensive.
9869 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9870 // Assume bitcasts are cheap, unless both register classes do not
9871 // explicitly share a common sub class.
9872 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9875 // Check if it will be merged with the load.
9876 // 1. Check the alignment constraint.
9877 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9878 ResVT.getTypeForEVT(*DAG->getContext()));
9880 if (RequiredAlignment > getAlignment())
9883 // 2. Check that the load is a legal operation for that type.
9884 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9887 // 3. Check that we do not have a zext in the way.
9888 if (Inst->getValueType(0) != getLoadedType())
9896 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9897 /// \p UsedBits looks like 0..0 1..1 0..0.
9898 static bool areUsedBitsDense(const APInt &UsedBits) {
9899 // If all the bits are one, this is dense!
9900 if (UsedBits.isAllOnesValue())
9903 // Get rid of the unused bits on the right.
9904 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9905 // Get rid of the unused bits on the left.
9906 if (NarrowedUsedBits.countLeadingZeros())
9907 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9908 // Check that the chunk of bits is completely used.
9909 return NarrowedUsedBits.isAllOnesValue();
9912 /// \brief Check whether or not \p First and \p Second are next to each other
9913 /// in memory. This means that there is no hole between the bits loaded
9914 /// by \p First and the bits loaded by \p Second.
9915 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9916 const LoadedSlice &Second) {
9917 assert(First.Origin == Second.Origin && First.Origin &&
9918 "Unable to match different memory origins.");
9919 APInt UsedBits = First.getUsedBits();
9920 assert((UsedBits & Second.getUsedBits()) == 0 &&
9921 "Slices are not supposed to overlap.");
9922 UsedBits |= Second.getUsedBits();
9923 return areUsedBitsDense(UsedBits);
9926 /// \brief Adjust the \p GlobalLSCost according to the target
9927 /// paring capabilities and the layout of the slices.
9928 /// \pre \p GlobalLSCost should account for at least as many loads as
9929 /// there is in the slices in \p LoadedSlices.
9930 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9931 LoadedSlice::Cost &GlobalLSCost) {
9932 unsigned NumberOfSlices = LoadedSlices.size();
9933 // If there is less than 2 elements, no pairing is possible.
9934 if (NumberOfSlices < 2)
9937 // Sort the slices so that elements that are likely to be next to each
9938 // other in memory are next to each other in the list.
9939 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9940 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9941 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9942 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9944 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9945 // First (resp. Second) is the first (resp. Second) potentially candidate
9946 // to be placed in a paired load.
9947 const LoadedSlice *First = nullptr;
9948 const LoadedSlice *Second = nullptr;
9949 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9950 // Set the beginning of the pair.
9953 Second = &LoadedSlices[CurrSlice];
9955 // If First is NULL, it means we start a new pair.
9956 // Get to the next slice.
9960 EVT LoadedType = First->getLoadedType();
9962 // If the types of the slices are different, we cannot pair them.
9963 if (LoadedType != Second->getLoadedType())
9966 // Check if the target supplies paired loads for this type.
9967 unsigned RequiredAlignment = 0;
9968 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9969 // move to the next pair, this type is hopeless.
9973 // Check if we meet the alignment requirement.
9974 if (RequiredAlignment > First->getAlignment())
9977 // Check that both loads are next to each other in memory.
9978 if (!areSlicesNextToEachOther(*First, *Second))
9981 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9982 --GlobalLSCost.Loads;
9983 // Move to the next pair.
9988 /// \brief Check the profitability of all involved LoadedSlice.
9989 /// Currently, it is considered profitable if there is exactly two
9990 /// involved slices (1) which are (2) next to each other in memory, and
9991 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9993 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9994 /// the elements themselves.
9996 /// FIXME: When the cost model will be mature enough, we can relax
9997 /// constraints (1) and (2).
9998 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9999 const APInt &UsedBits, bool ForCodeSize) {
10000 unsigned NumberOfSlices = LoadedSlices.size();
10001 if (StressLoadSlicing)
10002 return NumberOfSlices > 1;
10005 if (NumberOfSlices != 2)
10009 if (!areUsedBitsDense(UsedBits))
10013 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10014 // The original code has one big load.
10015 OrigCost.Loads = 1;
10016 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10017 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10018 // Accumulate the cost of all the slices.
10019 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10020 GlobalSlicingCost += SliceCost;
10022 // Account as cost in the original configuration the gain obtained
10023 // with the current slices.
10024 OrigCost.addSliceGain(LS);
10027 // If the target supports paired load, adjust the cost accordingly.
10028 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10029 return OrigCost > GlobalSlicingCost;
10032 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10033 /// operations, split it in the various pieces being extracted.
10035 /// This sort of thing is introduced by SROA.
10036 /// This slicing takes care not to insert overlapping loads.
10037 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10038 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10039 if (Level < AfterLegalizeDAG)
10042 LoadSDNode *LD = cast<LoadSDNode>(N);
10043 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10044 !LD->getValueType(0).isInteger())
10047 // Keep track of already used bits to detect overlapping values.
10048 // In that case, we will just abort the transformation.
10049 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10051 SmallVector<LoadedSlice, 4> LoadedSlices;
10053 // Check if this load is used as several smaller chunks of bits.
10054 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10055 // of computation for each trunc.
10056 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10057 UI != UIEnd; ++UI) {
10058 // Skip the uses of the chain.
10059 if (UI.getUse().getResNo() != 0)
10062 SDNode *User = *UI;
10063 unsigned Shift = 0;
10065 // Check if this is a trunc(lshr).
10066 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10067 isa<ConstantSDNode>(User->getOperand(1))) {
10068 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10069 User = *User->use_begin();
10072 // At this point, User is a Truncate, iff we encountered, trunc or
10074 if (User->getOpcode() != ISD::TRUNCATE)
10077 // The width of the type must be a power of 2 and greater than 8-bits.
10078 // Otherwise the load cannot be represented in LLVM IR.
10079 // Moreover, if we shifted with a non-8-bits multiple, the slice
10080 // will be across several bytes. We do not support that.
10081 unsigned Width = User->getValueSizeInBits(0);
10082 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10085 // Build the slice for this chain of computations.
10086 LoadedSlice LS(User, LD, Shift, &DAG);
10087 APInt CurrentUsedBits = LS.getUsedBits();
10089 // Check if this slice overlaps with another.
10090 if ((CurrentUsedBits & UsedBits) != 0)
10092 // Update the bits used globally.
10093 UsedBits |= CurrentUsedBits;
10095 // Check if the new slice would be legal.
10099 // Record the slice.
10100 LoadedSlices.push_back(LS);
10103 // Abort slicing if it does not seem to be profitable.
10104 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10109 // Rewrite each chain to use an independent load.
10110 // By construction, each chain can be represented by a unique load.
10112 // Prepare the argument for the new token factor for all the slices.
10113 SmallVector<SDValue, 8> ArgChains;
10114 for (SmallVectorImpl<LoadedSlice>::const_iterator
10115 LSIt = LoadedSlices.begin(),
10116 LSItEnd = LoadedSlices.end();
10117 LSIt != LSItEnd; ++LSIt) {
10118 SDValue SliceInst = LSIt->loadSlice();
10119 CombineTo(LSIt->Inst, SliceInst, true);
10120 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10121 SliceInst = SliceInst.getOperand(0);
10122 assert(SliceInst->getOpcode() == ISD::LOAD &&
10123 "It takes more than a zext to get to the loaded slice!!");
10124 ArgChains.push_back(SliceInst.getValue(1));
10127 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10129 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10133 /// Check to see if V is (and load (ptr), imm), where the load is having
10134 /// specific bytes cleared out. If so, return the byte size being masked out
10135 /// and the shift amount.
10136 static std::pair<unsigned, unsigned>
10137 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10138 std::pair<unsigned, unsigned> Result(0, 0);
10140 // Check for the structure we're looking for.
10141 if (V->getOpcode() != ISD::AND ||
10142 !isa<ConstantSDNode>(V->getOperand(1)) ||
10143 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10146 // Check the chain and pointer.
10147 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10148 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10150 // The store should be chained directly to the load or be an operand of a
10152 if (LD == Chain.getNode())
10154 else if (Chain->getOpcode() != ISD::TokenFactor)
10155 return Result; // Fail.
10158 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10159 if (Chain->getOperand(i).getNode() == LD) {
10163 if (!isOk) return Result;
10166 // This only handles simple types.
10167 if (V.getValueType() != MVT::i16 &&
10168 V.getValueType() != MVT::i32 &&
10169 V.getValueType() != MVT::i64)
10172 // Check the constant mask. Invert it so that the bits being masked out are
10173 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10174 // follow the sign bit for uniformity.
10175 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10176 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10177 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10178 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10179 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10180 if (NotMaskLZ == 64) return Result; // All zero mask.
10182 // See if we have a continuous run of bits. If so, we have 0*1+0*
10183 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10186 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10187 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10188 NotMaskLZ -= 64-V.getValueSizeInBits();
10190 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10191 switch (MaskedBytes) {
10195 default: return Result; // All one mask, or 5-byte mask.
10198 // Verify that the first bit starts at a multiple of mask so that the access
10199 // is aligned the same as the access width.
10200 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10202 Result.first = MaskedBytes;
10203 Result.second = NotMaskTZ/8;
10208 /// Check to see if IVal is something that provides a value as specified by
10209 /// MaskInfo. If so, replace the specified store with a narrower store of
10210 /// truncated IVal.
10212 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10213 SDValue IVal, StoreSDNode *St,
10215 unsigned NumBytes = MaskInfo.first;
10216 unsigned ByteShift = MaskInfo.second;
10217 SelectionDAG &DAG = DC->getDAG();
10219 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10220 // that uses this. If not, this is not a replacement.
10221 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10222 ByteShift*8, (ByteShift+NumBytes)*8);
10223 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10225 // Check that it is legal on the target to do this. It is legal if the new
10226 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10228 MVT VT = MVT::getIntegerVT(NumBytes*8);
10229 if (!DC->isTypeLegal(VT))
10232 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10233 // shifted by ByteShift and truncated down to NumBytes.
10236 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10237 DAG.getConstant(ByteShift*8, DL,
10238 DC->getShiftAmountTy(IVal.getValueType())));
10241 // Figure out the offset for the store and the alignment of the access.
10243 unsigned NewAlign = St->getAlignment();
10245 if (DAG.getTargetLoweringInfo().isLittleEndian())
10246 StOffset = ByteShift;
10248 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10250 SDValue Ptr = St->getBasePtr();
10253 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10254 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10255 NewAlign = MinAlign(NewAlign, StOffset);
10258 // Truncate down to the new size.
10259 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10262 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10263 St->getPointerInfo().getWithOffset(StOffset),
10264 false, false, NewAlign).getNode();
10268 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10269 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10270 /// narrowing the load and store if it would end up being a win for performance
10272 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10273 StoreSDNode *ST = cast<StoreSDNode>(N);
10274 if (ST->isVolatile())
10277 SDValue Chain = ST->getChain();
10278 SDValue Value = ST->getValue();
10279 SDValue Ptr = ST->getBasePtr();
10280 EVT VT = Value.getValueType();
10282 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10285 unsigned Opc = Value.getOpcode();
10287 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10288 // is a byte mask indicating a consecutive number of bytes, check to see if
10289 // Y is known to provide just those bytes. If so, we try to replace the
10290 // load + replace + store sequence with a single (narrower) store, which makes
10292 if (Opc == ISD::OR) {
10293 std::pair<unsigned, unsigned> MaskedLoad;
10294 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10295 if (MaskedLoad.first)
10296 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10297 Value.getOperand(1), ST,this))
10298 return SDValue(NewST, 0);
10300 // Or is commutative, so try swapping X and Y.
10301 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10302 if (MaskedLoad.first)
10303 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10304 Value.getOperand(0), ST,this))
10305 return SDValue(NewST, 0);
10308 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10309 Value.getOperand(1).getOpcode() != ISD::Constant)
10312 SDValue N0 = Value.getOperand(0);
10313 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10314 Chain == SDValue(N0.getNode(), 1)) {
10315 LoadSDNode *LD = cast<LoadSDNode>(N0);
10316 if (LD->getBasePtr() != Ptr ||
10317 LD->getPointerInfo().getAddrSpace() !=
10318 ST->getPointerInfo().getAddrSpace())
10321 // Find the type to narrow it the load / op / store to.
10322 SDValue N1 = Value.getOperand(1);
10323 unsigned BitWidth = N1.getValueSizeInBits();
10324 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10325 if (Opc == ISD::AND)
10326 Imm ^= APInt::getAllOnesValue(BitWidth);
10327 if (Imm == 0 || Imm.isAllOnesValue())
10329 unsigned ShAmt = Imm.countTrailingZeros();
10330 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10331 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10332 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10333 // The narrowing should be profitable, the load/store operation should be
10334 // legal (or custom) and the store size should be equal to the NewVT width.
10335 while (NewBW < BitWidth &&
10336 (NewVT.getStoreSizeInBits() != NewBW ||
10337 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10338 !TLI.isNarrowingProfitable(VT, NewVT))) {
10339 NewBW = NextPowerOf2(NewBW);
10340 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10342 if (NewBW >= BitWidth)
10345 // If the lsb changed does not start at the type bitwidth boundary,
10346 // start at the previous one.
10348 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10349 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10350 std::min(BitWidth, ShAmt + NewBW));
10351 if ((Imm & Mask) == Imm) {
10352 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10353 if (Opc == ISD::AND)
10354 NewImm ^= APInt::getAllOnesValue(NewBW);
10355 uint64_t PtrOff = ShAmt / 8;
10356 // For big endian targets, we need to adjust the offset to the pointer to
10357 // load the correct bytes.
10358 if (TLI.isBigEndian())
10359 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10361 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10362 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10363 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10366 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10367 Ptr.getValueType(), Ptr,
10368 DAG.getConstant(PtrOff, SDLoc(LD),
10369 Ptr.getValueType()));
10370 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10371 LD->getChain(), NewPtr,
10372 LD->getPointerInfo().getWithOffset(PtrOff),
10373 LD->isVolatile(), LD->isNonTemporal(),
10374 LD->isInvariant(), NewAlign,
10376 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10377 DAG.getConstant(NewImm, SDLoc(Value),
10379 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10381 ST->getPointerInfo().getWithOffset(PtrOff),
10382 false, false, NewAlign);
10384 AddToWorklist(NewPtr.getNode());
10385 AddToWorklist(NewLD.getNode());
10386 AddToWorklist(NewVal.getNode());
10387 WorklistRemover DeadNodes(*this);
10388 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10397 /// For a given floating point load / store pair, if the load value isn't used
10398 /// by any other operations, then consider transforming the pair to integer
10399 /// load / store operations if the target deems the transformation profitable.
10400 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10401 StoreSDNode *ST = cast<StoreSDNode>(N);
10402 SDValue Chain = ST->getChain();
10403 SDValue Value = ST->getValue();
10404 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10405 Value.hasOneUse() &&
10406 Chain == SDValue(Value.getNode(), 1)) {
10407 LoadSDNode *LD = cast<LoadSDNode>(Value);
10408 EVT VT = LD->getMemoryVT();
10409 if (!VT.isFloatingPoint() ||
10410 VT != ST->getMemoryVT() ||
10411 LD->isNonTemporal() ||
10412 ST->isNonTemporal() ||
10413 LD->getPointerInfo().getAddrSpace() != 0 ||
10414 ST->getPointerInfo().getAddrSpace() != 0)
10417 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10418 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10419 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10420 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10421 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10424 unsigned LDAlign = LD->getAlignment();
10425 unsigned STAlign = ST->getAlignment();
10426 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10427 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10428 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10431 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10432 LD->getChain(), LD->getBasePtr(),
10433 LD->getPointerInfo(),
10434 false, false, false, LDAlign);
10436 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10437 NewLD, ST->getBasePtr(),
10438 ST->getPointerInfo(),
10439 false, false, STAlign);
10441 AddToWorklist(NewLD.getNode());
10442 AddToWorklist(NewST.getNode());
10443 WorklistRemover DeadNodes(*this);
10444 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10453 /// Helper struct to parse and store a memory address as base + index + offset.
10454 /// We ignore sign extensions when it is safe to do so.
10455 /// The following two expressions are not equivalent. To differentiate we need
10456 /// to store whether there was a sign extension involved in the index
10458 /// (load (i64 add (i64 copyfromreg %c)
10459 /// (i64 signextend (add (i8 load %index)
10463 /// (load (i64 add (i64 copyfromreg %c)
10464 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10466 struct BaseIndexOffset {
10470 bool IsIndexSignExt;
10472 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10474 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10475 bool IsIndexSignExt) :
10476 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10478 bool equalBaseIndex(const BaseIndexOffset &Other) {
10479 return Other.Base == Base && Other.Index == Index &&
10480 Other.IsIndexSignExt == IsIndexSignExt;
10483 /// Parses tree in Ptr for base, index, offset addresses.
10484 static BaseIndexOffset match(SDValue Ptr) {
10485 bool IsIndexSignExt = false;
10487 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10488 // instruction, then it could be just the BASE or everything else we don't
10489 // know how to handle. Just use Ptr as BASE and give up.
10490 if (Ptr->getOpcode() != ISD::ADD)
10491 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10493 // We know that we have at least an ADD instruction. Try to pattern match
10494 // the simple case of BASE + OFFSET.
10495 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10496 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10497 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10501 // Inside a loop the current BASE pointer is calculated using an ADD and a
10502 // MUL instruction. In this case Ptr is the actual BASE pointer.
10503 // (i64 add (i64 %array_ptr)
10504 // (i64 mul (i64 %induction_var)
10505 // (i64 %element_size)))
10506 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10507 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10509 // Look at Base + Index + Offset cases.
10510 SDValue Base = Ptr->getOperand(0);
10511 SDValue IndexOffset = Ptr->getOperand(1);
10513 // Skip signextends.
10514 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10515 IndexOffset = IndexOffset->getOperand(0);
10516 IsIndexSignExt = true;
10519 // Either the case of Base + Index (no offset) or something else.
10520 if (IndexOffset->getOpcode() != ISD::ADD)
10521 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10523 // Now we have the case of Base + Index + offset.
10524 SDValue Index = IndexOffset->getOperand(0);
10525 SDValue Offset = IndexOffset->getOperand(1);
10527 if (!isa<ConstantSDNode>(Offset))
10528 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10530 // Ignore signextends.
10531 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10532 Index = Index->getOperand(0);
10533 IsIndexSignExt = true;
10534 } else IsIndexSignExt = false;
10536 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10537 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10542 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10543 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10544 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10545 // Make sure we have something to merge.
10549 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10550 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10551 unsigned LatestNodeUsed = 0;
10553 for (unsigned i=0; i < NumElem; ++i) {
10554 // Find a chain for the new wide-store operand. Notice that some
10555 // of the store nodes that we found may not be selected for inclusion
10556 // in the wide store. The chain we use needs to be the chain of the
10557 // latest store node which is *used* and replaced by the wide store.
10558 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10559 LatestNodeUsed = i;
10562 // The latest Node in the DAG.
10563 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10564 SDLoc DL(StoreNodes[0].MemNode);
10568 // Find a legal type for the vector store.
10569 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10570 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10571 if (IsConstantSrc) {
10572 // A vector store with a constant source implies that the constant is
10573 // zero; we only handle merging stores of constant zeros because the zero
10574 // can be materialized without a load.
10575 // It may be beneficial to loosen this restriction to allow non-zero
10577 StoredVal = DAG.getConstant(0, DL, Ty);
10579 SmallVector<SDValue, 8> Ops;
10580 for (unsigned i = 0; i < NumElem ; ++i) {
10581 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10582 SDValue Val = St->getValue();
10583 // All of the operands of a BUILD_VECTOR must have the same type.
10584 if (Val.getValueType() != MemVT)
10586 Ops.push_back(Val);
10589 // Build the extracted vector elements back into a vector.
10590 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10593 // We should always use a vector store when merging extracted vector
10594 // elements, so this path implies a store of constants.
10595 assert(IsConstantSrc && "Merged vector elements should use vector store");
10597 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10598 APInt StoreInt(StoreBW, 0);
10600 // Construct a single integer constant which is made of the smaller
10601 // constant inputs.
10602 bool IsLE = TLI.isLittleEndian();
10603 for (unsigned i = 0; i < NumElem ; ++i) {
10604 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10605 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10606 SDValue Val = St->getValue();
10607 StoreInt <<= ElementSizeBytes*8;
10608 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10609 StoreInt |= C->getAPIntValue().zext(StoreBW);
10610 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10611 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10613 llvm_unreachable("Invalid constant element type");
10617 // Create the new Load and Store operations.
10618 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10619 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10622 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10623 FirstInChain->getBasePtr(),
10624 FirstInChain->getPointerInfo(),
10626 FirstInChain->getAlignment());
10628 // Replace the last store with the new store
10629 CombineTo(LatestOp, NewStore);
10630 // Erase all other stores.
10631 for (unsigned i = 0; i < NumElem ; ++i) {
10632 if (StoreNodes[i].MemNode == LatestOp)
10634 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10635 // ReplaceAllUsesWith will replace all uses that existed when it was
10636 // called, but graph optimizations may cause new ones to appear. For
10637 // example, the case in pr14333 looks like
10639 // St's chain -> St -> another store -> X
10641 // And the only difference from St to the other store is the chain.
10642 // When we change it's chain to be St's chain they become identical,
10643 // get CSEed and the net result is that X is now a use of St.
10644 // Since we know that St is redundant, just iterate.
10645 while (!St->use_empty())
10646 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10647 deleteAndRecombine(St);
10653 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10654 if (OptLevel == CodeGenOpt::None)
10657 EVT MemVT = St->getMemoryVT();
10658 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10659 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10660 Attribute::NoImplicitFloat);
10662 // Don't merge vectors into wider inputs.
10663 if (MemVT.isVector() || !MemVT.isSimple())
10666 // Perform an early exit check. Do not bother looking at stored values that
10667 // are not constants, loads, or extracted vector elements.
10668 SDValue StoredVal = St->getValue();
10669 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10670 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10671 isa<ConstantFPSDNode>(StoredVal);
10672 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10674 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10677 // Only look at ends of store sequences.
10678 SDValue Chain = SDValue(St, 0);
10679 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10682 // This holds the base pointer, index, and the offset in bytes from the base
10684 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10686 // We must have a base and an offset.
10687 if (!BasePtr.Base.getNode())
10690 // Do not handle stores to undef base pointers.
10691 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10694 // Save the LoadSDNodes that we find in the chain.
10695 // We need to make sure that these nodes do not interfere with
10696 // any of the store nodes.
10697 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10699 // Save the StoreSDNodes that we find in the chain.
10700 SmallVector<MemOpLink, 8> StoreNodes;
10702 // Walk up the chain and look for nodes with offsets from the same
10703 // base pointer. Stop when reaching an instruction with a different kind
10704 // or instruction which has a different base pointer.
10706 StoreSDNode *Index = St;
10708 // If the chain has more than one use, then we can't reorder the mem ops.
10709 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10712 // Find the base pointer and offset for this memory node.
10713 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10715 // Check that the base pointer is the same as the original one.
10716 if (!Ptr.equalBaseIndex(BasePtr))
10719 // Check that the alignment is the same.
10720 if (Index->getAlignment() != St->getAlignment())
10723 // The memory operands must not be volatile.
10724 if (Index->isVolatile() || Index->isIndexed())
10728 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10729 if (St->isTruncatingStore())
10732 // The stored memory type must be the same.
10733 if (Index->getMemoryVT() != MemVT)
10736 // We do not allow unaligned stores because we want to prevent overriding
10738 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10741 // We found a potential memory operand to merge.
10742 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10744 // Find the next memory operand in the chain. If the next operand in the
10745 // chain is a store then move up and continue the scan with the next
10746 // memory operand. If the next operand is a load save it and use alias
10747 // information to check if it interferes with anything.
10748 SDNode *NextInChain = Index->getChain().getNode();
10750 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10751 // We found a store node. Use it for the next iteration.
10754 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10755 if (Ldn->isVolatile()) {
10760 // Save the load node for later. Continue the scan.
10761 AliasLoadNodes.push_back(Ldn);
10762 NextInChain = Ldn->getChain().getNode();
10771 // Check if there is anything to merge.
10772 if (StoreNodes.size() < 2)
10775 // Sort the memory operands according to their distance from the base pointer.
10776 std::sort(StoreNodes.begin(), StoreNodes.end(),
10777 [](MemOpLink LHS, MemOpLink RHS) {
10778 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10779 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10780 LHS.SequenceNum > RHS.SequenceNum);
10783 // Scan the memory operations on the chain and find the first non-consecutive
10784 // store memory address.
10785 unsigned LastConsecutiveStore = 0;
10786 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10787 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10789 // Check that the addresses are consecutive starting from the second
10790 // element in the list of stores.
10792 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10793 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10797 bool Alias = false;
10798 // Check if this store interferes with any of the loads that we found.
10799 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10800 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10804 // We found a load that alias with this store. Stop the sequence.
10808 // Mark this node as useful.
10809 LastConsecutiveStore = i;
10812 // The node with the lowest store address.
10813 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10815 // Store the constants into memory as one consecutive store.
10816 if (IsConstantSrc) {
10817 unsigned LastLegalType = 0;
10818 unsigned LastLegalVectorType = 0;
10819 bool NonZero = false;
10820 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10821 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10822 SDValue StoredVal = St->getValue();
10824 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10825 NonZero |= !C->isNullValue();
10826 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10827 NonZero |= !C->getConstantFPValue()->isNullValue();
10833 // Find a legal type for the constant store.
10834 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10835 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10836 if (TLI.isTypeLegal(StoreTy))
10837 LastLegalType = i+1;
10838 // Or check whether a truncstore is legal.
10839 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10840 TargetLowering::TypePromoteInteger) {
10841 EVT LegalizedStoredValueTy =
10842 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10843 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10844 LastLegalType = i+1;
10847 // Find a legal type for the vector store.
10848 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10849 if (TLI.isTypeLegal(Ty))
10850 LastLegalVectorType = i + 1;
10853 // We only use vectors if the constant is known to be zero and the
10854 // function is not marked with the noimplicitfloat attribute.
10855 if (NonZero || NoVectors)
10856 LastLegalVectorType = 0;
10858 // Check if we found a legal integer type to store.
10859 if (LastLegalType == 0 && LastLegalVectorType == 0)
10862 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10863 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10865 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10869 // When extracting multiple vector elements, try to store them
10870 // in one vector store rather than a sequence of scalar stores.
10871 if (IsExtractVecEltSrc) {
10872 unsigned NumElem = 0;
10873 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10874 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10875 SDValue StoredVal = St->getValue();
10876 // This restriction could be loosened.
10877 // Bail out if any stored values are not elements extracted from a vector.
10878 // It should be possible to handle mixed sources, but load sources need
10879 // more careful handling (see the block of code below that handles
10880 // consecutive loads).
10881 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10884 // Find a legal type for the vector store.
10885 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10886 if (TLI.isTypeLegal(Ty))
10890 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10894 // Below we handle the case of multiple consecutive stores that
10895 // come from multiple consecutive loads. We merge them into a single
10896 // wide load and a single wide store.
10898 // Look for load nodes which are used by the stored values.
10899 SmallVector<MemOpLink, 8> LoadNodes;
10901 // Find acceptable loads. Loads need to have the same chain (token factor),
10902 // must not be zext, volatile, indexed, and they must be consecutive.
10903 BaseIndexOffset LdBasePtr;
10904 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10905 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10906 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10909 // Loads must only have one use.
10910 if (!Ld->hasNUsesOfValue(1, 0))
10913 // Check that the alignment is the same as the stores.
10914 if (Ld->getAlignment() != St->getAlignment())
10917 // The memory operands must not be volatile.
10918 if (Ld->isVolatile() || Ld->isIndexed())
10921 // We do not accept ext loads.
10922 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10925 // The stored memory type must be the same.
10926 if (Ld->getMemoryVT() != MemVT)
10929 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10930 // If this is not the first ptr that we check.
10931 if (LdBasePtr.Base.getNode()) {
10932 // The base ptr must be the same.
10933 if (!LdPtr.equalBaseIndex(LdBasePtr))
10936 // Check that all other base pointers are the same as this one.
10940 // We found a potential memory operand to merge.
10941 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10944 if (LoadNodes.size() < 2)
10947 // If we have load/store pair instructions and we only have two values,
10949 unsigned RequiredAlignment;
10950 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10951 St->getAlignment() >= RequiredAlignment)
10954 // Scan the memory operations on the chain and find the first non-consecutive
10955 // load memory address. These variables hold the index in the store node
10957 unsigned LastConsecutiveLoad = 0;
10958 // This variable refers to the size and not index in the array.
10959 unsigned LastLegalVectorType = 0;
10960 unsigned LastLegalIntegerType = 0;
10961 StartAddress = LoadNodes[0].OffsetFromBase;
10962 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10963 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10964 // All loads much share the same chain.
10965 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10968 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10969 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10971 LastConsecutiveLoad = i;
10973 // Find a legal type for the vector store.
10974 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10975 if (TLI.isTypeLegal(StoreTy))
10976 LastLegalVectorType = i + 1;
10978 // Find a legal type for the integer store.
10979 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10980 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10981 if (TLI.isTypeLegal(StoreTy))
10982 LastLegalIntegerType = i + 1;
10983 // Or check whether a truncstore and extload is legal.
10984 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10985 TargetLowering::TypePromoteInteger) {
10986 EVT LegalizedStoredValueTy =
10987 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10988 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10989 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10990 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10991 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10992 LastLegalIntegerType = i+1;
10996 // Only use vector types if the vector type is larger than the integer type.
10997 // If they are the same, use integers.
10998 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10999 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11001 // We add +1 here because the LastXXX variables refer to location while
11002 // the NumElem refers to array/index size.
11003 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11004 NumElem = std::min(LastLegalType, NumElem);
11009 // The latest Node in the DAG.
11010 unsigned LatestNodeUsed = 0;
11011 for (unsigned i=1; i<NumElem; ++i) {
11012 // Find a chain for the new wide-store operand. Notice that some
11013 // of the store nodes that we found may not be selected for inclusion
11014 // in the wide store. The chain we use needs to be the chain of the
11015 // latest store node which is *used* and replaced by the wide store.
11016 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11017 LatestNodeUsed = i;
11020 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11022 // Find if it is better to use vectors or integers to load and store
11026 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11028 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11029 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11032 SDLoc LoadDL(LoadNodes[0].MemNode);
11033 SDLoc StoreDL(StoreNodes[0].MemNode);
11035 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11036 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
11037 FirstLoad->getChain(),
11038 FirstLoad->getBasePtr(),
11039 FirstLoad->getPointerInfo(),
11040 false, false, false,
11041 FirstLoad->getAlignment());
11043 SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
11044 FirstInChain->getBasePtr(),
11045 FirstInChain->getPointerInfo(), false, false,
11046 FirstInChain->getAlignment());
11048 // Replace one of the loads with the new load.
11049 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11050 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11051 SDValue(NewLoad.getNode(), 1));
11053 // Remove the rest of the load chains.
11054 for (unsigned i = 1; i < NumElem ; ++i) {
11055 // Replace all chain users of the old load nodes with the chain of the new
11057 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11058 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11061 // Replace the last store with the new store.
11062 CombineTo(LatestOp, NewStore);
11063 // Erase all other stores.
11064 for (unsigned i = 0; i < NumElem ; ++i) {
11065 // Remove all Store nodes.
11066 if (StoreNodes[i].MemNode == LatestOp)
11068 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11069 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11070 deleteAndRecombine(St);
11076 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11077 StoreSDNode *ST = cast<StoreSDNode>(N);
11078 SDValue Chain = ST->getChain();
11079 SDValue Value = ST->getValue();
11080 SDValue Ptr = ST->getBasePtr();
11082 // If this is a store of a bit convert, store the input value if the
11083 // resultant store does not need a higher alignment than the original.
11084 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11085 ST->isUnindexed()) {
11086 unsigned OrigAlign = ST->getAlignment();
11087 EVT SVT = Value.getOperand(0).getValueType();
11088 unsigned Align = TLI.getDataLayout()->
11089 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11090 if (Align <= OrigAlign &&
11091 ((!LegalOperations && !ST->isVolatile()) ||
11092 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11093 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11094 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11095 ST->isNonTemporal(), OrigAlign,
11099 // Turn 'store undef, Ptr' -> nothing.
11100 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11103 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11104 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11105 // NOTE: If the original store is volatile, this transform must not increase
11106 // the number of stores. For example, on x86-32 an f64 can be stored in one
11107 // processor operation but an i64 (which is not legal) requires two. So the
11108 // transform should not be done in this case.
11109 if (Value.getOpcode() != ISD::TargetConstantFP) {
11111 switch (CFP->getSimpleValueType(0).SimpleTy) {
11112 default: llvm_unreachable("Unknown FP type");
11113 case MVT::f16: // We don't do this for these yet.
11119 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11120 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11122 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11123 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11125 return DAG.getStore(Chain, SDLoc(N), Tmp,
11126 Ptr, ST->getMemOperand());
11130 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11131 !ST->isVolatile()) ||
11132 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11134 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11135 getZExtValue(), SDLoc(CFP), MVT::i64);
11136 return DAG.getStore(Chain, SDLoc(N), Tmp,
11137 Ptr, ST->getMemOperand());
11140 if (!ST->isVolatile() &&
11141 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11142 // Many FP stores are not made apparent until after legalize, e.g. for
11143 // argument passing. Since this is so common, custom legalize the
11144 // 64-bit integer store into two 32-bit stores.
11145 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11146 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11147 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11148 if (TLI.isBigEndian()) std::swap(Lo, Hi);
11150 unsigned Alignment = ST->getAlignment();
11151 bool isVolatile = ST->isVolatile();
11152 bool isNonTemporal = ST->isNonTemporal();
11153 AAMDNodes AAInfo = ST->getAAInfo();
11157 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11158 Ptr, ST->getPointerInfo(),
11159 isVolatile, isNonTemporal,
11160 ST->getAlignment(), AAInfo);
11161 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11162 DAG.getConstant(4, DL, Ptr.getValueType()));
11163 Alignment = MinAlign(Alignment, 4U);
11164 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11165 Ptr, ST->getPointerInfo().getWithOffset(4),
11166 isVolatile, isNonTemporal,
11167 Alignment, AAInfo);
11168 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11177 // Try to infer better alignment information than the store already has.
11178 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11179 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11180 if (Align > ST->getAlignment()) {
11182 DAG.getTruncStore(Chain, SDLoc(N), Value,
11183 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11184 ST->isVolatile(), ST->isNonTemporal(), Align,
11186 if (NewStore.getNode() != N)
11187 return CombineTo(ST, NewStore, true);
11192 // Try transforming a pair floating point load / store ops to integer
11193 // load / store ops.
11194 SDValue NewST = TransformFPLoadStorePair(N);
11195 if (NewST.getNode())
11198 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11199 : DAG.getSubtarget().useAA();
11201 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11202 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11205 if (UseAA && ST->isUnindexed()) {
11206 // Walk up chain skipping non-aliasing memory nodes.
11207 SDValue BetterChain = FindBetterChain(N, Chain);
11209 // If there is a better chain.
11210 if (Chain != BetterChain) {
11213 // Replace the chain to avoid dependency.
11214 if (ST->isTruncatingStore()) {
11215 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11216 ST->getMemoryVT(), ST->getMemOperand());
11218 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11219 ST->getMemOperand());
11222 // Create token to keep both nodes around.
11223 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11224 MVT::Other, Chain, ReplStore);
11226 // Make sure the new and old chains are cleaned up.
11227 AddToWorklist(Token.getNode());
11229 // Don't add users to work list.
11230 return CombineTo(N, Token, false);
11234 // Try transforming N to an indexed store.
11235 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11236 return SDValue(N, 0);
11238 // FIXME: is there such a thing as a truncating indexed store?
11239 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11240 Value.getValueType().isInteger()) {
11241 // See if we can simplify the input to this truncstore with knowledge that
11242 // only the low bits are being used. For example:
11243 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11245 GetDemandedBits(Value,
11246 APInt::getLowBitsSet(
11247 Value.getValueType().getScalarType().getSizeInBits(),
11248 ST->getMemoryVT().getScalarType().getSizeInBits()));
11249 AddToWorklist(Value.getNode());
11250 if (Shorter.getNode())
11251 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11252 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11254 // Otherwise, see if we can simplify the operation with
11255 // SimplifyDemandedBits, which only works if the value has a single use.
11256 if (SimplifyDemandedBits(Value,
11257 APInt::getLowBitsSet(
11258 Value.getValueType().getScalarType().getSizeInBits(),
11259 ST->getMemoryVT().getScalarType().getSizeInBits())))
11260 return SDValue(N, 0);
11263 // If this is a load followed by a store to the same location, then the store
11265 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11266 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11267 ST->isUnindexed() && !ST->isVolatile() &&
11268 // There can't be any side effects between the load and store, such as
11269 // a call or store.
11270 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11271 // The store is dead, remove it.
11276 // If this is a store followed by a store with the same value to the same
11277 // location, then the store is dead/noop.
11278 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11279 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11280 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11281 ST1->isUnindexed() && !ST1->isVolatile()) {
11282 // The store is dead, remove it.
11287 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11288 // truncating store. We can do this even if this is already a truncstore.
11289 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11290 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11291 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11292 ST->getMemoryVT())) {
11293 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11294 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11297 // Only perform this optimization before the types are legal, because we
11298 // don't want to perform this optimization on every DAGCombine invocation.
11300 bool EverChanged = false;
11303 // There can be multiple store sequences on the same chain.
11304 // Keep trying to merge store sequences until we are unable to do so
11305 // or until we merge the last store on the chain.
11306 bool Changed = MergeConsecutiveStores(ST);
11307 EverChanged |= Changed;
11308 if (!Changed) break;
11309 } while (ST->getOpcode() != ISD::DELETED_NODE);
11312 return SDValue(N, 0);
11315 return ReduceLoadOpStoreWidth(N);
11318 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11319 SDValue InVec = N->getOperand(0);
11320 SDValue InVal = N->getOperand(1);
11321 SDValue EltNo = N->getOperand(2);
11324 // If the inserted element is an UNDEF, just use the input vector.
11325 if (InVal.getOpcode() == ISD::UNDEF)
11328 EVT VT = InVec.getValueType();
11330 // If we can't generate a legal BUILD_VECTOR, exit
11331 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11334 // Check that we know which element is being inserted
11335 if (!isa<ConstantSDNode>(EltNo))
11337 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11339 // Canonicalize insert_vector_elt dag nodes.
11341 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11342 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11344 // Do this only if the child insert_vector node has one use; also
11345 // do this only if indices are both constants and Idx1 < Idx0.
11346 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11347 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11348 unsigned OtherElt =
11349 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11350 if (Elt < OtherElt) {
11352 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11353 InVec.getOperand(0), InVal, EltNo);
11354 AddToWorklist(NewOp.getNode());
11355 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11356 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11360 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11361 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11362 // vector elements.
11363 SmallVector<SDValue, 8> Ops;
11364 // Do not combine these two vectors if the output vector will not replace
11365 // the input vector.
11366 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11367 Ops.append(InVec.getNode()->op_begin(),
11368 InVec.getNode()->op_end());
11369 } else if (InVec.getOpcode() == ISD::UNDEF) {
11370 unsigned NElts = VT.getVectorNumElements();
11371 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11376 // Insert the element
11377 if (Elt < Ops.size()) {
11378 // All the operands of BUILD_VECTOR must have the same type;
11379 // we enforce that here.
11380 EVT OpVT = Ops[0].getValueType();
11381 if (InVal.getValueType() != OpVT)
11382 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11383 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11384 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11388 // Return the new vector
11389 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11392 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11393 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11394 EVT ResultVT = EVE->getValueType(0);
11395 EVT VecEltVT = InVecVT.getVectorElementType();
11396 unsigned Align = OriginalLoad->getAlignment();
11397 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11398 VecEltVT.getTypeForEVT(*DAG.getContext()));
11400 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11405 SDValue NewPtr = OriginalLoad->getBasePtr();
11407 EVT PtrType = NewPtr.getValueType();
11408 MachinePointerInfo MPI;
11410 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11411 int Elt = ConstEltNo->getZExtValue();
11412 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11413 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11414 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11416 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11417 Offset = DAG.getNode(
11418 ISD::MUL, DL, PtrType, Offset,
11419 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11420 MPI = OriginalLoad->getPointerInfo();
11422 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11424 // The replacement we need to do here is a little tricky: we need to
11425 // replace an extractelement of a load with a load.
11426 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11427 // Note that this replacement assumes that the extractvalue is the only
11428 // use of the load; that's okay because we don't want to perform this
11429 // transformation in other cases anyway.
11432 if (ResultVT.bitsGT(VecEltVT)) {
11433 // If the result type of vextract is wider than the load, then issue an
11434 // extending load instead.
11435 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11439 Load = DAG.getExtLoad(
11440 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11441 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11442 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11443 Chain = Load.getValue(1);
11445 Load = DAG.getLoad(
11446 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11447 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11448 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11449 Chain = Load.getValue(1);
11450 if (ResultVT.bitsLT(VecEltVT))
11451 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11453 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11455 WorklistRemover DeadNodes(*this);
11456 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11457 SDValue To[] = { Load, Chain };
11458 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11459 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11460 // worklist explicitly as well.
11461 AddToWorklist(Load.getNode());
11462 AddUsersToWorklist(Load.getNode()); // Add users too
11463 // Make sure to revisit this node to clean it up; it will usually be dead.
11464 AddToWorklist(EVE);
11466 return SDValue(EVE, 0);
11469 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11470 // (vextract (scalar_to_vector val, 0) -> val
11471 SDValue InVec = N->getOperand(0);
11472 EVT VT = InVec.getValueType();
11473 EVT NVT = N->getValueType(0);
11475 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11476 // Check if the result type doesn't match the inserted element type. A
11477 // SCALAR_TO_VECTOR may truncate the inserted element and the
11478 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11479 SDValue InOp = InVec.getOperand(0);
11480 if (InOp.getValueType() != NVT) {
11481 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11482 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11487 SDValue EltNo = N->getOperand(1);
11488 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11490 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11491 // We only perform this optimization before the op legalization phase because
11492 // we may introduce new vector instructions which are not backed by TD
11493 // patterns. For example on AVX, extracting elements from a wide vector
11494 // without using extract_subvector. However, if we can find an underlying
11495 // scalar value, then we can always use that.
11496 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11498 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11499 int NumElem = VT.getVectorNumElements();
11500 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11501 // Find the new index to extract from.
11502 int OrigElt = SVOp->getMaskElt(Elt);
11504 // Extracting an undef index is undef.
11506 return DAG.getUNDEF(NVT);
11508 // Select the right vector half to extract from.
11510 if (OrigElt < NumElem) {
11511 SVInVec = InVec->getOperand(0);
11513 SVInVec = InVec->getOperand(1);
11514 OrigElt -= NumElem;
11517 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11518 SDValue InOp = SVInVec.getOperand(OrigElt);
11519 if (InOp.getValueType() != NVT) {
11520 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11521 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11527 // FIXME: We should handle recursing on other vector shuffles and
11528 // scalar_to_vector here as well.
11530 if (!LegalOperations) {
11531 EVT IndexTy = TLI.getVectorIdxTy();
11532 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11533 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11537 bool BCNumEltsChanged = false;
11538 EVT ExtVT = VT.getVectorElementType();
11541 // If the result of load has to be truncated, then it's not necessarily
11543 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11546 if (InVec.getOpcode() == ISD::BITCAST) {
11547 // Don't duplicate a load with other uses.
11548 if (!InVec.hasOneUse())
11551 EVT BCVT = InVec.getOperand(0).getValueType();
11552 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11554 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11555 BCNumEltsChanged = true;
11556 InVec = InVec.getOperand(0);
11557 ExtVT = BCVT.getVectorElementType();
11560 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11561 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11562 ISD::isNormalLoad(InVec.getNode()) &&
11563 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11564 SDValue Index = N->getOperand(1);
11565 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11566 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11570 // Perform only after legalization to ensure build_vector / vector_shuffle
11571 // optimizations have already been done.
11572 if (!LegalOperations) return SDValue();
11574 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11575 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11576 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11579 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11581 LoadSDNode *LN0 = nullptr;
11582 const ShuffleVectorSDNode *SVN = nullptr;
11583 if (ISD::isNormalLoad(InVec.getNode())) {
11584 LN0 = cast<LoadSDNode>(InVec);
11585 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11586 InVec.getOperand(0).getValueType() == ExtVT &&
11587 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11588 // Don't duplicate a load with other uses.
11589 if (!InVec.hasOneUse())
11592 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11593 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11594 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11596 // (load $addr+1*size)
11598 // Don't duplicate a load with other uses.
11599 if (!InVec.hasOneUse())
11602 // If the bit convert changed the number of elements, it is unsafe
11603 // to examine the mask.
11604 if (BCNumEltsChanged)
11607 // Select the input vector, guarding against out of range extract vector.
11608 unsigned NumElems = VT.getVectorNumElements();
11609 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11610 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11612 if (InVec.getOpcode() == ISD::BITCAST) {
11613 // Don't duplicate a load with other uses.
11614 if (!InVec.hasOneUse())
11617 InVec = InVec.getOperand(0);
11619 if (ISD::isNormalLoad(InVec.getNode())) {
11620 LN0 = cast<LoadSDNode>(InVec);
11621 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11622 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11626 // Make sure we found a non-volatile load and the extractelement is
11628 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11631 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11633 return DAG.getUNDEF(LVT);
11635 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11641 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11642 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11643 // We perform this optimization post type-legalization because
11644 // the type-legalizer often scalarizes integer-promoted vectors.
11645 // Performing this optimization before may create bit-casts which
11646 // will be type-legalized to complex code sequences.
11647 // We perform this optimization only before the operation legalizer because we
11648 // may introduce illegal operations.
11649 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11652 unsigned NumInScalars = N->getNumOperands();
11654 EVT VT = N->getValueType(0);
11656 // Check to see if this is a BUILD_VECTOR of a bunch of values
11657 // which come from any_extend or zero_extend nodes. If so, we can create
11658 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11659 // optimizations. We do not handle sign-extend because we can't fill the sign
11661 EVT SourceType = MVT::Other;
11662 bool AllAnyExt = true;
11664 for (unsigned i = 0; i != NumInScalars; ++i) {
11665 SDValue In = N->getOperand(i);
11666 // Ignore undef inputs.
11667 if (In.getOpcode() == ISD::UNDEF) continue;
11669 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11670 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11672 // Abort if the element is not an extension.
11673 if (!ZeroExt && !AnyExt) {
11674 SourceType = MVT::Other;
11678 // The input is a ZeroExt or AnyExt. Check the original type.
11679 EVT InTy = In.getOperand(0).getValueType();
11681 // Check that all of the widened source types are the same.
11682 if (SourceType == MVT::Other)
11685 else if (InTy != SourceType) {
11686 // Multiple income types. Abort.
11687 SourceType = MVT::Other;
11691 // Check if all of the extends are ANY_EXTENDs.
11692 AllAnyExt &= AnyExt;
11695 // In order to have valid types, all of the inputs must be extended from the
11696 // same source type and all of the inputs must be any or zero extend.
11697 // Scalar sizes must be a power of two.
11698 EVT OutScalarTy = VT.getScalarType();
11699 bool ValidTypes = SourceType != MVT::Other &&
11700 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11701 isPowerOf2_32(SourceType.getSizeInBits());
11703 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11704 // turn into a single shuffle instruction.
11708 bool isLE = TLI.isLittleEndian();
11709 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11710 assert(ElemRatio > 1 && "Invalid element size ratio");
11711 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11712 DAG.getConstant(0, SDLoc(N), SourceType);
11714 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11715 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11717 // Populate the new build_vector
11718 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11719 SDValue Cast = N->getOperand(i);
11720 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11721 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11722 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11724 if (Cast.getOpcode() == ISD::UNDEF)
11725 In = DAG.getUNDEF(SourceType);
11727 In = Cast->getOperand(0);
11728 unsigned Index = isLE ? (i * ElemRatio) :
11729 (i * ElemRatio + (ElemRatio - 1));
11731 assert(Index < Ops.size() && "Invalid index");
11735 // The type of the new BUILD_VECTOR node.
11736 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11737 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11738 "Invalid vector size");
11739 // Check if the new vector type is legal.
11740 if (!isTypeLegal(VecVT)) return SDValue();
11742 // Make the new BUILD_VECTOR.
11743 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11745 // The new BUILD_VECTOR node has the potential to be further optimized.
11746 AddToWorklist(BV.getNode());
11747 // Bitcast to the desired type.
11748 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11751 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11752 EVT VT = N->getValueType(0);
11754 unsigned NumInScalars = N->getNumOperands();
11757 EVT SrcVT = MVT::Other;
11758 unsigned Opcode = ISD::DELETED_NODE;
11759 unsigned NumDefs = 0;
11761 for (unsigned i = 0; i != NumInScalars; ++i) {
11762 SDValue In = N->getOperand(i);
11763 unsigned Opc = In.getOpcode();
11765 if (Opc == ISD::UNDEF)
11768 // If all scalar values are floats and converted from integers.
11769 if (Opcode == ISD::DELETED_NODE &&
11770 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11777 EVT InVT = In.getOperand(0).getValueType();
11779 // If all scalar values are typed differently, bail out. It's chosen to
11780 // simplify BUILD_VECTOR of integer types.
11781 if (SrcVT == MVT::Other)
11788 // If the vector has just one element defined, it's not worth to fold it into
11789 // a vectorized one.
11793 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11794 && "Should only handle conversion from integer to float.");
11795 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11797 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11799 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11802 // Just because the floating-point vector type is legal does not necessarily
11803 // mean that the corresponding integer vector type is.
11804 if (!isTypeLegal(NVT))
11807 SmallVector<SDValue, 8> Opnds;
11808 for (unsigned i = 0; i != NumInScalars; ++i) {
11809 SDValue In = N->getOperand(i);
11811 if (In.getOpcode() == ISD::UNDEF)
11812 Opnds.push_back(DAG.getUNDEF(SrcVT));
11814 Opnds.push_back(In.getOperand(0));
11816 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11817 AddToWorklist(BV.getNode());
11819 return DAG.getNode(Opcode, dl, VT, BV);
11822 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11823 unsigned NumInScalars = N->getNumOperands();
11825 EVT VT = N->getValueType(0);
11827 // A vector built entirely of undefs is undef.
11828 if (ISD::allOperandsUndef(N))
11829 return DAG.getUNDEF(VT);
11831 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11834 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11837 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11838 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11839 // at most two distinct vectors, turn this into a shuffle node.
11841 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11842 if (!isTypeLegal(VT))
11845 // May only combine to shuffle after legalize if shuffle is legal.
11846 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11849 SDValue VecIn1, VecIn2;
11850 bool UsesZeroVector = false;
11851 for (unsigned i = 0; i != NumInScalars; ++i) {
11852 SDValue Op = N->getOperand(i);
11853 // Ignore undef inputs.
11854 if (Op.getOpcode() == ISD::UNDEF) continue;
11856 // See if we can combine this build_vector into a blend with a zero vector.
11857 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11858 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11859 (Op.getOpcode() == ISD::ConstantFP &&
11860 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11861 UsesZeroVector = true;
11865 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11866 // constant index, bail out.
11867 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11868 !isa<ConstantSDNode>(Op.getOperand(1))) {
11869 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11873 // We allow up to two distinct input vectors.
11874 SDValue ExtractedFromVec = Op.getOperand(0);
11875 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11878 if (!VecIn1.getNode()) {
11879 VecIn1 = ExtractedFromVec;
11880 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11881 VecIn2 = ExtractedFromVec;
11883 // Too many inputs.
11884 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11889 // If everything is good, we can make a shuffle operation.
11890 if (VecIn1.getNode()) {
11891 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11892 SmallVector<int, 8> Mask;
11893 for (unsigned i = 0; i != NumInScalars; ++i) {
11894 unsigned Opcode = N->getOperand(i).getOpcode();
11895 if (Opcode == ISD::UNDEF) {
11896 Mask.push_back(-1);
11900 // Operands can also be zero.
11901 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11902 assert(UsesZeroVector &&
11903 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11904 "Unexpected node found!");
11905 Mask.push_back(NumInScalars+i);
11909 // If extracting from the first vector, just use the index directly.
11910 SDValue Extract = N->getOperand(i);
11911 SDValue ExtVal = Extract.getOperand(1);
11912 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11913 if (Extract.getOperand(0) == VecIn1) {
11914 Mask.push_back(ExtIndex);
11918 // Otherwise, use InIdx + InputVecSize
11919 Mask.push_back(InNumElements + ExtIndex);
11922 // Avoid introducing illegal shuffles with zero.
11923 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11926 // We can't generate a shuffle node with mismatched input and output types.
11927 // Attempt to transform a single input vector to the correct type.
11928 if ((VT != VecIn1.getValueType())) {
11929 // If the input vector type has a different base type to the output
11930 // vector type, bail out.
11931 EVT VTElemType = VT.getVectorElementType();
11932 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11933 (VecIn2.getNode() &&
11934 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11937 // If the input vector is too small, widen it.
11938 // We only support widening of vectors which are half the size of the
11939 // output registers. For example XMM->YMM widening on X86 with AVX.
11940 EVT VecInT = VecIn1.getValueType();
11941 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11942 // If we only have one small input, widen it by adding undef values.
11943 if (!VecIn2.getNode())
11944 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11945 DAG.getUNDEF(VecIn1.getValueType()));
11946 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11947 // If we have two small inputs of the same type, try to concat them.
11948 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11949 VecIn2 = SDValue(nullptr, 0);
11952 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11953 // If the input vector is too large, try to split it.
11954 // We don't support having two input vectors that are too large.
11955 // If the zero vector was used, we can not split the vector,
11956 // since we'd need 3 inputs.
11957 if (UsesZeroVector || VecIn2.getNode())
11960 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11963 // Try to replace VecIn1 with two extract_subvectors
11964 // No need to update the masks, they should still be correct.
11965 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11966 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11967 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11968 DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11973 if (UsesZeroVector)
11974 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11975 DAG.getConstantFP(0.0, dl, VT);
11977 // If VecIn2 is unused then change it to undef.
11978 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11980 // Check that we were able to transform all incoming values to the same
11982 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11983 VecIn1.getValueType() != VT)
11986 // Return the new VECTOR_SHUFFLE node.
11990 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11996 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
11997 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11998 EVT OpVT = N->getOperand(0).getValueType();
12000 // If the operands are legal vectors, leave them alone.
12001 if (TLI.isTypeLegal(OpVT))
12005 EVT VT = N->getValueType(0);
12006 SmallVector<SDValue, 8> Ops;
12008 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12009 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12011 // Keep track of what we encounter.
12012 bool AnyInteger = false;
12013 bool AnyFP = false;
12014 for (const SDValue &Op : N->ops()) {
12015 if (ISD::BITCAST == Op.getOpcode() &&
12016 !Op.getOperand(0).getValueType().isVector())
12017 Ops.push_back(Op.getOperand(0));
12018 else if (ISD::UNDEF == Op.getOpcode())
12019 Ops.push_back(ScalarUndef);
12023 // Note whether we encounter an integer or floating point scalar.
12024 // If it's neither, bail out, it could be something weird like x86mmx.
12025 EVT LastOpVT = Ops.back().getValueType();
12026 if (LastOpVT.isFloatingPoint())
12028 else if (LastOpVT.isInteger())
12034 // If any of the operands is a floating point scalar bitcast to a vector,
12035 // use floating point types throughout, and bitcast everything.
12036 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12038 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12039 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12041 for (SDValue &Op : Ops) {
12042 if (Op.getValueType() == SVT)
12044 if (Op.getOpcode() == ISD::UNDEF)
12047 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12052 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12053 VT.getSizeInBits() / SVT.getSizeInBits());
12054 return DAG.getNode(ISD::BITCAST, DL, VT,
12055 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12058 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12059 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12060 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
12061 // inputs come from at most two distinct vectors, turn this into a shuffle
12064 // If we only have one input vector, we don't need to do any concatenation.
12065 if (N->getNumOperands() == 1)
12066 return N->getOperand(0);
12068 // Check if all of the operands are undefs.
12069 EVT VT = N->getValueType(0);
12070 if (ISD::allOperandsUndef(N))
12071 return DAG.getUNDEF(VT);
12073 // Optimize concat_vectors where all but the first of the vectors are undef.
12074 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12075 return Op.getOpcode() == ISD::UNDEF;
12077 SDValue In = N->getOperand(0);
12078 assert(In.getValueType().isVector() && "Must concat vectors");
12080 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12081 if (In->getOpcode() == ISD::BITCAST &&
12082 !In->getOperand(0)->getValueType(0).isVector()) {
12083 SDValue Scalar = In->getOperand(0);
12085 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12086 // look through the trunc so we can still do the transform:
12087 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12088 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12089 !TLI.isTypeLegal(Scalar.getValueType()) &&
12090 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12091 Scalar = Scalar->getOperand(0);
12093 EVT SclTy = Scalar->getValueType(0);
12095 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12098 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12099 VT.getSizeInBits() / SclTy.getSizeInBits());
12100 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12103 SDLoc dl = SDLoc(N);
12104 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12105 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12109 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12110 // We have already tested above for an UNDEF only concatenation.
12111 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12112 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12113 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12114 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12116 bool AllBuildVectorsOrUndefs =
12117 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12118 if (AllBuildVectorsOrUndefs) {
12119 SmallVector<SDValue, 8> Opnds;
12120 EVT SVT = VT.getScalarType();
12123 if (!SVT.isFloatingPoint()) {
12124 // If BUILD_VECTOR are from built from integer, they may have different
12125 // operand types. Get the smallest type and truncate all operands to it.
12126 bool FoundMinVT = false;
12127 for (const SDValue &Op : N->ops())
12128 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12129 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12130 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12133 assert(FoundMinVT && "Concat vector type mismatch");
12136 for (const SDValue &Op : N->ops()) {
12137 EVT OpVT = Op.getValueType();
12138 unsigned NumElts = OpVT.getVectorNumElements();
12140 if (ISD::UNDEF == Op.getOpcode())
12141 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12143 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12144 if (SVT.isFloatingPoint()) {
12145 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12146 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12148 for (unsigned i = 0; i != NumElts; ++i)
12150 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12155 assert(VT.getVectorNumElements() == Opnds.size() &&
12156 "Concat vector type mismatch");
12157 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12160 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12161 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12164 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12165 // nodes often generate nop CONCAT_VECTOR nodes.
12166 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12167 // place the incoming vectors at the exact same location.
12168 SDValue SingleSource = SDValue();
12169 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12171 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12172 SDValue Op = N->getOperand(i);
12174 if (Op.getOpcode() == ISD::UNDEF)
12177 // Check if this is the identity extract:
12178 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12181 // Find the single incoming vector for the extract_subvector.
12182 if (SingleSource.getNode()) {
12183 if (Op.getOperand(0) != SingleSource)
12186 SingleSource = Op.getOperand(0);
12188 // Check the source type is the same as the type of the result.
12189 // If not, this concat may extend the vector, so we can not
12190 // optimize it away.
12191 if (SingleSource.getValueType() != N->getValueType(0))
12195 unsigned IdentityIndex = i * PartNumElem;
12196 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12197 // The extract index must be constant.
12201 // Check that we are reading from the identity index.
12202 if (CS->getZExtValue() != IdentityIndex)
12206 if (SingleSource.getNode())
12207 return SingleSource;
12212 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12213 EVT NVT = N->getValueType(0);
12214 SDValue V = N->getOperand(0);
12216 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12218 // (extract_subvec (concat V1, V2, ...), i)
12221 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12223 if (V->getOperand(0).getValueType() != NVT)
12225 unsigned Idx = N->getConstantOperandVal(1);
12226 unsigned NumElems = NVT.getVectorNumElements();
12227 assert((Idx % NumElems) == 0 &&
12228 "IDX in concat is not a multiple of the result vector length.");
12229 return V->getOperand(Idx / NumElems);
12233 if (V->getOpcode() == ISD::BITCAST)
12234 V = V.getOperand(0);
12236 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12238 // Handle only simple case where vector being inserted and vector
12239 // being extracted are of same type, and are half size of larger vectors.
12240 EVT BigVT = V->getOperand(0).getValueType();
12241 EVT SmallVT = V->getOperand(1).getValueType();
12242 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12245 // Only handle cases where both indexes are constants with the same type.
12246 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12247 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12249 if (InsIdx && ExtIdx &&
12250 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12251 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12253 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12255 // indices are equal or bit offsets are equal => V1
12256 // otherwise => (extract_subvec V1, ExtIdx)
12257 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12258 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12259 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12260 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12261 DAG.getNode(ISD::BITCAST, dl,
12262 N->getOperand(0).getValueType(),
12263 V->getOperand(0)), N->getOperand(1));
12270 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12271 SDValue V, SelectionDAG &DAG) {
12273 EVT VT = V.getValueType();
12275 switch (V.getOpcode()) {
12279 case ISD::CONCAT_VECTORS: {
12280 EVT OpVT = V->getOperand(0).getValueType();
12281 int OpSize = OpVT.getVectorNumElements();
12282 SmallBitVector OpUsedElements(OpSize, false);
12283 bool FoundSimplification = false;
12284 SmallVector<SDValue, 4> NewOps;
12285 NewOps.reserve(V->getNumOperands());
12286 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12287 SDValue Op = V->getOperand(i);
12288 bool OpUsed = false;
12289 for (int j = 0; j < OpSize; ++j)
12290 if (UsedElements[i * OpSize + j]) {
12291 OpUsedElements[j] = true;
12295 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12296 : DAG.getUNDEF(OpVT));
12297 FoundSimplification |= Op == NewOps.back();
12298 OpUsedElements.reset();
12300 if (FoundSimplification)
12301 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12305 case ISD::INSERT_SUBVECTOR: {
12306 SDValue BaseV = V->getOperand(0);
12307 SDValue SubV = V->getOperand(1);
12308 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12312 int SubSize = SubV.getValueType().getVectorNumElements();
12313 int Idx = IdxN->getZExtValue();
12314 bool SubVectorUsed = false;
12315 SmallBitVector SubUsedElements(SubSize, false);
12316 for (int i = 0; i < SubSize; ++i)
12317 if (UsedElements[i + Idx]) {
12318 SubVectorUsed = true;
12319 SubUsedElements[i] = true;
12320 UsedElements[i + Idx] = false;
12323 // Now recurse on both the base and sub vectors.
12324 SDValue SimplifiedSubV =
12326 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12327 : DAG.getUNDEF(SubV.getValueType());
12328 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12329 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12330 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12331 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12337 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12338 SDValue N1, SelectionDAG &DAG) {
12339 EVT VT = SVN->getValueType(0);
12340 int NumElts = VT.getVectorNumElements();
12341 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12342 for (int M : SVN->getMask())
12343 if (M >= 0 && M < NumElts)
12344 N0UsedElements[M] = true;
12345 else if (M >= NumElts)
12346 N1UsedElements[M - NumElts] = true;
12348 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12349 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12350 if (S0 == N0 && S1 == N1)
12353 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12356 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12357 // or turn a shuffle of a single concat into simpler shuffle then concat.
12358 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12359 EVT VT = N->getValueType(0);
12360 unsigned NumElts = VT.getVectorNumElements();
12362 SDValue N0 = N->getOperand(0);
12363 SDValue N1 = N->getOperand(1);
12364 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12366 SmallVector<SDValue, 4> Ops;
12367 EVT ConcatVT = N0.getOperand(0).getValueType();
12368 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12369 unsigned NumConcats = NumElts / NumElemsPerConcat;
12371 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12372 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12373 // half vector elements.
12374 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12375 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12376 SVN->getMask().end(), [](int i) { return i == -1; })) {
12377 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12378 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12379 N1 = DAG.getUNDEF(ConcatVT);
12380 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12383 // Look at every vector that's inserted. We're looking for exact
12384 // subvector-sized copies from a concatenated vector
12385 for (unsigned I = 0; I != NumConcats; ++I) {
12386 // Make sure we're dealing with a copy.
12387 unsigned Begin = I * NumElemsPerConcat;
12388 bool AllUndef = true, NoUndef = true;
12389 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12390 if (SVN->getMaskElt(J) >= 0)
12397 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12400 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12401 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12404 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12405 if (FirstElt < N0.getNumOperands())
12406 Ops.push_back(N0.getOperand(FirstElt));
12408 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12410 } else if (AllUndef) {
12411 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12412 } else { // Mixed with general masks and undefs, can't do optimization.
12417 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12420 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12421 EVT VT = N->getValueType(0);
12422 unsigned NumElts = VT.getVectorNumElements();
12424 SDValue N0 = N->getOperand(0);
12425 SDValue N1 = N->getOperand(1);
12427 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12429 // Canonicalize shuffle undef, undef -> undef
12430 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12431 return DAG.getUNDEF(VT);
12433 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12435 // Canonicalize shuffle v, v -> v, undef
12437 SmallVector<int, 8> NewMask;
12438 for (unsigned i = 0; i != NumElts; ++i) {
12439 int Idx = SVN->getMaskElt(i);
12440 if (Idx >= (int)NumElts) Idx -= NumElts;
12441 NewMask.push_back(Idx);
12443 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12447 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12448 if (N0.getOpcode() == ISD::UNDEF) {
12449 SmallVector<int, 8> NewMask;
12450 for (unsigned i = 0; i != NumElts; ++i) {
12451 int Idx = SVN->getMaskElt(i);
12453 if (Idx >= (int)NumElts)
12456 Idx = -1; // remove reference to lhs
12458 NewMask.push_back(Idx);
12460 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12464 // Remove references to rhs if it is undef
12465 if (N1.getOpcode() == ISD::UNDEF) {
12466 bool Changed = false;
12467 SmallVector<int, 8> NewMask;
12468 for (unsigned i = 0; i != NumElts; ++i) {
12469 int Idx = SVN->getMaskElt(i);
12470 if (Idx >= (int)NumElts) {
12474 NewMask.push_back(Idx);
12477 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12480 // If it is a splat, check if the argument vector is another splat or a
12482 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12483 SDNode *V = N0.getNode();
12485 // If this is a bit convert that changes the element type of the vector but
12486 // not the number of vector elements, look through it. Be careful not to
12487 // look though conversions that change things like v4f32 to v2f64.
12488 if (V->getOpcode() == ISD::BITCAST) {
12489 SDValue ConvInput = V->getOperand(0);
12490 if (ConvInput.getValueType().isVector() &&
12491 ConvInput.getValueType().getVectorNumElements() == NumElts)
12492 V = ConvInput.getNode();
12495 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12496 assert(V->getNumOperands() == NumElts &&
12497 "BUILD_VECTOR has wrong number of operands");
12499 bool AllSame = true;
12500 for (unsigned i = 0; i != NumElts; ++i) {
12501 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12502 Base = V->getOperand(i);
12506 // Splat of <u, u, u, u>, return <u, u, u, u>
12507 if (!Base.getNode())
12509 for (unsigned i = 0; i != NumElts; ++i) {
12510 if (V->getOperand(i) != Base) {
12515 // Splat of <x, x, x, x>, return <x, x, x, x>
12519 // Canonicalize any other splat as a build_vector.
12520 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12521 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12522 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12523 V->getValueType(0), Ops);
12525 // We may have jumped through bitcasts, so the type of the
12526 // BUILD_VECTOR may not match the type of the shuffle.
12527 if (V->getValueType(0) != VT)
12528 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12533 // There are various patterns used to build up a vector from smaller vectors,
12534 // subvectors, or elements. Scan chains of these and replace unused insertions
12535 // or components with undef.
12536 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12539 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12540 Level < AfterLegalizeVectorOps &&
12541 (N1.getOpcode() == ISD::UNDEF ||
12542 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12543 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12544 SDValue V = partitionShuffleOfConcats(N, DAG);
12550 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12551 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12552 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12553 SmallVector<SDValue, 8> Ops;
12554 for (int M : SVN->getMask()) {
12555 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12557 int Idx = M % NumElts;
12558 SDValue &S = (M < (int)NumElts ? N0 : N1);
12559 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12560 Op = S.getOperand(Idx);
12561 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12563 Op = S.getOperand(0);
12565 // Operand can't be combined - bail out.
12571 if (Ops.size() == VT.getVectorNumElements()) {
12572 // BUILD_VECTOR requires all inputs to be of the same type, find the
12573 // maximum type and extend them all.
12574 EVT SVT = VT.getScalarType();
12575 if (SVT.isInteger())
12576 for (SDValue &Op : Ops)
12577 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12578 if (SVT != VT.getScalarType())
12579 for (SDValue &Op : Ops)
12580 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12581 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12582 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12583 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12587 // If this shuffle only has a single input that is a bitcasted shuffle,
12588 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12589 // back to their original types.
12590 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12591 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12592 TLI.isTypeLegal(VT)) {
12594 // Peek through the bitcast only if there is one user.
12596 while (BC0.getOpcode() == ISD::BITCAST) {
12597 if (!BC0.hasOneUse())
12599 BC0 = BC0.getOperand(0);
12602 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12604 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12606 SmallVector<int, 8> NewMask;
12608 for (int s = 0; s != Scale; ++s)
12609 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12613 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12614 EVT SVT = VT.getScalarType();
12615 EVT InnerVT = BC0->getValueType(0);
12616 EVT InnerSVT = InnerVT.getScalarType();
12618 // Determine which shuffle works with the smaller scalar type.
12619 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12620 EVT ScaleSVT = ScaleVT.getScalarType();
12622 if (TLI.isTypeLegal(ScaleVT) &&
12623 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12624 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12626 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12627 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12629 // Scale the shuffle masks to the smaller scalar type.
12630 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12631 SmallVector<int, 8> InnerMask =
12632 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12633 SmallVector<int, 8> OuterMask =
12634 ScaleShuffleMask(SVN->getMask(), OuterScale);
12636 // Merge the shuffle masks.
12637 SmallVector<int, 8> NewMask;
12638 for (int M : OuterMask)
12639 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12641 // Test for shuffle mask legality over both commutations.
12642 SDValue SV0 = BC0->getOperand(0);
12643 SDValue SV1 = BC0->getOperand(1);
12644 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12646 std::swap(SV0, SV1);
12647 ShuffleVectorSDNode::commuteMask(NewMask);
12648 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12652 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12653 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12654 return DAG.getNode(
12655 ISD::BITCAST, SDLoc(N), VT,
12656 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12662 // Canonicalize shuffles according to rules:
12663 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12664 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12665 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12666 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12667 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12668 TLI.isTypeLegal(VT)) {
12669 // The incoming shuffle must be of the same type as the result of the
12670 // current shuffle.
12671 assert(N1->getOperand(0).getValueType() == VT &&
12672 "Shuffle types don't match");
12674 SDValue SV0 = N1->getOperand(0);
12675 SDValue SV1 = N1->getOperand(1);
12676 bool HasSameOp0 = N0 == SV0;
12677 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12678 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12679 // Commute the operands of this shuffle so that next rule
12681 return DAG.getCommutedVectorShuffle(*SVN);
12684 // Try to fold according to rules:
12685 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12686 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12687 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12688 // Don't try to fold shuffles with illegal type.
12689 // Only fold if this shuffle is the only user of the other shuffle.
12690 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12691 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12692 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12694 // The incoming shuffle must be of the same type as the result of the
12695 // current shuffle.
12696 assert(OtherSV->getOperand(0).getValueType() == VT &&
12697 "Shuffle types don't match");
12700 SmallVector<int, 4> Mask;
12701 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12702 // operand, and SV1 as the second operand.
12703 for (unsigned i = 0; i != NumElts; ++i) {
12704 int Idx = SVN->getMaskElt(i);
12706 // Propagate Undef.
12707 Mask.push_back(Idx);
12711 SDValue CurrentVec;
12712 if (Idx < (int)NumElts) {
12713 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12714 // shuffle mask to identify which vector is actually referenced.
12715 Idx = OtherSV->getMaskElt(Idx);
12717 // Propagate Undef.
12718 Mask.push_back(Idx);
12722 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12723 : OtherSV->getOperand(1);
12725 // This shuffle index references an element within N1.
12729 // Simple case where 'CurrentVec' is UNDEF.
12730 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12731 Mask.push_back(-1);
12735 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12736 // will be the first or second operand of the combined shuffle.
12737 Idx = Idx % NumElts;
12738 if (!SV0.getNode() || SV0 == CurrentVec) {
12739 // Ok. CurrentVec is the left hand side.
12740 // Update the mask accordingly.
12742 Mask.push_back(Idx);
12746 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12747 if (SV1.getNode() && SV1 != CurrentVec)
12750 // Ok. CurrentVec is the right hand side.
12751 // Update the mask accordingly.
12753 Mask.push_back(Idx + NumElts);
12756 // Check if all indices in Mask are Undef. In case, propagate Undef.
12757 bool isUndefMask = true;
12758 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12759 isUndefMask &= Mask[i] < 0;
12762 return DAG.getUNDEF(VT);
12764 if (!SV0.getNode())
12765 SV0 = DAG.getUNDEF(VT);
12766 if (!SV1.getNode())
12767 SV1 = DAG.getUNDEF(VT);
12769 // Avoid introducing shuffles with illegal mask.
12770 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12771 ShuffleVectorSDNode::commuteMask(Mask);
12773 if (!TLI.isShuffleMaskLegal(Mask, VT))
12776 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12777 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12778 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12779 std::swap(SV0, SV1);
12782 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12783 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12784 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12785 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12791 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12792 SDValue InVal = N->getOperand(0);
12793 EVT VT = N->getValueType(0);
12795 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12796 // with a VECTOR_SHUFFLE.
12797 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12798 SDValue InVec = InVal->getOperand(0);
12799 SDValue EltNo = InVal->getOperand(1);
12801 // FIXME: We could support implicit truncation if the shuffle can be
12802 // scaled to a smaller vector scalar type.
12803 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12804 if (C0 && VT == InVec.getValueType() &&
12805 VT.getScalarType() == InVal.getValueType()) {
12806 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12807 int Elt = C0->getZExtValue();
12810 if (TLI.isShuffleMaskLegal(NewMask, VT))
12811 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12819 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12820 SDValue N0 = N->getOperand(0);
12821 SDValue N2 = N->getOperand(2);
12823 // If the input vector is a concatenation, and the insert replaces
12824 // one of the halves, we can optimize into a single concat_vectors.
12825 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12826 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12827 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12828 EVT VT = N->getValueType(0);
12830 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12831 // (concat_vectors Z, Y)
12833 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12834 N->getOperand(1), N0.getOperand(1));
12836 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12837 // (concat_vectors X, Z)
12838 if (InsIdx == VT.getVectorNumElements()/2)
12839 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12840 N0.getOperand(0), N->getOperand(1));
12846 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12847 SDValue N0 = N->getOperand(0);
12849 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12850 if (N0->getOpcode() == ISD::FP16_TO_FP)
12851 return N0->getOperand(0);
12856 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12857 /// with the destination vector and a zero vector.
12858 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12859 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12860 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12861 EVT VT = N->getValueType(0);
12862 SDValue LHS = N->getOperand(0);
12863 SDValue RHS = N->getOperand(1);
12866 // Make sure we're not running after operation legalization where it
12867 // may have custom lowered the vector shuffles.
12868 if (LegalOperations)
12871 if (N->getOpcode() != ISD::AND)
12874 if (RHS.getOpcode() == ISD::BITCAST)
12875 RHS = RHS.getOperand(0);
12877 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12878 SmallVector<int, 8> Indices;
12879 unsigned NumElts = RHS.getNumOperands();
12881 for (unsigned i = 0; i != NumElts; ++i) {
12882 SDValue Elt = RHS.getOperand(i);
12883 if (!isa<ConstantSDNode>(Elt))
12886 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12887 Indices.push_back(i);
12888 else if (cast<ConstantSDNode>(Elt)->isNullValue())
12889 Indices.push_back(NumElts+i);
12894 // Let's see if the target supports this vector_shuffle.
12895 EVT RVT = RHS.getValueType();
12896 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12899 // Return the new VECTOR_SHUFFLE node.
12900 EVT EltVT = RVT.getVectorElementType();
12901 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12902 DAG.getConstant(0, dl, EltVT));
12903 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12904 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12905 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12906 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12912 /// Visit a binary vector operation, like ADD.
12913 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12914 assert(N->getValueType(0).isVector() &&
12915 "SimplifyVBinOp only works on vectors!");
12917 SDValue LHS = N->getOperand(0);
12918 SDValue RHS = N->getOperand(1);
12920 if (SDValue Shuffle = XformToShuffleWithZero(N))
12923 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12925 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12926 RHS.getOpcode() == ISD::BUILD_VECTOR) {
12927 // Check if both vectors are constants. If not bail out.
12928 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12929 cast<BuildVectorSDNode>(RHS)->isConstant()))
12932 SmallVector<SDValue, 8> Ops;
12933 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12934 SDValue LHSOp = LHS.getOperand(i);
12935 SDValue RHSOp = RHS.getOperand(i);
12937 // Can't fold divide by zero.
12938 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12939 N->getOpcode() == ISD::FDIV) {
12940 if ((RHSOp.getOpcode() == ISD::Constant &&
12941 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12942 (RHSOp.getOpcode() == ISD::ConstantFP &&
12943 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12947 EVT VT = LHSOp.getValueType();
12948 EVT RVT = RHSOp.getValueType();
12950 // Integer BUILD_VECTOR operands may have types larger than the element
12951 // size (e.g., when the element type is not legal). Prior to type
12952 // legalization, the types may not match between the two BUILD_VECTORS.
12953 // Truncate one of the operands to make them match.
12954 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12955 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12957 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12961 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12963 if (FoldOp.getOpcode() != ISD::UNDEF &&
12964 FoldOp.getOpcode() != ISD::Constant &&
12965 FoldOp.getOpcode() != ISD::ConstantFP)
12967 Ops.push_back(FoldOp);
12968 AddToWorklist(FoldOp.getNode());
12971 if (Ops.size() == LHS.getNumOperands())
12972 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12975 // Type legalization might introduce new shuffles in the DAG.
12976 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12977 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12978 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12979 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12980 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12981 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12982 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12983 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12985 if (SVN0->getMask().equals(SVN1->getMask())) {
12986 EVT VT = N->getValueType(0);
12987 SDValue UndefVector = LHS.getOperand(1);
12988 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12989 LHS.getOperand(0), RHS.getOperand(0));
12990 AddUsersToWorklist(N);
12991 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12992 &SVN0->getMask()[0]);
12999 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13000 SDValue N1, SDValue N2){
13001 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13003 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13004 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13006 // If we got a simplified select_cc node back from SimplifySelectCC, then
13007 // break it down into a new SETCC node, and a new SELECT node, and then return
13008 // the SELECT node, since we were called with a SELECT node.
13009 if (SCC.getNode()) {
13010 // Check to see if we got a select_cc back (to turn into setcc/select).
13011 // Otherwise, just return whatever node we got back, like fabs.
13012 if (SCC.getOpcode() == ISD::SELECT_CC) {
13013 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13015 SCC.getOperand(0), SCC.getOperand(1),
13016 SCC.getOperand(4));
13017 AddToWorklist(SETCC.getNode());
13018 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13019 SCC.getOperand(2), SCC.getOperand(3));
13027 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13028 /// being selected between, see if we can simplify the select. Callers of this
13029 /// should assume that TheSelect is deleted if this returns true. As such, they
13030 /// should return the appropriate thing (e.g. the node) back to the top-level of
13031 /// the DAG combiner loop to avoid it being looked at.
13032 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13035 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13036 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13037 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13038 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13039 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13040 SDValue Sqrt = RHS;
13043 const ConstantFPSDNode *NegZero = nullptr;
13045 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13046 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13047 CmpLHS = TheSelect->getOperand(0);
13048 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13050 // SELECT or VSELECT
13051 SDValue Cmp = TheSelect->getOperand(0);
13052 if (Cmp.getOpcode() == ISD::SETCC) {
13053 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13054 CmpLHS = Cmp.getOperand(0);
13055 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13058 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13059 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13060 CC == ISD::SETULT || CC == ISD::SETLT)) {
13061 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13062 CombineTo(TheSelect, Sqrt);
13067 // Cannot simplify select with vector condition
13068 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13070 // If this is a select from two identical things, try to pull the operation
13071 // through the select.
13072 if (LHS.getOpcode() != RHS.getOpcode() ||
13073 !LHS.hasOneUse() || !RHS.hasOneUse())
13076 // If this is a load and the token chain is identical, replace the select
13077 // of two loads with a load through a select of the address to load from.
13078 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13079 // constants have been dropped into the constant pool.
13080 if (LHS.getOpcode() == ISD::LOAD) {
13081 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13082 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13084 // Token chains must be identical.
13085 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13086 // Do not let this transformation reduce the number of volatile loads.
13087 LLD->isVolatile() || RLD->isVolatile() ||
13088 // FIXME: If either is a pre/post inc/dec load,
13089 // we'd need to split out the address adjustment.
13090 LLD->isIndexed() || RLD->isIndexed() ||
13091 // If this is an EXTLOAD, the VT's must match.
13092 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13093 // If this is an EXTLOAD, the kind of extension must match.
13094 (LLD->getExtensionType() != RLD->getExtensionType() &&
13095 // The only exception is if one of the extensions is anyext.
13096 LLD->getExtensionType() != ISD::EXTLOAD &&
13097 RLD->getExtensionType() != ISD::EXTLOAD) ||
13098 // FIXME: this discards src value information. This is
13099 // over-conservative. It would be beneficial to be able to remember
13100 // both potential memory locations. Since we are discarding
13101 // src value info, don't do the transformation if the memory
13102 // locations are not in the default address space.
13103 LLD->getPointerInfo().getAddrSpace() != 0 ||
13104 RLD->getPointerInfo().getAddrSpace() != 0 ||
13105 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13106 LLD->getBasePtr().getValueType()))
13109 // Check that the select condition doesn't reach either load. If so,
13110 // folding this will induce a cycle into the DAG. If not, this is safe to
13111 // xform, so create a select of the addresses.
13113 if (TheSelect->getOpcode() == ISD::SELECT) {
13114 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13115 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13116 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13118 // The loads must not depend on one another.
13119 if (LLD->isPredecessorOf(RLD) ||
13120 RLD->isPredecessorOf(LLD))
13122 Addr = DAG.getSelect(SDLoc(TheSelect),
13123 LLD->getBasePtr().getValueType(),
13124 TheSelect->getOperand(0), LLD->getBasePtr(),
13125 RLD->getBasePtr());
13126 } else { // Otherwise SELECT_CC
13127 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13128 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13130 if ((LLD->hasAnyUseOfValue(1) &&
13131 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13132 (RLD->hasAnyUseOfValue(1) &&
13133 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13136 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13137 LLD->getBasePtr().getValueType(),
13138 TheSelect->getOperand(0),
13139 TheSelect->getOperand(1),
13140 LLD->getBasePtr(), RLD->getBasePtr(),
13141 TheSelect->getOperand(4));
13145 // It is safe to replace the two loads if they have different alignments,
13146 // but the new load must be the minimum (most restrictive) alignment of the
13148 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13149 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13150 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13151 Load = DAG.getLoad(TheSelect->getValueType(0),
13153 // FIXME: Discards pointer and AA info.
13154 LLD->getChain(), Addr, MachinePointerInfo(),
13155 LLD->isVolatile(), LLD->isNonTemporal(),
13156 isInvariant, Alignment);
13158 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13159 RLD->getExtensionType() : LLD->getExtensionType(),
13161 TheSelect->getValueType(0),
13162 // FIXME: Discards pointer and AA info.
13163 LLD->getChain(), Addr, MachinePointerInfo(),
13164 LLD->getMemoryVT(), LLD->isVolatile(),
13165 LLD->isNonTemporal(), isInvariant, Alignment);
13168 // Users of the select now use the result of the load.
13169 CombineTo(TheSelect, Load);
13171 // Users of the old loads now use the new load's chain. We know the
13172 // old-load value is dead now.
13173 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13174 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13181 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13182 /// where 'cond' is the comparison specified by CC.
13183 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13184 SDValue N2, SDValue N3,
13185 ISD::CondCode CC, bool NotExtCompare) {
13186 // (x ? y : y) -> y.
13187 if (N2 == N3) return N2;
13189 EVT VT = N2.getValueType();
13190 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13191 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13192 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
13194 // Determine if the condition we're dealing with is constant
13195 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13196 N0, N1, CC, DL, false);
13197 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13198 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
13200 // fold select_cc true, x, y -> x
13201 if (SCCC && !SCCC->isNullValue())
13203 // fold select_cc false, x, y -> y
13204 if (SCCC && SCCC->isNullValue())
13207 // Check to see if we can simplify the select into an fabs node
13208 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13209 // Allow either -0.0 or 0.0
13210 if (CFP->getValueAPF().isZero()) {
13211 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13212 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13213 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13214 N2 == N3.getOperand(0))
13215 return DAG.getNode(ISD::FABS, DL, VT, N0);
13217 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13218 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13219 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13220 N2.getOperand(0) == N3)
13221 return DAG.getNode(ISD::FABS, DL, VT, N3);
13225 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13226 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13227 // in it. This is a win when the constant is not otherwise available because
13228 // it replaces two constant pool loads with one. We only do this if the FP
13229 // type is known to be legal, because if it isn't, then we are before legalize
13230 // types an we want the other legalization to happen first (e.g. to avoid
13231 // messing with soft float) and if the ConstantFP is not legal, because if
13232 // it is legal, we may not need to store the FP constant in a constant pool.
13233 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13234 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13235 if (TLI.isTypeLegal(N2.getValueType()) &&
13236 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13237 TargetLowering::Legal &&
13238 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13239 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13240 // If both constants have multiple uses, then we won't need to do an
13241 // extra load, they are likely around in registers for other users.
13242 (TV->hasOneUse() || FV->hasOneUse())) {
13243 Constant *Elts[] = {
13244 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13245 const_cast<ConstantFP*>(TV->getConstantFPValue())
13247 Type *FPTy = Elts[0]->getType();
13248 const DataLayout &TD = *TLI.getDataLayout();
13250 // Create a ConstantArray of the two constants.
13251 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13252 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13253 TD.getPrefTypeAlignment(FPTy));
13254 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13256 // Get the offsets to the 0 and 1 element of the array so that we can
13257 // select between them.
13258 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13259 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13260 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13262 SDValue Cond = DAG.getSetCC(DL,
13263 getSetCCResultType(N0.getValueType()),
13265 AddToWorklist(Cond.getNode());
13266 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13268 AddToWorklist(CstOffset.getNode());
13269 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13271 AddToWorklist(CPIdx.getNode());
13272 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13273 MachinePointerInfo::getConstantPool(), false,
13274 false, false, Alignment);
13278 // Check to see if we can perform the "gzip trick", transforming
13279 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13280 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13281 (N1C->isNullValue() || // (a < 0) ? b : 0
13282 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
13283 EVT XType = N0.getValueType();
13284 EVT AType = N2.getValueType();
13285 if (XType.bitsGE(AType)) {
13286 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13287 // single-bit constant.
13288 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13289 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13290 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13291 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13292 getShiftAmountTy(N0.getValueType()));
13293 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13295 AddToWorklist(Shift.getNode());
13297 if (XType.bitsGT(AType)) {
13298 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13299 AddToWorklist(Shift.getNode());
13302 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13305 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13307 DAG.getConstant(XType.getSizeInBits() - 1,
13309 getShiftAmountTy(N0.getValueType())));
13310 AddToWorklist(Shift.getNode());
13312 if (XType.bitsGT(AType)) {
13313 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13314 AddToWorklist(Shift.getNode());
13317 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13321 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13322 // where y is has a single bit set.
13323 // A plaintext description would be, we can turn the SELECT_CC into an AND
13324 // when the condition can be materialized as an all-ones register. Any
13325 // single bit-test can be materialized as an all-ones register with
13326 // shift-left and shift-right-arith.
13327 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13328 N0->getValueType(0) == VT &&
13329 N1C && N1C->isNullValue() &&
13330 N2C && N2C->isNullValue()) {
13331 SDValue AndLHS = N0->getOperand(0);
13332 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13333 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13334 // Shift the tested bit over the sign bit.
13335 APInt AndMask = ConstAndRHS->getAPIntValue();
13337 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13338 getShiftAmountTy(AndLHS.getValueType()));
13339 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13341 // Now arithmetic right shift it all the way over, so the result is either
13342 // all-ones, or zero.
13344 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13345 getShiftAmountTy(Shl.getValueType()));
13346 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13348 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13352 // fold select C, 16, 0 -> shl C, 4
13353 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13354 TLI.getBooleanContents(N0.getValueType()) ==
13355 TargetLowering::ZeroOrOneBooleanContent) {
13357 // If the caller doesn't want us to simplify this into a zext of a compare,
13359 if (NotExtCompare && N2C->getAPIntValue() == 1)
13362 // Get a SetCC of the condition
13363 // NOTE: Don't create a SETCC if it's not legal on this target.
13364 if (!LegalOperations ||
13365 TLI.isOperationLegal(ISD::SETCC,
13366 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13368 // cast from setcc result type to select result type
13370 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13372 if (N2.getValueType().bitsLT(SCC.getValueType()))
13373 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13374 N2.getValueType());
13376 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13377 N2.getValueType(), SCC);
13379 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13380 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13381 N2.getValueType(), SCC);
13384 AddToWorklist(SCC.getNode());
13385 AddToWorklist(Temp.getNode());
13387 if (N2C->getAPIntValue() == 1)
13390 // shl setcc result by log2 n2c
13391 return DAG.getNode(
13392 ISD::SHL, DL, N2.getValueType(), Temp,
13393 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13394 getShiftAmountTy(Temp.getValueType())));
13398 // Check to see if this is the equivalent of setcc
13399 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13400 // otherwise, go ahead with the folds.
13401 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13402 EVT XType = N0.getValueType();
13403 if (!LegalOperations ||
13404 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13405 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13406 if (Res.getValueType() != VT)
13407 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13411 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13412 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13413 (!LegalOperations ||
13414 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13415 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13416 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13417 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13419 getShiftAmountTy(Ctlz.getValueType())));
13421 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13422 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13424 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13425 XType, DAG.getConstant(0, DL, XType), N0);
13426 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13427 return DAG.getNode(ISD::SRL, DL, XType,
13428 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13429 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13430 getShiftAmountTy(XType)));
13432 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13433 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13435 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13436 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13437 getShiftAmountTy(N0.getValueType())));
13438 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13443 // Check to see if this is an integer abs.
13444 // select_cc setg[te] X, 0, X, -X ->
13445 // select_cc setgt X, -1, X, -X ->
13446 // select_cc setl[te] X, 0, -X, X ->
13447 // select_cc setlt X, 1, -X, X ->
13448 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13450 ConstantSDNode *SubC = nullptr;
13451 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13452 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13453 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13454 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13455 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13456 (N1C->isOne() && CC == ISD::SETLT)) &&
13457 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13458 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13460 EVT XType = N0.getValueType();
13461 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13463 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13465 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13466 getShiftAmountTy(N0.getValueType())));
13467 SDValue Add = DAG.getNode(ISD::ADD, DL,
13469 AddToWorklist(Shift.getNode());
13470 AddToWorklist(Add.getNode());
13471 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13478 /// This is a stub for TargetLowering::SimplifySetCC.
13479 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13480 SDValue N1, ISD::CondCode Cond,
13481 SDLoc DL, bool foldBooleans) {
13482 TargetLowering::DAGCombinerInfo
13483 DagCombineInfo(DAG, Level, false, this);
13484 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13487 /// Given an ISD::SDIV node expressing a divide by constant, return
13488 /// a DAG expression to select that will generate the same value by multiplying
13489 /// by a magic number.
13490 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13491 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13492 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13496 // Avoid division by zero.
13497 if (!C->getAPIntValue())
13500 std::vector<SDNode*> Built;
13502 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13504 for (SDNode *N : Built)
13509 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13510 /// DAG expression that will generate the same value by right shifting.
13511 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13512 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13516 // Avoid division by zero.
13517 if (!C->getAPIntValue())
13520 std::vector<SDNode *> Built;
13521 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13523 for (SDNode *N : Built)
13528 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13529 /// expression that will generate the same value by multiplying by a magic
13531 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13532 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13533 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13537 // Avoid division by zero.
13538 if (!C->getAPIntValue())
13541 std::vector<SDNode*> Built;
13543 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13545 for (SDNode *N : Built)
13550 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13551 if (Level >= AfterLegalizeDAG)
13554 // Expose the DAG combiner to the target combiner implementations.
13555 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13557 unsigned Iterations = 0;
13558 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13560 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13561 // For the reciprocal, we need to find the zero of the function:
13562 // F(X) = A X - 1 [which has a zero at X = 1/A]
13564 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13565 // does not require additional intermediate precision]
13566 EVT VT = Op.getValueType();
13568 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13570 AddToWorklist(Est.getNode());
13572 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13573 for (unsigned i = 0; i < Iterations; ++i) {
13574 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13575 AddToWorklist(NewEst.getNode());
13577 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13578 AddToWorklist(NewEst.getNode());
13580 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13581 AddToWorklist(NewEst.getNode());
13583 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13584 AddToWorklist(Est.getNode());
13593 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13594 /// For the reciprocal sqrt, we need to find the zero of the function:
13595 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13597 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13598 /// As a result, we precompute A/2 prior to the iteration loop.
13599 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13600 unsigned Iterations) {
13601 EVT VT = Arg.getValueType();
13603 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13605 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13606 // this entire sequence requires only one FP constant.
13607 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13608 AddToWorklist(HalfArg.getNode());
13610 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13611 AddToWorklist(HalfArg.getNode());
13613 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13614 for (unsigned i = 0; i < Iterations; ++i) {
13615 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13616 AddToWorklist(NewEst.getNode());
13618 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13619 AddToWorklist(NewEst.getNode());
13621 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13622 AddToWorklist(NewEst.getNode());
13624 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13625 AddToWorklist(Est.getNode());
13630 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13631 /// For the reciprocal sqrt, we need to find the zero of the function:
13632 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13634 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13635 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13636 unsigned Iterations) {
13637 EVT VT = Arg.getValueType();
13639 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13640 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13642 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13643 for (unsigned i = 0; i < Iterations; ++i) {
13644 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13645 AddToWorklist(HalfEst.getNode());
13647 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13648 AddToWorklist(Est.getNode());
13650 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13651 AddToWorklist(Est.getNode());
13653 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13654 AddToWorklist(Est.getNode());
13656 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13657 AddToWorklist(Est.getNode());
13662 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13663 if (Level >= AfterLegalizeDAG)
13666 // Expose the DAG combiner to the target combiner implementations.
13667 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13668 unsigned Iterations = 0;
13669 bool UseOneConstNR = false;
13670 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13671 AddToWorklist(Est.getNode());
13673 Est = UseOneConstNR ?
13674 BuildRsqrtNROneConst(Op, Est, Iterations) :
13675 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13683 /// Return true if base is a frame index, which is known not to alias with
13684 /// anything but itself. Provides base object and offset as results.
13685 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13686 const GlobalValue *&GV, const void *&CV) {
13687 // Assume it is a primitive operation.
13688 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13690 // If it's an adding a simple constant then integrate the offset.
13691 if (Base.getOpcode() == ISD::ADD) {
13692 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13693 Base = Base.getOperand(0);
13694 Offset += C->getZExtValue();
13698 // Return the underlying GlobalValue, and update the Offset. Return false
13699 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13700 // by multiple nodes with different offsets.
13701 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13702 GV = G->getGlobal();
13703 Offset += G->getOffset();
13707 // Return the underlying Constant value, and update the Offset. Return false
13708 // for ConstantSDNodes since the same constant pool entry may be represented
13709 // by multiple nodes with different offsets.
13710 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13711 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13712 : (const void *)C->getConstVal();
13713 Offset += C->getOffset();
13716 // If it's any of the following then it can't alias with anything but itself.
13717 return isa<FrameIndexSDNode>(Base);
13720 /// Return true if there is any possibility that the two addresses overlap.
13721 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13722 // If they are the same then they must be aliases.
13723 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13725 // If they are both volatile then they cannot be reordered.
13726 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13728 // Gather base node and offset information.
13729 SDValue Base1, Base2;
13730 int64_t Offset1, Offset2;
13731 const GlobalValue *GV1, *GV2;
13732 const void *CV1, *CV2;
13733 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13734 Base1, Offset1, GV1, CV1);
13735 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13736 Base2, Offset2, GV2, CV2);
13738 // If they have a same base address then check to see if they overlap.
13739 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13740 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13741 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13743 // It is possible for different frame indices to alias each other, mostly
13744 // when tail call optimization reuses return address slots for arguments.
13745 // To catch this case, look up the actual index of frame indices to compute
13746 // the real alias relationship.
13747 if (isFrameIndex1 && isFrameIndex2) {
13748 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13749 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13750 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13751 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13752 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13755 // Otherwise, if we know what the bases are, and they aren't identical, then
13756 // we know they cannot alias.
13757 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13760 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13761 // compared to the size and offset of the access, we may be able to prove they
13762 // do not alias. This check is conservative for now to catch cases created by
13763 // splitting vector types.
13764 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13765 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13766 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13767 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13768 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13769 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13770 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13772 // There is no overlap between these relatively aligned accesses of similar
13773 // size, return no alias.
13774 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13775 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13779 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13781 : DAG.getSubtarget().useAA();
13783 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13784 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13788 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13789 // Use alias analysis information.
13790 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13791 Op1->getSrcValueOffset());
13792 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13793 Op0->getSrcValueOffset() - MinOffset;
13794 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13795 Op1->getSrcValueOffset() - MinOffset;
13796 AliasAnalysis::AliasResult AAResult =
13797 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13799 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13800 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13802 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13803 if (AAResult == AliasAnalysis::NoAlias)
13807 // Otherwise we have to assume they alias.
13811 /// Walk up chain skipping non-aliasing memory nodes,
13812 /// looking for aliasing nodes and adding them to the Aliases vector.
13813 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13814 SmallVectorImpl<SDValue> &Aliases) {
13815 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13816 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13818 // Get alias information for node.
13819 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13822 Chains.push_back(OriginalChain);
13823 unsigned Depth = 0;
13825 // Look at each chain and determine if it is an alias. If so, add it to the
13826 // aliases list. If not, then continue up the chain looking for the next
13828 while (!Chains.empty()) {
13829 SDValue Chain = Chains.back();
13832 // For TokenFactor nodes, look at each operand and only continue up the
13833 // chain until we find two aliases. If we've seen two aliases, assume we'll
13834 // find more and revert to original chain since the xform is unlikely to be
13837 // FIXME: The depth check could be made to return the last non-aliasing
13838 // chain we found before we hit a tokenfactor rather than the original
13840 if (Depth > 6 || Aliases.size() == 2) {
13842 Aliases.push_back(OriginalChain);
13846 // Don't bother if we've been before.
13847 if (!Visited.insert(Chain.getNode()).second)
13850 switch (Chain.getOpcode()) {
13851 case ISD::EntryToken:
13852 // Entry token is ideal chain operand, but handled in FindBetterChain.
13857 // Get alias information for Chain.
13858 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13859 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13861 // If chain is alias then stop here.
13862 if (!(IsLoad && IsOpLoad) &&
13863 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13864 Aliases.push_back(Chain);
13866 // Look further up the chain.
13867 Chains.push_back(Chain.getOperand(0));
13873 case ISD::TokenFactor:
13874 // We have to check each of the operands of the token factor for "small"
13875 // token factors, so we queue them up. Adding the operands to the queue
13876 // (stack) in reverse order maintains the original order and increases the
13877 // likelihood that getNode will find a matching token factor (CSE.)
13878 if (Chain.getNumOperands() > 16) {
13879 Aliases.push_back(Chain);
13882 for (unsigned n = Chain.getNumOperands(); n;)
13883 Chains.push_back(Chain.getOperand(--n));
13888 // For all other instructions we will just have to take what we can get.
13889 Aliases.push_back(Chain);
13894 // We need to be careful here to also search for aliases through the
13895 // value operand of a store, etc. Consider the following situation:
13897 // L1 = load Token1, %52
13898 // S1 = store Token1, L1, %51
13899 // L2 = load Token1, %52+8
13900 // S2 = store Token1, L2, %51+8
13901 // Token2 = Token(S1, S2)
13902 // L3 = load Token2, %53
13903 // S3 = store Token2, L3, %52
13904 // L4 = load Token2, %53+8
13905 // S4 = store Token2, L4, %52+8
13906 // If we search for aliases of S3 (which loads address %52), and we look
13907 // only through the chain, then we'll miss the trivial dependence on L1
13908 // (which also loads from %52). We then might change all loads and
13909 // stores to use Token1 as their chain operand, which could result in
13910 // copying %53 into %52 before copying %52 into %51 (which should
13913 // The problem is, however, that searching for such data dependencies
13914 // can become expensive, and the cost is not directly related to the
13915 // chain depth. Instead, we'll rule out such configurations here by
13916 // insisting that we've visited all chain users (except for users
13917 // of the original chain, which is not necessary). When doing this,
13918 // we need to look through nodes we don't care about (otherwise, things
13919 // like register copies will interfere with trivial cases).
13921 SmallVector<const SDNode *, 16> Worklist;
13922 for (const SDNode *N : Visited)
13923 if (N != OriginalChain.getNode())
13924 Worklist.push_back(N);
13926 while (!Worklist.empty()) {
13927 const SDNode *M = Worklist.pop_back_val();
13929 // We have already visited M, and want to make sure we've visited any uses
13930 // of M that we care about. For uses that we've not visisted, and don't
13931 // care about, queue them to the worklist.
13933 for (SDNode::use_iterator UI = M->use_begin(),
13934 UIE = M->use_end(); UI != UIE; ++UI)
13935 if (UI.getUse().getValueType() == MVT::Other &&
13936 Visited.insert(*UI).second) {
13937 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13938 // We've not visited this use, and we care about it (it could have an
13939 // ordering dependency with the original node).
13941 Aliases.push_back(OriginalChain);
13945 // We've not visited this use, but we don't care about it. Mark it as
13946 // visited and enqueue it to the worklist.
13947 Worklist.push_back(*UI);
13952 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13953 /// (aliasing node.)
13954 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13955 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
13957 // Accumulate all the aliases to this node.
13958 GatherAllAliases(N, OldChain, Aliases);
13960 // If no operands then chain to entry token.
13961 if (Aliases.size() == 0)
13962 return DAG.getEntryNode();
13964 // If a single operand then chain to it. We don't need to revisit it.
13965 if (Aliases.size() == 1)
13968 // Construct a custom tailored token factor.
13969 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13972 /// This is the entry point for the file.
13973 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13974 CodeGenOpt::Level OptLevel) {
13975 /// This is the main entry point to this class.
13976 DAGCombiner(*this, AA, OptLevel).Run(Level);