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 (const BinaryWithFlagsSDNode *BinNode =
1456 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1457 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1458 BinNode->Flags.hasNoUnsignedWrap(),
1459 BinNode->Flags.hasNoSignedWrap(),
1460 BinNode->Flags.hasExact());
1462 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1465 return SDValue(CSENode, 0);
1472 /// Given a node, return its input chain if it has one, otherwise return a null
1474 static SDValue getInputChainForNode(SDNode *N) {
1475 if (unsigned NumOps = N->getNumOperands()) {
1476 if (N->getOperand(0).getValueType() == MVT::Other)
1477 return N->getOperand(0);
1478 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1479 return N->getOperand(NumOps-1);
1480 for (unsigned i = 1; i < NumOps-1; ++i)
1481 if (N->getOperand(i).getValueType() == MVT::Other)
1482 return N->getOperand(i);
1487 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1488 // If N has two operands, where one has an input chain equal to the other,
1489 // the 'other' chain is redundant.
1490 if (N->getNumOperands() == 2) {
1491 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1492 return N->getOperand(0);
1493 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1494 return N->getOperand(1);
1497 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1498 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1499 SmallPtrSet<SDNode*, 16> SeenOps;
1500 bool Changed = false; // If we should replace this token factor.
1502 // Start out with this token factor.
1505 // Iterate through token factors. The TFs grows when new token factors are
1507 for (unsigned i = 0; i < TFs.size(); ++i) {
1508 SDNode *TF = TFs[i];
1510 // Check each of the operands.
1511 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1512 SDValue Op = TF->getOperand(i);
1514 switch (Op.getOpcode()) {
1515 case ISD::EntryToken:
1516 // Entry tokens don't need to be added to the list. They are
1521 case ISD::TokenFactor:
1522 if (Op.hasOneUse() &&
1523 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1524 // Queue up for processing.
1525 TFs.push_back(Op.getNode());
1526 // Clean up in case the token factor is removed.
1527 AddToWorklist(Op.getNode());
1534 // Only add if it isn't already in the list.
1535 if (SeenOps.insert(Op.getNode()).second)
1546 // If we've changed things around then replace token factor.
1549 // The entry token is the only possible outcome.
1550 Result = DAG.getEntryNode();
1552 // New and improved token factor.
1553 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1556 // Add users to worklist if AA is enabled, since it may introduce
1557 // a lot of new chained token factors while removing memory deps.
1558 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1559 : DAG.getSubtarget().useAA();
1560 return CombineTo(N, Result, UseAA /*add to worklist*/);
1566 /// MERGE_VALUES can always be eliminated.
1567 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1568 WorklistRemover DeadNodes(*this);
1569 // Replacing results may cause a different MERGE_VALUES to suddenly
1570 // be CSE'd with N, and carry its uses with it. Iterate until no
1571 // uses remain, to ensure that the node can be safely deleted.
1572 // First add the users of this node to the work list so that they
1573 // can be tried again once they have new operands.
1574 AddUsersToWorklist(N);
1576 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1577 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1578 } while (!N->use_empty());
1579 deleteAndRecombine(N);
1580 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1583 SDValue DAGCombiner::visitADD(SDNode *N) {
1584 SDValue N0 = N->getOperand(0);
1585 SDValue N1 = N->getOperand(1);
1586 EVT VT = N0.getValueType();
1589 if (VT.isVector()) {
1590 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1593 // fold (add x, 0) -> x, vector edition
1594 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1596 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1600 // fold (add x, undef) -> undef
1601 if (N0.getOpcode() == ISD::UNDEF)
1603 if (N1.getOpcode() == ISD::UNDEF)
1605 // fold (add c1, c2) -> c1+c2
1606 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1607 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1609 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1610 // canonicalize constant to RHS
1611 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1612 !isConstantIntBuildVectorOrConstantInt(N1))
1613 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1614 // fold (add x, 0) -> x
1615 if (N1C && N1C->isNullValue())
1617 // fold (add Sym, c) -> Sym+c
1618 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1619 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1620 GA->getOpcode() == ISD::GlobalAddress)
1621 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1623 (uint64_t)N1C->getSExtValue());
1624 // fold ((c1-A)+c2) -> (c1+c2)-A
1625 if (N1C && N0.getOpcode() == ISD::SUB)
1626 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1628 return DAG.getNode(ISD::SUB, DL, VT,
1629 DAG.getConstant(N1C->getAPIntValue()+
1630 N0C->getAPIntValue(), DL, VT),
1634 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1636 // fold ((0-A) + B) -> B-A
1637 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1638 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1639 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1640 // fold (A + (0-B)) -> A-B
1641 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1642 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1643 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1644 // fold (A+(B-A)) -> B
1645 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1646 return N1.getOperand(0);
1647 // fold ((B-A)+A) -> B
1648 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1649 return N0.getOperand(0);
1650 // fold (A+(B-(A+C))) to (B-C)
1651 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1652 N0 == N1.getOperand(1).getOperand(0))
1653 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1654 N1.getOperand(1).getOperand(1));
1655 // fold (A+(B-(C+A))) to (B-C)
1656 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1657 N0 == N1.getOperand(1).getOperand(1))
1658 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1659 N1.getOperand(1).getOperand(0));
1660 // fold (A+((B-A)+or-C)) to (B+or-C)
1661 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1662 N1.getOperand(0).getOpcode() == ISD::SUB &&
1663 N0 == N1.getOperand(0).getOperand(1))
1664 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1665 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1667 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1668 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1669 SDValue N00 = N0.getOperand(0);
1670 SDValue N01 = N0.getOperand(1);
1671 SDValue N10 = N1.getOperand(0);
1672 SDValue N11 = N1.getOperand(1);
1674 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1675 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1676 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1677 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1680 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1681 return SDValue(N, 0);
1683 // fold (a+b) -> (a|b) iff a and b share no bits.
1684 if (VT.isInteger() && !VT.isVector()) {
1685 APInt LHSZero, LHSOne;
1686 APInt RHSZero, RHSOne;
1687 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1689 if (LHSZero.getBoolValue()) {
1690 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1692 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1693 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1694 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1695 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1696 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1701 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1702 if (N1.getOpcode() == ISD::SHL &&
1703 N1.getOperand(0).getOpcode() == ISD::SUB)
1704 if (ConstantSDNode *C =
1705 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1706 if (C->getAPIntValue() == 0)
1707 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1708 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1709 N1.getOperand(0).getOperand(1),
1711 if (N0.getOpcode() == ISD::SHL &&
1712 N0.getOperand(0).getOpcode() == ISD::SUB)
1713 if (ConstantSDNode *C =
1714 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1715 if (C->getAPIntValue() == 0)
1716 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1717 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1718 N0.getOperand(0).getOperand(1),
1721 if (N1.getOpcode() == ISD::AND) {
1722 SDValue AndOp0 = N1.getOperand(0);
1723 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1724 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1725 unsigned DestBits = VT.getScalarType().getSizeInBits();
1727 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1728 // and similar xforms where the inner op is either ~0 or 0.
1729 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1731 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1735 // add (sext i1), X -> sub X, (zext i1)
1736 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1737 N0.getOperand(0).getValueType() == MVT::i1 &&
1738 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1740 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1741 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1744 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1745 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1746 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1747 if (TN->getVT() == MVT::i1) {
1749 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1750 DAG.getConstant(1, DL, VT));
1751 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1758 SDValue DAGCombiner::visitADDC(SDNode *N) {
1759 SDValue N0 = N->getOperand(0);
1760 SDValue N1 = N->getOperand(1);
1761 EVT VT = N0.getValueType();
1763 // If the flag result is dead, turn this into an ADD.
1764 if (!N->hasAnyUseOfValue(1))
1765 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1766 DAG.getNode(ISD::CARRY_FALSE,
1767 SDLoc(N), MVT::Glue));
1769 // canonicalize constant to RHS.
1770 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1771 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1773 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1775 // fold (addc x, 0) -> x + no carry out
1776 if (N1C && N1C->isNullValue())
1777 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1778 SDLoc(N), MVT::Glue));
1780 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1781 APInt LHSZero, LHSOne;
1782 APInt RHSZero, RHSOne;
1783 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1785 if (LHSZero.getBoolValue()) {
1786 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1788 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1789 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1790 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1791 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1792 DAG.getNode(ISD::CARRY_FALSE,
1793 SDLoc(N), MVT::Glue));
1799 SDValue DAGCombiner::visitADDE(SDNode *N) {
1800 SDValue N0 = N->getOperand(0);
1801 SDValue N1 = N->getOperand(1);
1802 SDValue CarryIn = N->getOperand(2);
1804 // canonicalize constant to RHS
1805 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1806 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1808 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1811 // fold (adde x, y, false) -> (addc x, y)
1812 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1813 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1818 // Since it may not be valid to emit a fold to zero for vector initializers
1819 // check if we can before folding.
1820 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1822 bool LegalOperations, bool LegalTypes) {
1824 return DAG.getConstant(0, DL, VT);
1825 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1826 return DAG.getConstant(0, DL, VT);
1830 SDValue DAGCombiner::visitSUB(SDNode *N) {
1831 SDValue N0 = N->getOperand(0);
1832 SDValue N1 = N->getOperand(1);
1833 EVT VT = N0.getValueType();
1836 if (VT.isVector()) {
1837 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1840 // fold (sub x, 0) -> x, vector edition
1841 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1845 // fold (sub x, x) -> 0
1846 // FIXME: Refactor this and xor and other similar operations together.
1848 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1849 // fold (sub c1, c2) -> c1-c2
1850 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1851 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1853 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1854 // fold (sub x, c) -> (add x, -c)
1857 return DAG.getNode(ISD::ADD, DL, VT, N0,
1858 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1860 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1861 if (N0C && N0C->isAllOnesValue())
1862 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1863 // fold A-(A-B) -> B
1864 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1865 return N1.getOperand(1);
1866 // fold (A+B)-A -> B
1867 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1868 return N0.getOperand(1);
1869 // fold (A+B)-B -> A
1870 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1871 return N0.getOperand(0);
1872 // fold C2-(A+C1) -> (C2-C1)-A
1873 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1874 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1875 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1877 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1879 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1882 // fold ((A+(B+or-C))-B) -> A+or-C
1883 if (N0.getOpcode() == ISD::ADD &&
1884 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1885 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1886 N0.getOperand(1).getOperand(0) == N1)
1887 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1888 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1889 // fold ((A+(C+B))-B) -> A+C
1890 if (N0.getOpcode() == ISD::ADD &&
1891 N0.getOperand(1).getOpcode() == ISD::ADD &&
1892 N0.getOperand(1).getOperand(1) == N1)
1893 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1894 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1895 // fold ((A-(B-C))-C) -> A-B
1896 if (N0.getOpcode() == ISD::SUB &&
1897 N0.getOperand(1).getOpcode() == ISD::SUB &&
1898 N0.getOperand(1).getOperand(1) == N1)
1899 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1900 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1902 // If either operand of a sub is undef, the result is undef
1903 if (N0.getOpcode() == ISD::UNDEF)
1905 if (N1.getOpcode() == ISD::UNDEF)
1908 // If the relocation model supports it, consider symbol offsets.
1909 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1910 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1911 // fold (sub Sym, c) -> Sym-c
1912 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1913 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1915 (uint64_t)N1C->getSExtValue());
1916 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1917 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1918 if (GA->getGlobal() == GB->getGlobal())
1919 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1923 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1924 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1925 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1926 if (TN->getVT() == MVT::i1) {
1928 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1929 DAG.getConstant(1, DL, VT));
1930 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1937 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1938 SDValue N0 = N->getOperand(0);
1939 SDValue N1 = N->getOperand(1);
1940 EVT VT = N0.getValueType();
1942 // If the flag result is dead, turn this into an SUB.
1943 if (!N->hasAnyUseOfValue(1))
1944 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1945 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1948 // fold (subc x, x) -> 0 + no borrow
1951 return CombineTo(N, DAG.getConstant(0, DL, VT),
1952 DAG.getNode(ISD::CARRY_FALSE, DL,
1956 // fold (subc x, 0) -> x + no borrow
1957 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1958 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1959 if (N1C && N1C->isNullValue())
1960 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1963 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1964 if (N0C && N0C->isAllOnesValue())
1965 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1966 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1972 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1973 SDValue N0 = N->getOperand(0);
1974 SDValue N1 = N->getOperand(1);
1975 SDValue CarryIn = N->getOperand(2);
1977 // fold (sube x, y, false) -> (subc x, y)
1978 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1979 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1984 SDValue DAGCombiner::visitMUL(SDNode *N) {
1985 SDValue N0 = N->getOperand(0);
1986 SDValue N1 = N->getOperand(1);
1987 EVT VT = N0.getValueType();
1989 // fold (mul x, undef) -> 0
1990 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1991 return DAG.getConstant(0, SDLoc(N), VT);
1993 bool N0IsConst = false;
1994 bool N1IsConst = false;
1995 APInt ConstValue0, ConstValue1;
1997 if (VT.isVector()) {
1998 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2001 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2002 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2004 N0IsConst = isa<ConstantSDNode>(N0);
2006 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2007 N1IsConst = isa<ConstantSDNode>(N1);
2009 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2012 // fold (mul c1, c2) -> c1*c2
2013 if (N0IsConst && N1IsConst)
2014 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2015 N0.getNode(), N1.getNode());
2017 // canonicalize constant to RHS (vector doesn't have to splat)
2018 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2019 !isConstantIntBuildVectorOrConstantInt(N1))
2020 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2021 // fold (mul x, 0) -> 0
2022 if (N1IsConst && ConstValue1 == 0)
2024 // We require a splat of the entire scalar bit width for non-contiguous
2027 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2028 // fold (mul x, 1) -> x
2029 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2031 // fold (mul x, -1) -> 0-x
2032 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2034 return DAG.getNode(ISD::SUB, DL, VT,
2035 DAG.getConstant(0, DL, VT), N0);
2037 // fold (mul x, (1 << c)) -> x << c
2038 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2040 return DAG.getNode(ISD::SHL, DL, VT, N0,
2041 DAG.getConstant(ConstValue1.logBase2(), DL,
2042 getShiftAmountTy(N0.getValueType())));
2044 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2045 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2046 unsigned Log2Val = (-ConstValue1).logBase2();
2048 // FIXME: If the input is something that is easily negated (e.g. a
2049 // single-use add), we should put the negate there.
2050 return DAG.getNode(ISD::SUB, DL, VT,
2051 DAG.getConstant(0, DL, VT),
2052 DAG.getNode(ISD::SHL, DL, VT, N0,
2053 DAG.getConstant(Log2Val, DL,
2054 getShiftAmountTy(N0.getValueType()))));
2058 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2059 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2060 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2061 isa<ConstantSDNode>(N0.getOperand(1)))) {
2062 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2063 N1, N0.getOperand(1));
2064 AddToWorklist(C3.getNode());
2065 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2066 N0.getOperand(0), C3);
2069 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2072 SDValue Sh(nullptr,0), Y(nullptr,0);
2073 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2074 if (N0.getOpcode() == ISD::SHL &&
2075 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2076 isa<ConstantSDNode>(N0.getOperand(1))) &&
2077 N0.getNode()->hasOneUse()) {
2079 } else if (N1.getOpcode() == ISD::SHL &&
2080 isa<ConstantSDNode>(N1.getOperand(1)) &&
2081 N1.getNode()->hasOneUse()) {
2086 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2087 Sh.getOperand(0), Y);
2088 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2089 Mul, Sh.getOperand(1));
2093 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2094 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2095 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2096 isa<ConstantSDNode>(N0.getOperand(1))))
2097 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2098 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2099 N0.getOperand(0), N1),
2100 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2101 N0.getOperand(1), N1));
2104 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2110 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2111 SDValue N0 = N->getOperand(0);
2112 SDValue N1 = N->getOperand(1);
2113 EVT VT = N->getValueType(0);
2117 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2120 // fold (sdiv c1, c2) -> c1/c2
2121 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2122 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2123 if (N0C && N1C && !N1C->isNullValue())
2124 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2125 // fold (sdiv X, 1) -> X
2126 if (N1C && N1C->getAPIntValue() == 1LL)
2128 // fold (sdiv X, -1) -> 0-X
2129 if (N1C && N1C->isAllOnesValue()) {
2131 return DAG.getNode(ISD::SUB, DL, VT,
2132 DAG.getConstant(0, DL, VT), N0);
2134 // If we know the sign bits of both operands are zero, strength reduce to a
2135 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2136 if (!VT.isVector()) {
2137 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2138 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2142 // fold (sdiv X, pow2) -> simple ops after legalize
2143 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2144 (-N1C->getAPIntValue()).isPowerOf2())) {
2145 // If dividing by powers of two is cheap, then don't perform the following
2147 if (TLI.isPow2SDivCheap())
2150 // Target-specific implementation of sdiv x, pow2.
2151 SDValue Res = BuildSDIVPow2(N);
2155 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2158 // Splat the sign bit into the register
2160 DAG.getNode(ISD::SRA, DL, VT, N0,
2161 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2162 getShiftAmountTy(N0.getValueType())));
2163 AddToWorklist(SGN.getNode());
2165 // Add (N0 < 0) ? abs2 - 1 : 0;
2167 DAG.getNode(ISD::SRL, DL, VT, SGN,
2168 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2169 getShiftAmountTy(SGN.getValueType())));
2170 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2171 AddToWorklist(SRL.getNode());
2172 AddToWorklist(ADD.getNode()); // Divide by pow2
2173 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2174 DAG.getConstant(lg2, DL,
2175 getShiftAmountTy(ADD.getValueType())));
2177 // If we're dividing by a positive value, we're done. Otherwise, we must
2178 // negate the result.
2179 if (N1C->getAPIntValue().isNonNegative())
2182 AddToWorklist(SRA.getNode());
2183 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2186 // If integer divide is expensive and we satisfy the requirements, emit an
2187 // alternate sequence.
2188 if (N1C && !TLI.isIntDivCheap()) {
2189 SDValue Op = BuildSDIV(N);
2190 if (Op.getNode()) return Op;
2194 if (N0.getOpcode() == ISD::UNDEF)
2195 return DAG.getConstant(0, SDLoc(N), VT);
2196 // X / undef -> undef
2197 if (N1.getOpcode() == ISD::UNDEF)
2203 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2204 SDValue N0 = N->getOperand(0);
2205 SDValue N1 = N->getOperand(1);
2206 EVT VT = N->getValueType(0);
2210 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2213 // fold (udiv c1, c2) -> c1/c2
2214 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2215 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2216 if (N0C && N1C && !N1C->isNullValue())
2217 return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2218 // fold (udiv x, (1 << c)) -> x >>u c
2219 if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2221 return DAG.getNode(ISD::SRL, DL, VT, N0,
2222 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2223 getShiftAmountTy(N0.getValueType())));
2225 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2226 if (N1.getOpcode() == ISD::SHL) {
2227 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2228 if (SHC->getAPIntValue().isPowerOf2()) {
2229 EVT ADDVT = N1.getOperand(1).getValueType();
2231 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2233 DAG.getConstant(SHC->getAPIntValue()
2236 AddToWorklist(Add.getNode());
2237 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2241 // fold (udiv x, c) -> alternate
2242 if (N1C && !TLI.isIntDivCheap()) {
2243 SDValue Op = BuildUDIV(N);
2244 if (Op.getNode()) return Op;
2248 if (N0.getOpcode() == ISD::UNDEF)
2249 return DAG.getConstant(0, SDLoc(N), VT);
2250 // X / undef -> undef
2251 if (N1.getOpcode() == ISD::UNDEF)
2257 SDValue DAGCombiner::visitSREM(SDNode *N) {
2258 SDValue N0 = N->getOperand(0);
2259 SDValue N1 = N->getOperand(1);
2260 EVT VT = N->getValueType(0);
2262 // fold (srem c1, c2) -> c1%c2
2263 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2264 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2265 if (N0C && N1C && !N1C->isNullValue())
2266 return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2267 // If we know the sign bits of both operands are zero, strength reduce to a
2268 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2269 if (!VT.isVector()) {
2270 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2271 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2274 // If X/C can be simplified by the division-by-constant logic, lower
2275 // X%C to the equivalent of X-X/C*C.
2276 if (N1C && !N1C->isNullValue()) {
2277 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2278 AddToWorklist(Div.getNode());
2279 SDValue OptimizedDiv = combine(Div.getNode());
2280 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2281 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2283 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2284 AddToWorklist(Mul.getNode());
2290 if (N0.getOpcode() == ISD::UNDEF)
2291 return DAG.getConstant(0, SDLoc(N), VT);
2292 // X % undef -> undef
2293 if (N1.getOpcode() == ISD::UNDEF)
2299 SDValue DAGCombiner::visitUREM(SDNode *N) {
2300 SDValue N0 = N->getOperand(0);
2301 SDValue N1 = N->getOperand(1);
2302 EVT VT = N->getValueType(0);
2304 // fold (urem c1, c2) -> c1%c2
2305 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2306 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2307 if (N0C && N1C && !N1C->isNullValue())
2308 return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2309 // fold (urem x, pow2) -> (and x, pow2-1)
2310 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2312 return DAG.getNode(ISD::AND, DL, VT, N0,
2313 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2315 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2316 if (N1.getOpcode() == ISD::SHL) {
2317 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2318 if (SHC->getAPIntValue().isPowerOf2()) {
2321 DAG.getNode(ISD::ADD, DL, VT, N1,
2322 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2324 AddToWorklist(Add.getNode());
2325 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2330 // If X/C can be simplified by the division-by-constant logic, lower
2331 // X%C to the equivalent of X-X/C*C.
2332 if (N1C && !N1C->isNullValue()) {
2333 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2334 AddToWorklist(Div.getNode());
2335 SDValue OptimizedDiv = combine(Div.getNode());
2336 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2337 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2339 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2340 AddToWorklist(Mul.getNode());
2346 if (N0.getOpcode() == ISD::UNDEF)
2347 return DAG.getConstant(0, SDLoc(N), VT);
2348 // X % undef -> undef
2349 if (N1.getOpcode() == ISD::UNDEF)
2355 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2356 SDValue N0 = N->getOperand(0);
2357 SDValue N1 = N->getOperand(1);
2358 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2359 EVT VT = N->getValueType(0);
2362 // fold (mulhs x, 0) -> 0
2363 if (N1C && N1C->isNullValue())
2365 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2366 if (N1C && N1C->getAPIntValue() == 1) {
2368 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2369 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2371 getShiftAmountTy(N0.getValueType())));
2373 // fold (mulhs x, undef) -> 0
2374 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2375 return DAG.getConstant(0, SDLoc(N), VT);
2377 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2379 if (VT.isSimple() && !VT.isVector()) {
2380 MVT Simple = VT.getSimpleVT();
2381 unsigned SimpleSize = Simple.getSizeInBits();
2382 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2383 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2384 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2385 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2386 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2387 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2388 DAG.getConstant(SimpleSize, DL,
2389 getShiftAmountTy(N1.getValueType())));
2390 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2397 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2398 SDValue N0 = N->getOperand(0);
2399 SDValue N1 = N->getOperand(1);
2400 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2401 EVT VT = N->getValueType(0);
2404 // fold (mulhu x, 0) -> 0
2405 if (N1C && N1C->isNullValue())
2407 // fold (mulhu x, 1) -> 0
2408 if (N1C && N1C->getAPIntValue() == 1)
2409 return DAG.getConstant(0, DL, N0.getValueType());
2410 // fold (mulhu x, undef) -> 0
2411 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2412 return DAG.getConstant(0, DL, VT);
2414 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2416 if (VT.isSimple() && !VT.isVector()) {
2417 MVT Simple = VT.getSimpleVT();
2418 unsigned SimpleSize = Simple.getSizeInBits();
2419 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2420 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2421 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2422 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2423 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2424 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2425 DAG.getConstant(SimpleSize, DL,
2426 getShiftAmountTy(N1.getValueType())));
2427 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2434 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2435 /// give the opcodes for the two computations that are being performed. Return
2436 /// true if a simplification was made.
2437 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2439 // If the high half is not needed, just compute the low half.
2440 bool HiExists = N->hasAnyUseOfValue(1);
2442 (!LegalOperations ||
2443 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2444 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2445 return CombineTo(N, Res, Res);
2448 // If the low half is not needed, just compute the high half.
2449 bool LoExists = N->hasAnyUseOfValue(0);
2451 (!LegalOperations ||
2452 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2453 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2454 return CombineTo(N, Res, Res);
2457 // If both halves are used, return as it is.
2458 if (LoExists && HiExists)
2461 // If the two computed results can be simplified separately, separate them.
2463 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2464 AddToWorklist(Lo.getNode());
2465 SDValue LoOpt = combine(Lo.getNode());
2466 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2467 (!LegalOperations ||
2468 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2469 return CombineTo(N, LoOpt, LoOpt);
2473 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2474 AddToWorklist(Hi.getNode());
2475 SDValue HiOpt = combine(Hi.getNode());
2476 if (HiOpt.getNode() && HiOpt != Hi &&
2477 (!LegalOperations ||
2478 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2479 return CombineTo(N, HiOpt, HiOpt);
2485 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2486 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2487 if (Res.getNode()) return Res;
2489 EVT VT = N->getValueType(0);
2492 // If the type is twice as wide is legal, transform the mulhu to a wider
2493 // multiply plus a shift.
2494 if (VT.isSimple() && !VT.isVector()) {
2495 MVT Simple = VT.getSimpleVT();
2496 unsigned SimpleSize = Simple.getSizeInBits();
2497 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2498 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2499 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2500 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2501 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2502 // Compute the high part as N1.
2503 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2504 DAG.getConstant(SimpleSize, DL,
2505 getShiftAmountTy(Lo.getValueType())));
2506 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2507 // Compute the low part as N0.
2508 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2509 return CombineTo(N, Lo, Hi);
2516 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2517 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2518 if (Res.getNode()) return Res;
2520 EVT VT = N->getValueType(0);
2523 // If the type is twice as wide is legal, transform the mulhu to a wider
2524 // multiply plus a shift.
2525 if (VT.isSimple() && !VT.isVector()) {
2526 MVT Simple = VT.getSimpleVT();
2527 unsigned SimpleSize = Simple.getSizeInBits();
2528 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2529 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2530 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2531 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2532 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2533 // Compute the high part as N1.
2534 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2535 DAG.getConstant(SimpleSize, DL,
2536 getShiftAmountTy(Lo.getValueType())));
2537 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2538 // Compute the low part as N0.
2539 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2540 return CombineTo(N, Lo, Hi);
2547 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2548 // (smulo x, 2) -> (saddo x, x)
2549 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2550 if (C2->getAPIntValue() == 2)
2551 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2552 N->getOperand(0), N->getOperand(0));
2557 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2558 // (umulo x, 2) -> (uaddo x, x)
2559 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2560 if (C2->getAPIntValue() == 2)
2561 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2562 N->getOperand(0), N->getOperand(0));
2567 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2568 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2569 if (Res.getNode()) return Res;
2574 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2575 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2576 if (Res.getNode()) return Res;
2581 /// If this is a binary operator with two operands of the same opcode, try to
2583 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2584 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2585 EVT VT = N0.getValueType();
2586 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2588 // Bail early if none of these transforms apply.
2589 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2591 // For each of OP in AND/OR/XOR:
2592 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2593 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2594 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2595 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2596 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2598 // do not sink logical op inside of a vector extend, since it may combine
2600 EVT Op0VT = N0.getOperand(0).getValueType();
2601 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2602 N0.getOpcode() == ISD::SIGN_EXTEND ||
2603 N0.getOpcode() == ISD::BSWAP ||
2604 // Avoid infinite looping with PromoteIntBinOp.
2605 (N0.getOpcode() == ISD::ANY_EXTEND &&
2606 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2607 (N0.getOpcode() == ISD::TRUNCATE &&
2608 (!TLI.isZExtFree(VT, Op0VT) ||
2609 !TLI.isTruncateFree(Op0VT, VT)) &&
2610 TLI.isTypeLegal(Op0VT))) &&
2612 Op0VT == N1.getOperand(0).getValueType() &&
2613 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2614 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2615 N0.getOperand(0).getValueType(),
2616 N0.getOperand(0), N1.getOperand(0));
2617 AddToWorklist(ORNode.getNode());
2618 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2621 // For each of OP in SHL/SRL/SRA/AND...
2622 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2623 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2624 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2625 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2626 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2627 N0.getOperand(1) == N1.getOperand(1)) {
2628 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2629 N0.getOperand(0).getValueType(),
2630 N0.getOperand(0), N1.getOperand(0));
2631 AddToWorklist(ORNode.getNode());
2632 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2633 ORNode, N0.getOperand(1));
2636 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2637 // Only perform this optimization after type legalization and before
2638 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2639 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2640 // we don't want to undo this promotion.
2641 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2643 if ((N0.getOpcode() == ISD::BITCAST ||
2644 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2645 Level == AfterLegalizeTypes) {
2646 SDValue In0 = N0.getOperand(0);
2647 SDValue In1 = N1.getOperand(0);
2648 EVT In0Ty = In0.getValueType();
2649 EVT In1Ty = In1.getValueType();
2651 // If both incoming values are integers, and the original types are the
2653 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2654 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2655 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2656 AddToWorklist(Op.getNode());
2661 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2662 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2663 // If both shuffles use the same mask, and both shuffle within a single
2664 // vector, then it is worthwhile to move the swizzle after the operation.
2665 // The type-legalizer generates this pattern when loading illegal
2666 // vector types from memory. In many cases this allows additional shuffle
2668 // There are other cases where moving the shuffle after the xor/and/or
2669 // is profitable even if shuffles don't perform a swizzle.
2670 // If both shuffles use the same mask, and both shuffles have the same first
2671 // or second operand, then it might still be profitable to move the shuffle
2672 // after the xor/and/or operation.
2673 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2674 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2675 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2677 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2678 "Inputs to shuffles are not the same type");
2680 // Check that both shuffles use the same mask. The masks are known to be of
2681 // the same length because the result vector type is the same.
2682 // Check also that shuffles have only one use to avoid introducing extra
2684 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2685 SVN0->getMask().equals(SVN1->getMask())) {
2686 SDValue ShOp = N0->getOperand(1);
2688 // Don't try to fold this node if it requires introducing a
2689 // build vector of all zeros that might be illegal at this stage.
2690 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2692 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2697 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2698 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2699 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2700 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2701 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2702 N0->getOperand(0), N1->getOperand(0));
2703 AddToWorklist(NewNode.getNode());
2704 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2705 &SVN0->getMask()[0]);
2708 // Don't try to fold this node if it requires introducing a
2709 // build vector of all zeros that might be illegal at this stage.
2710 ShOp = N0->getOperand(0);
2711 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2713 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2718 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2719 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2720 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2721 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2722 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2723 N0->getOperand(1), N1->getOperand(1));
2724 AddToWorklist(NewNode.getNode());
2725 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2726 &SVN0->getMask()[0]);
2734 /// This contains all DAGCombine rules which reduce two values combined by
2735 /// an And operation to a single value. This makes them reusable in the context
2736 /// of visitSELECT(). Rules involving constants are not included as
2737 /// visitSELECT() already handles those cases.
2738 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2739 SDNode *LocReference) {
2740 EVT VT = N1.getValueType();
2742 // fold (and x, undef) -> 0
2743 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2744 return DAG.getConstant(0, SDLoc(LocReference), VT);
2745 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2746 SDValue LL, LR, RL, RR, CC0, CC1;
2747 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2748 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2749 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2751 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2752 LL.getValueType().isInteger()) {
2753 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2754 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2755 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2756 LR.getValueType(), LL, RL);
2757 AddToWorklist(ORNode.getNode());
2758 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2760 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2761 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2762 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2763 LR.getValueType(), LL, RL);
2764 AddToWorklist(ANDNode.getNode());
2765 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2767 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2768 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2769 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2770 LR.getValueType(), LL, RL);
2771 AddToWorklist(ORNode.getNode());
2772 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2775 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2776 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2777 Op0 == Op1 && LL.getValueType().isInteger() &&
2778 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2779 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2780 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2781 cast<ConstantSDNode>(RR)->isNullValue()))) {
2783 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2784 LL, DAG.getConstant(1, DL,
2785 LL.getValueType()));
2786 AddToWorklist(ADDNode.getNode());
2787 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2788 DAG.getConstant(2, DL, LL.getValueType()),
2791 // canonicalize equivalent to ll == rl
2792 if (LL == RR && LR == RL) {
2793 Op1 = ISD::getSetCCSwappedOperands(Op1);
2796 if (LL == RL && LR == RR) {
2797 bool isInteger = LL.getValueType().isInteger();
2798 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2799 if (Result != ISD::SETCC_INVALID &&
2800 (!LegalOperations ||
2801 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2802 TLI.isOperationLegal(ISD::SETCC,
2803 getSetCCResultType(N0.getSimpleValueType())))))
2804 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2809 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2810 VT.getSizeInBits() <= 64) {
2811 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2812 APInt ADDC = ADDI->getAPIntValue();
2813 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2814 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2815 // immediate for an add, but it is legal if its top c2 bits are set,
2816 // transform the ADD so the immediate doesn't need to be materialized
2818 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2819 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2820 SRLI->getZExtValue());
2821 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2823 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2826 DAG.getNode(ISD::ADD, DL, VT,
2827 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2828 CombineTo(N0.getNode(), NewAdd);
2829 // Return N so it doesn't get rechecked!
2830 return SDValue(LocReference, 0);
2841 SDValue DAGCombiner::visitAND(SDNode *N) {
2842 SDValue N0 = N->getOperand(0);
2843 SDValue N1 = N->getOperand(1);
2844 EVT VT = N1.getValueType();
2847 if (VT.isVector()) {
2848 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2851 // fold (and x, 0) -> 0, vector edition
2852 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2853 // do not return N0, because undef node may exist in N0
2854 return DAG.getConstant(
2855 APInt::getNullValue(
2856 N0.getValueType().getScalarType().getSizeInBits()),
2857 SDLoc(N), N0.getValueType());
2858 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2859 // do not return N1, because undef node may exist in N1
2860 return DAG.getConstant(
2861 APInt::getNullValue(
2862 N1.getValueType().getScalarType().getSizeInBits()),
2863 SDLoc(N), N1.getValueType());
2865 // fold (and x, -1) -> x, vector edition
2866 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2868 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2872 // fold (and c1, c2) -> c1&c2
2873 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2874 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2876 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2877 // canonicalize constant to RHS
2878 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2879 !isConstantIntBuildVectorOrConstantInt(N1))
2880 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2881 // fold (and x, -1) -> x
2882 if (N1C && N1C->isAllOnesValue())
2884 // if (and x, c) is known to be zero, return 0
2885 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2886 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2887 APInt::getAllOnesValue(BitWidth)))
2888 return DAG.getConstant(0, SDLoc(N), VT);
2890 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2892 // fold (and (or x, C), D) -> D if (C & D) == D
2893 if (N1C && N0.getOpcode() == ISD::OR)
2894 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2895 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2897 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2898 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2899 SDValue N0Op0 = N0.getOperand(0);
2900 APInt Mask = ~N1C->getAPIntValue();
2901 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2902 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2903 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2904 N0.getValueType(), N0Op0);
2906 // Replace uses of the AND with uses of the Zero extend node.
2909 // We actually want to replace all uses of the any_extend with the
2910 // zero_extend, to avoid duplicating things. This will later cause this
2911 // AND to be folded.
2912 CombineTo(N0.getNode(), Zext);
2913 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2916 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2917 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2918 // already be zero by virtue of the width of the base type of the load.
2920 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2922 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2923 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2924 N0.getOpcode() == ISD::LOAD) {
2925 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2926 N0 : N0.getOperand(0) );
2928 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2929 // This can be a pure constant or a vector splat, in which case we treat the
2930 // vector as a scalar and use the splat value.
2931 APInt Constant = APInt::getNullValue(1);
2932 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2933 Constant = C->getAPIntValue();
2934 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2935 APInt SplatValue, SplatUndef;
2936 unsigned SplatBitSize;
2938 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2939 SplatBitSize, HasAnyUndefs);
2941 // Undef bits can contribute to a possible optimisation if set, so
2943 SplatValue |= SplatUndef;
2945 // The splat value may be something like "0x00FFFFFF", which means 0 for
2946 // the first vector value and FF for the rest, repeating. We need a mask
2947 // that will apply equally to all members of the vector, so AND all the
2948 // lanes of the constant together.
2949 EVT VT = Vector->getValueType(0);
2950 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2952 // If the splat value has been compressed to a bitlength lower
2953 // than the size of the vector lane, we need to re-expand it to
2955 if (BitWidth > SplatBitSize)
2956 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2957 SplatBitSize < BitWidth;
2958 SplatBitSize = SplatBitSize * 2)
2959 SplatValue |= SplatValue.shl(SplatBitSize);
2961 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2962 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2963 if (SplatBitSize % BitWidth == 0) {
2964 Constant = APInt::getAllOnesValue(BitWidth);
2965 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2966 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2971 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2972 // actually legal and isn't going to get expanded, else this is a false
2974 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2975 Load->getValueType(0),
2976 Load->getMemoryVT());
2978 // Resize the constant to the same size as the original memory access before
2979 // extension. If it is still the AllOnesValue then this AND is completely
2982 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2985 switch (Load->getExtensionType()) {
2986 default: B = false; break;
2987 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2989 case ISD::NON_EXTLOAD: B = true; break;
2992 if (B && Constant.isAllOnesValue()) {
2993 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2994 // preserve semantics once we get rid of the AND.
2995 SDValue NewLoad(Load, 0);
2996 if (Load->getExtensionType() == ISD::EXTLOAD) {
2997 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2998 Load->getValueType(0), SDLoc(Load),
2999 Load->getChain(), Load->getBasePtr(),
3000 Load->getOffset(), Load->getMemoryVT(),
3001 Load->getMemOperand());
3002 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3003 if (Load->getNumValues() == 3) {
3004 // PRE/POST_INC loads have 3 values.
3005 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3006 NewLoad.getValue(2) };
3007 CombineTo(Load, To, 3, true);
3009 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3013 // Fold the AND away, taking care not to fold to the old load node if we
3015 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3017 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3021 // fold (and (load x), 255) -> (zextload x, i8)
3022 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3023 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3024 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3025 (N0.getOpcode() == ISD::ANY_EXTEND &&
3026 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3027 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3028 LoadSDNode *LN0 = HasAnyExt
3029 ? cast<LoadSDNode>(N0.getOperand(0))
3030 : cast<LoadSDNode>(N0);
3031 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3032 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3033 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3034 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3035 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3036 EVT LoadedVT = LN0->getMemoryVT();
3037 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3039 if (ExtVT == LoadedVT &&
3040 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3044 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3045 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3046 LN0->getMemOperand());
3048 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3049 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3052 // Do not change the width of a volatile load.
3053 // Do not generate loads of non-round integer types since these can
3054 // be expensive (and would be wrong if the type is not byte sized).
3055 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3056 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3058 EVT PtrType = LN0->getOperand(1).getValueType();
3060 unsigned Alignment = LN0->getAlignment();
3061 SDValue NewPtr = LN0->getBasePtr();
3063 // For big endian targets, we need to add an offset to the pointer
3064 // to load the correct bytes. For little endian systems, we merely
3065 // need to read fewer bytes from the same pointer.
3066 if (TLI.isBigEndian()) {
3067 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3068 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3069 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3071 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3072 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3073 Alignment = MinAlign(Alignment, PtrOff);
3076 AddToWorklist(NewPtr.getNode());
3079 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3080 LN0->getChain(), NewPtr,
3081 LN0->getPointerInfo(),
3082 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3083 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3085 CombineTo(LN0, Load, Load.getValue(1));
3086 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3092 if (SDValue Combined = visitANDLike(N0, N1, N))
3095 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3096 if (N0.getOpcode() == N1.getOpcode()) {
3097 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3098 if (Tmp.getNode()) return Tmp;
3101 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3102 // fold (and (sra)) -> (and (srl)) when possible.
3103 if (!VT.isVector() &&
3104 SimplifyDemandedBits(SDValue(N, 0)))
3105 return SDValue(N, 0);
3107 // fold (zext_inreg (extload x)) -> (zextload x)
3108 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3109 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3110 EVT MemVT = LN0->getMemoryVT();
3111 // If we zero all the possible extended bits, then we can turn this into
3112 // a zextload if we are running before legalize or the operation is legal.
3113 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3114 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3115 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3116 ((!LegalOperations && !LN0->isVolatile()) ||
3117 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3118 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3119 LN0->getChain(), LN0->getBasePtr(),
3120 MemVT, LN0->getMemOperand());
3122 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3123 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3126 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3127 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3129 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3130 EVT MemVT = LN0->getMemoryVT();
3131 // If we zero all the possible extended bits, then we can turn this into
3132 // a zextload if we are running before legalize or the operation is legal.
3133 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3134 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3135 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3136 ((!LegalOperations && !LN0->isVolatile()) ||
3137 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3138 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3139 LN0->getChain(), LN0->getBasePtr(),
3140 MemVT, LN0->getMemOperand());
3142 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3143 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3146 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3147 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3148 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3149 N0.getOperand(1), false);
3150 if (BSwap.getNode())
3157 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3158 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3159 bool DemandHighBits) {
3160 if (!LegalOperations)
3163 EVT VT = N->getValueType(0);
3164 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3166 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3169 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3170 bool LookPassAnd0 = false;
3171 bool LookPassAnd1 = false;
3172 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3174 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3176 if (N0.getOpcode() == ISD::AND) {
3177 if (!N0.getNode()->hasOneUse())
3179 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3180 if (!N01C || N01C->getZExtValue() != 0xFF00)
3182 N0 = N0.getOperand(0);
3183 LookPassAnd0 = true;
3186 if (N1.getOpcode() == ISD::AND) {
3187 if (!N1.getNode()->hasOneUse())
3189 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3190 if (!N11C || N11C->getZExtValue() != 0xFF)
3192 N1 = N1.getOperand(0);
3193 LookPassAnd1 = true;
3196 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3198 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3200 if (!N0.getNode()->hasOneUse() ||
3201 !N1.getNode()->hasOneUse())
3204 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3208 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3211 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3212 SDValue N00 = N0->getOperand(0);
3213 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3214 if (!N00.getNode()->hasOneUse())
3216 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3217 if (!N001C || N001C->getZExtValue() != 0xFF)
3219 N00 = N00.getOperand(0);
3220 LookPassAnd0 = true;
3223 SDValue N10 = N1->getOperand(0);
3224 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3225 if (!N10.getNode()->hasOneUse())
3227 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3228 if (!N101C || N101C->getZExtValue() != 0xFF00)
3230 N10 = N10.getOperand(0);
3231 LookPassAnd1 = true;
3237 // Make sure everything beyond the low halfword gets set to zero since the SRL
3238 // 16 will clear the top bits.
3239 unsigned OpSizeInBits = VT.getSizeInBits();
3240 if (DemandHighBits && OpSizeInBits > 16) {
3241 // If the left-shift isn't masked out then the only way this is a bswap is
3242 // if all bits beyond the low 8 are 0. In that case the entire pattern
3243 // reduces to a left shift anyway: leave it for other parts of the combiner.
3247 // However, if the right shift isn't masked out then it might be because
3248 // it's not needed. See if we can spot that too.
3249 if (!LookPassAnd1 &&
3250 !DAG.MaskedValueIsZero(
3251 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3255 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3256 if (OpSizeInBits > 16) {
3258 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3259 DAG.getConstant(OpSizeInBits - 16, DL,
3260 getShiftAmountTy(VT)));
3265 /// Return true if the specified node is an element that makes up a 32-bit
3266 /// packed halfword byteswap.
3267 /// ((x & 0x000000ff) << 8) |
3268 /// ((x & 0x0000ff00) >> 8) |
3269 /// ((x & 0x00ff0000) << 8) |
3270 /// ((x & 0xff000000) >> 8)
3271 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3272 if (!N.getNode()->hasOneUse())
3275 unsigned Opc = N.getOpcode();
3276 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3279 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3284 switch (N1C->getZExtValue()) {
3287 case 0xFF: Num = 0; break;
3288 case 0xFF00: Num = 1; break;
3289 case 0xFF0000: Num = 2; break;
3290 case 0xFF000000: Num = 3; break;
3293 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3294 SDValue N0 = N.getOperand(0);
3295 if (Opc == ISD::AND) {
3296 if (Num == 0 || Num == 2) {
3298 // (x >> 8) & 0xff0000
3299 if (N0.getOpcode() != ISD::SRL)
3301 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3302 if (!C || C->getZExtValue() != 8)
3305 // (x << 8) & 0xff00
3306 // (x << 8) & 0xff000000
3307 if (N0.getOpcode() != ISD::SHL)
3309 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3310 if (!C || C->getZExtValue() != 8)
3313 } else if (Opc == ISD::SHL) {
3315 // (x & 0xff0000) << 8
3316 if (Num != 0 && Num != 2)
3318 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3319 if (!C || C->getZExtValue() != 8)
3321 } else { // Opc == ISD::SRL
3322 // (x & 0xff00) >> 8
3323 // (x & 0xff000000) >> 8
3324 if (Num != 1 && Num != 3)
3326 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3327 if (!C || C->getZExtValue() != 8)
3334 Parts[Num] = N0.getOperand(0).getNode();
3338 /// Match a 32-bit packed halfword bswap. That is
3339 /// ((x & 0x000000ff) << 8) |
3340 /// ((x & 0x0000ff00) >> 8) |
3341 /// ((x & 0x00ff0000) << 8) |
3342 /// ((x & 0xff000000) >> 8)
3343 /// => (rotl (bswap x), 16)
3344 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3345 if (!LegalOperations)
3348 EVT VT = N->getValueType(0);
3351 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3355 // (or (or (and), (and)), (or (and), (and)))
3356 // (or (or (or (and), (and)), (and)), (and))
3357 if (N0.getOpcode() != ISD::OR)
3359 SDValue N00 = N0.getOperand(0);
3360 SDValue N01 = N0.getOperand(1);
3361 SDNode *Parts[4] = {};
3363 if (N1.getOpcode() == ISD::OR &&
3364 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3365 // (or (or (and), (and)), (or (and), (and)))
3366 SDValue N000 = N00.getOperand(0);
3367 if (!isBSwapHWordElement(N000, Parts))
3370 SDValue N001 = N00.getOperand(1);
3371 if (!isBSwapHWordElement(N001, Parts))
3373 SDValue N010 = N01.getOperand(0);
3374 if (!isBSwapHWordElement(N010, Parts))
3376 SDValue N011 = N01.getOperand(1);
3377 if (!isBSwapHWordElement(N011, Parts))
3380 // (or (or (or (and), (and)), (and)), (and))
3381 if (!isBSwapHWordElement(N1, Parts))
3383 if (!isBSwapHWordElement(N01, Parts))
3385 if (N00.getOpcode() != ISD::OR)
3387 SDValue N000 = N00.getOperand(0);
3388 if (!isBSwapHWordElement(N000, Parts))
3390 SDValue N001 = N00.getOperand(1);
3391 if (!isBSwapHWordElement(N001, Parts))
3395 // Make sure the parts are all coming from the same node.
3396 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3400 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3401 SDValue(Parts[0], 0));
3403 // Result of the bswap should be rotated by 16. If it's not legal, then
3404 // do (x << 16) | (x >> 16).
3405 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3406 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3407 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3408 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3409 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3410 return DAG.getNode(ISD::OR, DL, VT,
3411 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3412 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3415 /// This contains all DAGCombine rules which reduce two values combined by
3416 /// an Or operation to a single value \see visitANDLike().
3417 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3418 EVT VT = N1.getValueType();
3419 // fold (or x, undef) -> -1
3420 if (!LegalOperations &&
3421 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3422 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3423 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3424 SDLoc(LocReference), VT);
3426 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3427 SDValue LL, LR, RL, RR, CC0, CC1;
3428 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3429 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3430 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3432 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3433 LL.getValueType().isInteger()) {
3434 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3435 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3436 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3437 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3438 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3439 LR.getValueType(), LL, RL);
3440 AddToWorklist(ORNode.getNode());
3441 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3443 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3444 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3445 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3446 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3447 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3448 LR.getValueType(), LL, RL);
3449 AddToWorklist(ANDNode.getNode());
3450 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3453 // canonicalize equivalent to ll == rl
3454 if (LL == RR && LR == RL) {
3455 Op1 = ISD::getSetCCSwappedOperands(Op1);
3458 if (LL == RL && LR == RR) {
3459 bool isInteger = LL.getValueType().isInteger();
3460 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3461 if (Result != ISD::SETCC_INVALID &&
3462 (!LegalOperations ||
3463 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3464 TLI.isOperationLegal(ISD::SETCC,
3465 getSetCCResultType(N0.getValueType())))))
3466 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3471 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3472 if (N0.getOpcode() == ISD::AND &&
3473 N1.getOpcode() == ISD::AND &&
3474 N0.getOperand(1).getOpcode() == ISD::Constant &&
3475 N1.getOperand(1).getOpcode() == ISD::Constant &&
3476 // Don't increase # computations.
3477 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3478 // We can only do this xform if we know that bits from X that are set in C2
3479 // but not in C1 are already zero. Likewise for Y.
3480 const APInt &LHSMask =
3481 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3482 const APInt &RHSMask =
3483 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3485 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3486 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3487 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3488 N0.getOperand(0), N1.getOperand(0));
3489 SDLoc DL(LocReference);
3490 return DAG.getNode(ISD::AND, DL, VT, X,
3491 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3495 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3496 if (N0.getOpcode() == ISD::AND &&
3497 N1.getOpcode() == ISD::AND &&
3498 N0.getOperand(0) == N1.getOperand(0) &&
3499 // Don't increase # computations.
3500 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3501 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3502 N0.getOperand(1), N1.getOperand(1));
3503 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3509 SDValue DAGCombiner::visitOR(SDNode *N) {
3510 SDValue N0 = N->getOperand(0);
3511 SDValue N1 = N->getOperand(1);
3512 EVT VT = N1.getValueType();
3515 if (VT.isVector()) {
3516 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3519 // fold (or x, 0) -> x, vector edition
3520 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3522 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3525 // fold (or x, -1) -> -1, vector edition
3526 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3527 // do not return N0, because undef node may exist in N0
3528 return DAG.getConstant(
3529 APInt::getAllOnesValue(
3530 N0.getValueType().getScalarType().getSizeInBits()),
3531 SDLoc(N), N0.getValueType());
3532 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3533 // do not return N1, because undef node may exist in N1
3534 return DAG.getConstant(
3535 APInt::getAllOnesValue(
3536 N1.getValueType().getScalarType().getSizeInBits()),
3537 SDLoc(N), N1.getValueType());
3539 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3540 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3541 // Do this only if the resulting shuffle is legal.
3542 if (isa<ShuffleVectorSDNode>(N0) &&
3543 isa<ShuffleVectorSDNode>(N1) &&
3544 // Avoid folding a node with illegal type.
3545 TLI.isTypeLegal(VT) &&
3546 N0->getOperand(1) == N1->getOperand(1) &&
3547 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3548 bool CanFold = true;
3549 unsigned NumElts = VT.getVectorNumElements();
3550 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3551 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3552 // We construct two shuffle masks:
3553 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3554 // and N1 as the second operand.
3555 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3556 // and N0 as the second operand.
3557 // We do this because OR is commutable and therefore there might be
3558 // two ways to fold this node into a shuffle.
3559 SmallVector<int,4> Mask1;
3560 SmallVector<int,4> Mask2;
3562 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3563 int M0 = SV0->getMaskElt(i);
3564 int M1 = SV1->getMaskElt(i);
3566 // Both shuffle indexes are undef. Propagate Undef.
3567 if (M0 < 0 && M1 < 0) {
3568 Mask1.push_back(M0);
3569 Mask2.push_back(M0);
3573 if (M0 < 0 || M1 < 0 ||
3574 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3575 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3580 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3581 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3585 // Fold this sequence only if the resulting shuffle is 'legal'.
3586 if (TLI.isShuffleMaskLegal(Mask1, VT))
3587 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3588 N1->getOperand(0), &Mask1[0]);
3589 if (TLI.isShuffleMaskLegal(Mask2, VT))
3590 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3591 N0->getOperand(0), &Mask2[0]);
3596 // fold (or c1, c2) -> c1|c2
3597 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3598 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3600 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3601 // canonicalize constant to RHS
3602 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3603 !isConstantIntBuildVectorOrConstantInt(N1))
3604 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3605 // fold (or x, 0) -> x
3606 if (N1C && N1C->isNullValue())
3608 // fold (or x, -1) -> -1
3609 if (N1C && N1C->isAllOnesValue())
3611 // fold (or x, c) -> c iff (x & ~c) == 0
3612 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3615 if (SDValue Combined = visitORLike(N0, N1, N))
3618 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3619 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3620 if (BSwap.getNode())
3622 BSwap = MatchBSwapHWordLow(N, N0, N1);
3623 if (BSwap.getNode())
3627 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3629 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3630 // iff (c1 & c2) == 0.
3631 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3632 isa<ConstantSDNode>(N0.getOperand(1))) {
3633 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3634 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3635 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3638 ISD::AND, SDLoc(N), VT,
3639 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3643 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3644 if (N0.getOpcode() == N1.getOpcode()) {
3645 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3646 if (Tmp.getNode()) return Tmp;
3649 // See if this is some rotate idiom.
3650 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3651 return SDValue(Rot, 0);
3653 // Simplify the operands using demanded-bits information.
3654 if (!VT.isVector() &&
3655 SimplifyDemandedBits(SDValue(N, 0)))
3656 return SDValue(N, 0);
3661 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3662 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3663 if (Op.getOpcode() == ISD::AND) {
3664 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3665 Mask = Op.getOperand(1);
3666 Op = Op.getOperand(0);
3672 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3680 // Return true if we can prove that, whenever Neg and Pos are both in the
3681 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3682 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3684 // (or (shift1 X, Neg), (shift2 X, Pos))
3686 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3687 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3688 // to consider shift amounts with defined behavior.
3689 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3690 // If OpSize is a power of 2 then:
3692 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3693 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3695 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3696 // for the stronger condition:
3698 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3700 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3701 // we can just replace Neg with Neg' for the rest of the function.
3703 // In other cases we check for the even stronger condition:
3705 // Neg == OpSize - Pos [B]
3707 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3708 // behavior if Pos == 0 (and consequently Neg == OpSize).
3710 // We could actually use [A] whenever OpSize is a power of 2, but the
3711 // only extra cases that it would match are those uninteresting ones
3712 // where Neg and Pos are never in range at the same time. E.g. for
3713 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3714 // as well as (sub 32, Pos), but:
3716 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3718 // always invokes undefined behavior for 32-bit X.
3720 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3721 unsigned MaskLoBits = 0;
3722 if (Neg.getOpcode() == ISD::AND &&
3723 isPowerOf2_64(OpSize) &&
3724 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3725 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3726 Neg = Neg.getOperand(0);
3727 MaskLoBits = Log2_64(OpSize);
3730 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3731 if (Neg.getOpcode() != ISD::SUB)
3733 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3736 SDValue NegOp1 = Neg.getOperand(1);
3738 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3739 // Pos'. The truncation is redundant for the purpose of the equality.
3741 Pos.getOpcode() == ISD::AND &&
3742 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3743 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3744 Pos = Pos.getOperand(0);
3746 // The condition we need is now:
3748 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3750 // If NegOp1 == Pos then we need:
3752 // OpSize & Mask == NegC & Mask
3754 // (because "x & Mask" is a truncation and distributes through subtraction).
3757 Width = NegC->getAPIntValue();
3758 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3759 // Then the condition we want to prove becomes:
3761 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3763 // which, again because "x & Mask" is a truncation, becomes:
3765 // NegC & Mask == (OpSize - PosC) & Mask
3766 // OpSize & Mask == (NegC + PosC) & Mask
3767 else if (Pos.getOpcode() == ISD::ADD &&
3768 Pos.getOperand(0) == NegOp1 &&
3769 Pos.getOperand(1).getOpcode() == ISD::Constant)
3770 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3771 NegC->getAPIntValue());
3775 // Now we just need to check that OpSize & Mask == Width & Mask.
3777 // Opsize & Mask is 0 since Mask is Opsize - 1.
3778 return Width.getLoBits(MaskLoBits) == 0;
3779 return Width == OpSize;
3782 // A subroutine of MatchRotate used once we have found an OR of two opposite
3783 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3784 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3785 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3786 // Neg with outer conversions stripped away.
3787 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3788 SDValue Neg, SDValue InnerPos,
3789 SDValue InnerNeg, unsigned PosOpcode,
3790 unsigned NegOpcode, SDLoc DL) {
3791 // fold (or (shl x, (*ext y)),
3792 // (srl x, (*ext (sub 32, y)))) ->
3793 // (rotl x, y) or (rotr x, (sub 32, y))
3795 // fold (or (shl x, (*ext (sub 32, y))),
3796 // (srl x, (*ext y))) ->
3797 // (rotr x, y) or (rotl x, (sub 32, y))
3798 EVT VT = Shifted.getValueType();
3799 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3800 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3801 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3802 HasPos ? Pos : Neg).getNode();
3808 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3809 // idioms for rotate, and if the target supports rotation instructions, generate
3811 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3812 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3813 EVT VT = LHS.getValueType();
3814 if (!TLI.isTypeLegal(VT)) return nullptr;
3816 // The target must have at least one rotate flavor.
3817 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3818 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3819 if (!HasROTL && !HasROTR) return nullptr;
3821 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3822 SDValue LHSShift; // The shift.
3823 SDValue LHSMask; // AND value if any.
3824 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3825 return nullptr; // Not part of a rotate.
3827 SDValue RHSShift; // The shift.
3828 SDValue RHSMask; // AND value if any.
3829 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3830 return nullptr; // Not part of a rotate.
3832 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3833 return nullptr; // Not shifting the same value.
3835 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3836 return nullptr; // Shifts must disagree.
3838 // Canonicalize shl to left side in a shl/srl pair.
3839 if (RHSShift.getOpcode() == ISD::SHL) {
3840 std::swap(LHS, RHS);
3841 std::swap(LHSShift, RHSShift);
3842 std::swap(LHSMask , RHSMask );
3845 unsigned OpSizeInBits = VT.getSizeInBits();
3846 SDValue LHSShiftArg = LHSShift.getOperand(0);
3847 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3848 SDValue RHSShiftArg = RHSShift.getOperand(0);
3849 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3851 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3852 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3853 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3854 RHSShiftAmt.getOpcode() == ISD::Constant) {
3855 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3856 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3857 if ((LShVal + RShVal) != OpSizeInBits)
3860 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3861 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3863 // If there is an AND of either shifted operand, apply it to the result.
3864 if (LHSMask.getNode() || RHSMask.getNode()) {
3865 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3867 if (LHSMask.getNode()) {
3868 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3869 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3871 if (RHSMask.getNode()) {
3872 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3873 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3876 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3879 return Rot.getNode();
3882 // If there is a mask here, and we have a variable shift, we can't be sure
3883 // that we're masking out the right stuff.
3884 if (LHSMask.getNode() || RHSMask.getNode())
3887 // If the shift amount is sign/zext/any-extended just peel it off.
3888 SDValue LExtOp0 = LHSShiftAmt;
3889 SDValue RExtOp0 = RHSShiftAmt;
3890 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3891 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3892 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3893 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3894 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3895 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3896 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3897 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3898 LExtOp0 = LHSShiftAmt.getOperand(0);
3899 RExtOp0 = RHSShiftAmt.getOperand(0);
3902 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3903 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3907 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3908 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3915 SDValue DAGCombiner::visitXOR(SDNode *N) {
3916 SDValue N0 = N->getOperand(0);
3917 SDValue N1 = N->getOperand(1);
3918 EVT VT = N0.getValueType();
3921 if (VT.isVector()) {
3922 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3925 // fold (xor x, 0) -> x, vector edition
3926 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3928 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3932 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3933 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3934 return DAG.getConstant(0, SDLoc(N), VT);
3935 // fold (xor x, undef) -> undef
3936 if (N0.getOpcode() == ISD::UNDEF)
3938 if (N1.getOpcode() == ISD::UNDEF)
3940 // fold (xor c1, c2) -> c1^c2
3941 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3942 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3944 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3945 // canonicalize constant to RHS
3946 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3947 !isConstantIntBuildVectorOrConstantInt(N1))
3948 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3949 // fold (xor x, 0) -> x
3950 if (N1C && N1C->isNullValue())
3953 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3956 // fold !(x cc y) -> (x !cc y)
3957 SDValue LHS, RHS, CC;
3958 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3959 bool isInt = LHS.getValueType().isInteger();
3960 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3963 if (!LegalOperations ||
3964 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3965 switch (N0.getOpcode()) {
3967 llvm_unreachable("Unhandled SetCC Equivalent!");
3969 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3970 case ISD::SELECT_CC:
3971 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3972 N0.getOperand(3), NotCC);
3977 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3978 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3979 N0.getNode()->hasOneUse() &&
3980 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3981 SDValue V = N0.getOperand(0);
3983 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3984 DAG.getConstant(1, DL, V.getValueType()));
3985 AddToWorklist(V.getNode());
3986 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3989 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3990 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3991 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3992 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3993 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3994 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3995 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3996 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3997 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3998 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4001 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4002 if (N1C && N1C->isAllOnesValue() &&
4003 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4004 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4005 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4006 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4007 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4008 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4009 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4010 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4013 // fold (xor (and x, y), y) -> (and (not x), y)
4014 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4015 N0->getOperand(1) == N1) {
4016 SDValue X = N0->getOperand(0);
4017 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4018 AddToWorklist(NotX.getNode());
4019 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4021 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4022 if (N1C && N0.getOpcode() == ISD::XOR) {
4023 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4024 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4027 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4028 DAG.getConstant(N1C->getAPIntValue() ^
4029 N00C->getAPIntValue(), DL, VT));
4033 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4034 DAG.getConstant(N1C->getAPIntValue() ^
4035 N01C->getAPIntValue(), DL, VT));
4038 // fold (xor x, x) -> 0
4040 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4042 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4043 // Here is a concrete example of this equivalence:
4045 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4046 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4050 // i16 ~1 == 0b1111111111111110
4051 // i16 rol(~1, 14) == 0b1011111111111111
4053 // Some additional tips to help conceptualize this transform:
4054 // - Try to see the operation as placing a single zero in a value of all ones.
4055 // - There exists no value for x which would allow the result to contain zero.
4056 // - Values of x larger than the bitwidth are undefined and do not require a
4057 // consistent result.
4058 // - Pushing the zero left requires shifting one bits in from the right.
4059 // A rotate left of ~1 is a nice way of achieving the desired result.
4060 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4061 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4062 if (N0.getOpcode() == ISD::SHL)
4063 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4064 if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4066 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4070 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4071 if (N0.getOpcode() == N1.getOpcode()) {
4072 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4073 if (Tmp.getNode()) return Tmp;
4076 // Simplify the expression using non-local knowledge.
4077 if (!VT.isVector() &&
4078 SimplifyDemandedBits(SDValue(N, 0)))
4079 return SDValue(N, 0);
4084 /// Handle transforms common to the three shifts, when the shift amount is a
4086 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4087 // We can't and shouldn't fold opaque constants.
4088 if (Amt->isOpaque())
4091 SDNode *LHS = N->getOperand(0).getNode();
4092 if (!LHS->hasOneUse()) return SDValue();
4094 // We want to pull some binops through shifts, so that we have (and (shift))
4095 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4096 // thing happens with address calculations, so it's important to canonicalize
4098 bool HighBitSet = false; // Can we transform this if the high bit is set?
4100 switch (LHS->getOpcode()) {
4101 default: return SDValue();
4104 HighBitSet = false; // We can only transform sra if the high bit is clear.
4107 HighBitSet = true; // We can only transform sra if the high bit is set.
4110 if (N->getOpcode() != ISD::SHL)
4111 return SDValue(); // only shl(add) not sr[al](add).
4112 HighBitSet = false; // We can only transform sra if the high bit is clear.
4116 // We require the RHS of the binop to be a constant and not opaque as well.
4117 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4118 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4120 // FIXME: disable this unless the input to the binop is a shift by a constant.
4121 // If it is not a shift, it pessimizes some common cases like:
4123 // void foo(int *X, int i) { X[i & 1235] = 1; }
4124 // int bar(int *X, int i) { return X[i & 255]; }
4125 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4126 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4127 BinOpLHSVal->getOpcode() != ISD::SRA &&
4128 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4129 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4132 EVT VT = N->getValueType(0);
4134 // If this is a signed shift right, and the high bit is modified by the
4135 // logical operation, do not perform the transformation. The highBitSet
4136 // boolean indicates the value of the high bit of the constant which would
4137 // cause it to be modified for this operation.
4138 if (N->getOpcode() == ISD::SRA) {
4139 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4140 if (BinOpRHSSignSet != HighBitSet)
4144 if (!TLI.isDesirableToCommuteWithShift(LHS))
4147 // Fold the constants, shifting the binop RHS by the shift amount.
4148 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4150 LHS->getOperand(1), N->getOperand(1));
4151 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4153 // Create the new shift.
4154 SDValue NewShift = DAG.getNode(N->getOpcode(),
4155 SDLoc(LHS->getOperand(0)),
4156 VT, LHS->getOperand(0), N->getOperand(1));
4158 // Create the new binop.
4159 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4162 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4163 assert(N->getOpcode() == ISD::TRUNCATE);
4164 assert(N->getOperand(0).getOpcode() == ISD::AND);
4166 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4167 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4168 SDValue N01 = N->getOperand(0).getOperand(1);
4170 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4171 EVT TruncVT = N->getValueType(0);
4172 SDValue N00 = N->getOperand(0).getOperand(0);
4173 APInt TruncC = N01C->getAPIntValue();
4174 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4177 return DAG.getNode(ISD::AND, DL, TruncVT,
4178 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4179 DAG.getConstant(TruncC, DL, TruncVT));
4186 SDValue DAGCombiner::visitRotate(SDNode *N) {
4187 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4188 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4189 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4190 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4191 if (NewOp1.getNode())
4192 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4193 N->getOperand(0), NewOp1);
4198 SDValue DAGCombiner::visitSHL(SDNode *N) {
4199 SDValue N0 = N->getOperand(0);
4200 SDValue N1 = N->getOperand(1);
4201 EVT VT = N0.getValueType();
4202 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4205 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4206 if (VT.isVector()) {
4207 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4210 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4211 // If setcc produces all-one true value then:
4212 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4213 if (N1CV && N1CV->isConstant()) {
4214 if (N0.getOpcode() == ISD::AND) {
4215 SDValue N00 = N0->getOperand(0);
4216 SDValue N01 = N0->getOperand(1);
4217 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4219 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4220 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4221 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4222 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4224 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4227 N1C = isConstOrConstSplat(N1);
4232 // fold (shl c1, c2) -> c1<<c2
4233 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4235 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4236 // fold (shl 0, x) -> 0
4237 if (N0C && N0C->isNullValue())
4239 // fold (shl x, c >= size(x)) -> undef
4240 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4241 return DAG.getUNDEF(VT);
4242 // fold (shl x, 0) -> x
4243 if (N1C && N1C->isNullValue())
4245 // fold (shl undef, x) -> 0
4246 if (N0.getOpcode() == ISD::UNDEF)
4247 return DAG.getConstant(0, SDLoc(N), VT);
4248 // if (shl x, c) is known to be zero, return 0
4249 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4250 APInt::getAllOnesValue(OpSizeInBits)))
4251 return DAG.getConstant(0, SDLoc(N), VT);
4252 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4253 if (N1.getOpcode() == ISD::TRUNCATE &&
4254 N1.getOperand(0).getOpcode() == ISD::AND) {
4255 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4256 if (NewOp1.getNode())
4257 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4260 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4261 return SDValue(N, 0);
4263 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4264 if (N1C && N0.getOpcode() == ISD::SHL) {
4265 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4266 uint64_t c1 = N0C1->getZExtValue();
4267 uint64_t c2 = N1C->getZExtValue();
4269 if (c1 + c2 >= OpSizeInBits)
4270 return DAG.getConstant(0, DL, VT);
4271 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4272 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4276 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4277 // For this to be valid, the second form must not preserve any of the bits
4278 // that are shifted out by the inner shift in the first form. This means
4279 // the outer shift size must be >= the number of bits added by the ext.
4280 // As a corollary, we don't care what kind of ext it is.
4281 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4282 N0.getOpcode() == ISD::ANY_EXTEND ||
4283 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4284 N0.getOperand(0).getOpcode() == ISD::SHL) {
4285 SDValue N0Op0 = N0.getOperand(0);
4286 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4287 uint64_t c1 = N0Op0C1->getZExtValue();
4288 uint64_t c2 = N1C->getZExtValue();
4289 EVT InnerShiftVT = N0Op0.getValueType();
4290 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4291 if (c2 >= OpSizeInBits - InnerShiftSize) {
4293 if (c1 + c2 >= OpSizeInBits)
4294 return DAG.getConstant(0, DL, VT);
4295 return DAG.getNode(ISD::SHL, DL, VT,
4296 DAG.getNode(N0.getOpcode(), DL, VT,
4297 N0Op0->getOperand(0)),
4298 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4303 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4304 // Only fold this if the inner zext has no other uses to avoid increasing
4305 // the total number of instructions.
4306 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4307 N0.getOperand(0).getOpcode() == ISD::SRL) {
4308 SDValue N0Op0 = N0.getOperand(0);
4309 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4310 uint64_t c1 = N0Op0C1->getZExtValue();
4311 if (c1 < VT.getScalarSizeInBits()) {
4312 uint64_t c2 = N1C->getZExtValue();
4314 SDValue NewOp0 = N0.getOperand(0);
4315 EVT CountVT = NewOp0.getOperand(1).getValueType();
4317 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4319 DAG.getConstant(c2, DL, CountVT));
4320 AddToWorklist(NewSHL.getNode());
4321 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4327 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4328 // (and (srl x, (sub c1, c2), MASK)
4329 // Only fold this if the inner shift has no other uses -- if it does, folding
4330 // this will increase the total number of instructions.
4331 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4332 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4333 uint64_t c1 = N0C1->getZExtValue();
4334 if (c1 < OpSizeInBits) {
4335 uint64_t c2 = N1C->getZExtValue();
4336 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4339 Mask = Mask.shl(c2 - c1);
4341 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4342 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4344 Mask = Mask.lshr(c1 - c2);
4346 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4347 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4350 return DAG.getNode(ISD::AND, DL, VT, Shift,
4351 DAG.getConstant(Mask, DL, VT));
4355 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4356 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4357 unsigned BitSize = VT.getScalarSizeInBits();
4359 SDValue HiBitsMask =
4360 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4361 BitSize - N1C->getZExtValue()),
4363 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4367 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4368 // Variant of version done on multiply, except mul by a power of 2 is turned
4371 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4372 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4373 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4374 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4375 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4376 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4380 SDValue NewSHL = visitShiftByConstant(N, N1C);
4381 if (NewSHL.getNode())
4388 SDValue DAGCombiner::visitSRA(SDNode *N) {
4389 SDValue N0 = N->getOperand(0);
4390 SDValue N1 = N->getOperand(1);
4391 EVT VT = N0.getValueType();
4392 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4395 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4396 if (VT.isVector()) {
4397 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4400 N1C = isConstOrConstSplat(N1);
4403 // fold (sra c1, c2) -> (sra c1, c2)
4404 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4406 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4407 // fold (sra 0, x) -> 0
4408 if (N0C && N0C->isNullValue())
4410 // fold (sra -1, x) -> -1
4411 if (N0C && N0C->isAllOnesValue())
4413 // fold (sra x, (setge c, size(x))) -> undef
4414 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4415 return DAG.getUNDEF(VT);
4416 // fold (sra x, 0) -> x
4417 if (N1C && N1C->isNullValue())
4419 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4421 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4422 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4423 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4425 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4426 ExtVT, VT.getVectorNumElements());
4427 if ((!LegalOperations ||
4428 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4429 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4430 N0.getOperand(0), DAG.getValueType(ExtVT));
4433 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4434 if (N1C && N0.getOpcode() == ISD::SRA) {
4435 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4436 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4437 if (Sum >= OpSizeInBits)
4438 Sum = OpSizeInBits - 1;
4440 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4441 DAG.getConstant(Sum, DL, N1.getValueType()));
4445 // fold (sra (shl X, m), (sub result_size, n))
4446 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4447 // result_size - n != m.
4448 // If truncate is free for the target sext(shl) is likely to result in better
4450 if (N0.getOpcode() == ISD::SHL && N1C) {
4451 // Get the two constanst of the shifts, CN0 = m, CN = n.
4452 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4454 LLVMContext &Ctx = *DAG.getContext();
4455 // Determine what the truncate's result bitsize and type would be.
4456 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4459 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4461 // Determine the residual right-shift amount.
4462 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4464 // If the shift is not a no-op (in which case this should be just a sign
4465 // extend already), the truncated to type is legal, sign_extend is legal
4466 // on that type, and the truncate to that type is both legal and free,
4467 // perform the transform.
4468 if ((ShiftAmt > 0) &&
4469 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4470 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4471 TLI.isTruncateFree(VT, TruncVT)) {
4474 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4475 getShiftAmountTy(N0.getOperand(0).getValueType()));
4476 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4477 N0.getOperand(0), Amt);
4478 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4480 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4481 N->getValueType(0), Trunc);
4486 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4487 if (N1.getOpcode() == ISD::TRUNCATE &&
4488 N1.getOperand(0).getOpcode() == ISD::AND) {
4489 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4490 if (NewOp1.getNode())
4491 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4494 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4495 // if c1 is equal to the number of bits the trunc removes
4496 if (N0.getOpcode() == ISD::TRUNCATE &&
4497 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4498 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4499 N0.getOperand(0).hasOneUse() &&
4500 N0.getOperand(0).getOperand(1).hasOneUse() &&
4502 SDValue N0Op0 = N0.getOperand(0);
4503 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4504 unsigned LargeShiftVal = LargeShift->getZExtValue();
4505 EVT LargeVT = N0Op0.getValueType();
4507 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4510 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4511 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4512 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4513 N0Op0.getOperand(0), Amt);
4514 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4519 // Simplify, based on bits shifted out of the LHS.
4520 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4521 return SDValue(N, 0);
4524 // If the sign bit is known to be zero, switch this to a SRL.
4525 if (DAG.SignBitIsZero(N0))
4526 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4529 SDValue NewSRA = visitShiftByConstant(N, N1C);
4530 if (NewSRA.getNode())
4537 SDValue DAGCombiner::visitSRL(SDNode *N) {
4538 SDValue N0 = N->getOperand(0);
4539 SDValue N1 = N->getOperand(1);
4540 EVT VT = N0.getValueType();
4541 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4544 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4545 if (VT.isVector()) {
4546 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4549 N1C = isConstOrConstSplat(N1);
4552 // fold (srl c1, c2) -> c1 >>u c2
4553 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4555 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4556 // fold (srl 0, x) -> 0
4557 if (N0C && N0C->isNullValue())
4559 // fold (srl x, c >= size(x)) -> undef
4560 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4561 return DAG.getUNDEF(VT);
4562 // fold (srl x, 0) -> x
4563 if (N1C && N1C->isNullValue())
4565 // if (srl x, c) is known to be zero, return 0
4566 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4567 APInt::getAllOnesValue(OpSizeInBits)))
4568 return DAG.getConstant(0, SDLoc(N), VT);
4570 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4571 if (N1C && N0.getOpcode() == ISD::SRL) {
4572 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4573 uint64_t c1 = N01C->getZExtValue();
4574 uint64_t c2 = N1C->getZExtValue();
4576 if (c1 + c2 >= OpSizeInBits)
4577 return DAG.getConstant(0, DL, VT);
4578 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4579 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4583 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4584 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4585 N0.getOperand(0).getOpcode() == ISD::SRL &&
4586 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4588 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4589 uint64_t c2 = N1C->getZExtValue();
4590 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4591 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4592 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4593 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4594 if (c1 + OpSizeInBits == InnerShiftSize) {
4596 if (c1 + c2 >= InnerShiftSize)
4597 return DAG.getConstant(0, DL, VT);
4598 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4599 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4600 N0.getOperand(0)->getOperand(0),
4601 DAG.getConstant(c1 + c2, DL,
4606 // fold (srl (shl x, c), c) -> (and x, cst2)
4607 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4608 unsigned BitSize = N0.getScalarValueSizeInBits();
4609 if (BitSize <= 64) {
4610 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4612 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4613 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4617 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4618 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4619 // Shifting in all undef bits?
4620 EVT SmallVT = N0.getOperand(0).getValueType();
4621 unsigned BitSize = SmallVT.getScalarSizeInBits();
4622 if (N1C->getZExtValue() >= BitSize)
4623 return DAG.getUNDEF(VT);
4625 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4626 uint64_t ShiftAmt = N1C->getZExtValue();
4628 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4630 DAG.getConstant(ShiftAmt, DL0,
4631 getShiftAmountTy(SmallVT)));
4632 AddToWorklist(SmallShift.getNode());
4633 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4635 return DAG.getNode(ISD::AND, DL, VT,
4636 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4637 DAG.getConstant(Mask, DL, VT));
4641 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4642 // bit, which is unmodified by sra.
4643 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4644 if (N0.getOpcode() == ISD::SRA)
4645 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4648 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4649 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4650 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4651 APInt KnownZero, KnownOne;
4652 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4654 // If any of the input bits are KnownOne, then the input couldn't be all
4655 // zeros, thus the result of the srl will always be zero.
4656 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4658 // If all of the bits input the to ctlz node are known to be zero, then
4659 // the result of the ctlz is "32" and the result of the shift is one.
4660 APInt UnknownBits = ~KnownZero;
4661 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4663 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4664 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4665 // Okay, we know that only that the single bit specified by UnknownBits
4666 // could be set on input to the CTLZ node. If this bit is set, the SRL
4667 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4668 // to an SRL/XOR pair, which is likely to simplify more.
4669 unsigned ShAmt = UnknownBits.countTrailingZeros();
4670 SDValue Op = N0.getOperand(0);
4674 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4675 DAG.getConstant(ShAmt, DL,
4676 getShiftAmountTy(Op.getValueType())));
4677 AddToWorklist(Op.getNode());
4681 return DAG.getNode(ISD::XOR, DL, VT,
4682 Op, DAG.getConstant(1, DL, VT));
4686 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4687 if (N1.getOpcode() == ISD::TRUNCATE &&
4688 N1.getOperand(0).getOpcode() == ISD::AND) {
4689 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4690 if (NewOp1.getNode())
4691 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4694 // fold operands of srl based on knowledge that the low bits are not
4696 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4697 return SDValue(N, 0);
4700 SDValue NewSRL = visitShiftByConstant(N, N1C);
4701 if (NewSRL.getNode())
4705 // Attempt to convert a srl of a load into a narrower zero-extending load.
4706 SDValue NarrowLoad = ReduceLoadWidth(N);
4707 if (NarrowLoad.getNode())
4710 // Here is a common situation. We want to optimize:
4713 // %b = and i32 %a, 2
4714 // %c = srl i32 %b, 1
4715 // brcond i32 %c ...
4721 // %c = setcc eq %b, 0
4724 // However when after the source operand of SRL is optimized into AND, the SRL
4725 // itself may not be optimized further. Look for it and add the BRCOND into
4727 if (N->hasOneUse()) {
4728 SDNode *Use = *N->use_begin();
4729 if (Use->getOpcode() == ISD::BRCOND)
4731 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4732 // Also look pass the truncate.
4733 Use = *Use->use_begin();
4734 if (Use->getOpcode() == ISD::BRCOND)
4742 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4743 SDValue N0 = N->getOperand(0);
4744 EVT VT = N->getValueType(0);
4746 // fold (ctlz c1) -> c2
4747 if (isa<ConstantSDNode>(N0))
4748 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4752 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4753 SDValue N0 = N->getOperand(0);
4754 EVT VT = N->getValueType(0);
4756 // fold (ctlz_zero_undef c1) -> c2
4757 if (isa<ConstantSDNode>(N0))
4758 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4762 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4763 SDValue N0 = N->getOperand(0);
4764 EVT VT = N->getValueType(0);
4766 // fold (cttz c1) -> c2
4767 if (isa<ConstantSDNode>(N0))
4768 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4772 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4773 SDValue N0 = N->getOperand(0);
4774 EVT VT = N->getValueType(0);
4776 // fold (cttz_zero_undef c1) -> c2
4777 if (isa<ConstantSDNode>(N0))
4778 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4782 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4783 SDValue N0 = N->getOperand(0);
4784 EVT VT = N->getValueType(0);
4786 // fold (ctpop c1) -> c2
4787 if (isa<ConstantSDNode>(N0))
4788 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4793 /// \brief Generate Min/Max node
4794 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4795 SDValue True, SDValue False,
4796 ISD::CondCode CC, const TargetLowering &TLI,
4797 SelectionDAG &DAG) {
4798 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4808 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4809 if (TLI.isOperationLegal(Opcode, VT))
4810 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4819 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4820 if (TLI.isOperationLegal(Opcode, VT))
4821 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4829 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4830 SDValue N0 = N->getOperand(0);
4831 SDValue N1 = N->getOperand(1);
4832 SDValue N2 = N->getOperand(2);
4833 EVT VT = N->getValueType(0);
4834 EVT VT0 = N0.getValueType();
4836 // fold (select C, X, X) -> X
4839 // fold (select true, X, Y) -> X
4840 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4841 if (N0C && !N0C->isNullValue())
4843 // fold (select false, X, Y) -> Y
4844 if (N0C && N0C->isNullValue())
4846 // fold (select C, 1, X) -> (or C, X)
4847 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4848 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4849 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4850 // fold (select C, 0, 1) -> (xor C, 1)
4851 // We can't do this reliably if integer based booleans have different contents
4852 // to floating point based booleans. This is because we can't tell whether we
4853 // have an integer-based boolean or a floating-point-based boolean unless we
4854 // can find the SETCC that produced it and inspect its operands. This is
4855 // fairly easy if C is the SETCC node, but it can potentially be
4856 // undiscoverable (or not reasonably discoverable). For example, it could be
4857 // in another basic block or it could require searching a complicated
4859 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4860 if (VT.isInteger() &&
4861 (VT0 == MVT::i1 || (VT0.isInteger() &&
4862 TLI.getBooleanContents(false, false) ==
4863 TLI.getBooleanContents(false, true) &&
4864 TLI.getBooleanContents(false, false) ==
4865 TargetLowering::ZeroOrOneBooleanContent)) &&
4866 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4870 return DAG.getNode(ISD::XOR, DL, VT0,
4871 N0, DAG.getConstant(1, DL, VT0));
4874 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4875 N0, DAG.getConstant(1, DL0, VT0));
4876 AddToWorklist(XORNode.getNode());
4878 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4879 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4881 // fold (select C, 0, X) -> (and (not C), X)
4882 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4883 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4884 AddToWorklist(NOTNode.getNode());
4885 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4887 // fold (select C, X, 1) -> (or (not C), X)
4888 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4889 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4890 AddToWorklist(NOTNode.getNode());
4891 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4893 // fold (select C, X, 0) -> (and C, X)
4894 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4895 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4896 // fold (select X, X, Y) -> (or X, Y)
4897 // fold (select X, 1, Y) -> (or X, Y)
4898 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4899 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4900 // fold (select X, Y, X) -> (and X, Y)
4901 // fold (select X, Y, 0) -> (and X, Y)
4902 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4903 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4905 // If we can fold this based on the true/false value, do so.
4906 if (SimplifySelectOps(N, N1, N2))
4907 return SDValue(N, 0); // Don't revisit N.
4909 // fold selects based on a setcc into other things, such as min/max/abs
4910 if (N0.getOpcode() == ISD::SETCC) {
4911 // select x, y (fcmp lt x, y) -> fminnum x, y
4912 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4914 // This is OK if we don't care about what happens if either operand is a
4918 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4919 // no signed zeros as well as no nans.
4920 const TargetOptions &Options = DAG.getTarget().Options;
4921 if (Options.UnsafeFPMath &&
4922 VT.isFloatingPoint() && N0.hasOneUse() &&
4923 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4924 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4927 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4928 N1, N2, CC, TLI, DAG);
4933 if ((!LegalOperations &&
4934 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4935 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4936 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4937 N0.getOperand(0), N0.getOperand(1),
4938 N1, N2, N0.getOperand(2));
4939 return SimplifySelect(SDLoc(N), N0, N1, N2);
4942 if (VT0 == MVT::i1) {
4943 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4944 // select (and Cond0, Cond1), X, Y
4945 // -> select Cond0, (select Cond1, X, Y), Y
4946 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4947 SDValue Cond0 = N0->getOperand(0);
4948 SDValue Cond1 = N0->getOperand(1);
4949 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4950 N1.getValueType(), Cond1, N1, N2);
4951 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4954 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4955 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4956 SDValue Cond0 = N0->getOperand(0);
4957 SDValue Cond1 = N0->getOperand(1);
4958 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4959 N1.getValueType(), Cond1, N1, N2);
4960 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4965 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4966 if (N1->getOpcode() == ISD::SELECT) {
4967 SDValue N1_0 = N1->getOperand(0);
4968 SDValue N1_1 = N1->getOperand(1);
4969 SDValue N1_2 = N1->getOperand(2);
4970 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4971 // Create the actual and node if we can generate good code for it.
4972 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4973 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4975 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4978 // Otherwise see if we can optimize the "and" to a better pattern.
4979 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4980 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4984 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4985 if (N2->getOpcode() == ISD::SELECT) {
4986 SDValue N2_0 = N2->getOperand(0);
4987 SDValue N2_1 = N2->getOperand(1);
4988 SDValue N2_2 = N2->getOperand(2);
4989 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4990 // Create the actual or node if we can generate good code for it.
4991 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4992 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4994 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4997 // Otherwise see if we can optimize to a better pattern.
4998 if (SDValue Combined = visitORLike(N0, N2_0, N))
4999 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5009 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5012 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5014 // Split the inputs.
5015 SDValue Lo, Hi, LL, LH, RL, RH;
5016 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5017 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5019 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5020 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5022 return std::make_pair(Lo, Hi);
5025 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5026 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5027 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5029 SDValue Cond = N->getOperand(0);
5030 SDValue LHS = N->getOperand(1);
5031 SDValue RHS = N->getOperand(2);
5032 EVT VT = N->getValueType(0);
5033 int NumElems = VT.getVectorNumElements();
5034 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5035 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5036 Cond.getOpcode() == ISD::BUILD_VECTOR);
5038 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5039 // binary ones here.
5040 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5043 // We're sure we have an even number of elements due to the
5044 // concat_vectors we have as arguments to vselect.
5045 // Skip BV elements until we find one that's not an UNDEF
5046 // After we find an UNDEF element, keep looping until we get to half the
5047 // length of the BV and see if all the non-undef nodes are the same.
5048 ConstantSDNode *BottomHalf = nullptr;
5049 for (int i = 0; i < NumElems / 2; ++i) {
5050 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5053 if (BottomHalf == nullptr)
5054 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5055 else if (Cond->getOperand(i).getNode() != BottomHalf)
5059 // Do the same for the second half of the BuildVector
5060 ConstantSDNode *TopHalf = nullptr;
5061 for (int i = NumElems / 2; i < NumElems; ++i) {
5062 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5065 if (TopHalf == nullptr)
5066 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5067 else if (Cond->getOperand(i).getNode() != TopHalf)
5071 assert(TopHalf && BottomHalf &&
5072 "One half of the selector was all UNDEFs and the other was all the "
5073 "same value. This should have been addressed before this function.");
5075 ISD::CONCAT_VECTORS, dl, VT,
5076 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5077 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5080 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5082 if (Level >= AfterLegalizeTypes)
5085 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5086 SDValue Mask = MSC->getMask();
5087 SDValue Data = MSC->getValue();
5090 // If the MSCATTER data type requires splitting and the mask is provided by a
5091 // SETCC, then split both nodes and its operands before legalization. This
5092 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5093 // and enables future optimizations (e.g. min/max pattern matching on X86).
5094 if (Mask.getOpcode() != ISD::SETCC)
5097 // Check if any splitting is required.
5098 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5099 TargetLowering::TypeSplitVector)
5101 SDValue MaskLo, MaskHi, Lo, Hi;
5102 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5105 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5107 SDValue Chain = MSC->getChain();
5109 EVT MemoryVT = MSC->getMemoryVT();
5110 unsigned Alignment = MSC->getOriginalAlignment();
5112 EVT LoMemVT, HiMemVT;
5113 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5115 SDValue DataLo, DataHi;
5116 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5118 SDValue BasePtr = MSC->getBasePtr();
5119 SDValue IndexLo, IndexHi;
5120 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5122 MachineMemOperand *MMO = DAG.getMachineFunction().
5123 getMachineMemOperand(MSC->getPointerInfo(),
5124 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5125 Alignment, MSC->getAAInfo(), MSC->getRanges());
5127 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5128 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5131 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5132 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5135 AddToWorklist(Lo.getNode());
5136 AddToWorklist(Hi.getNode());
5138 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5141 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5143 if (Level >= AfterLegalizeTypes)
5146 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5147 SDValue Mask = MST->getMask();
5148 SDValue Data = MST->getValue();
5151 // If the MSTORE data type requires splitting and the mask is provided by a
5152 // SETCC, then split both nodes and its operands before legalization. This
5153 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5154 // and enables future optimizations (e.g. min/max pattern matching on X86).
5155 if (Mask.getOpcode() == ISD::SETCC) {
5157 // Check if any splitting is required.
5158 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5159 TargetLowering::TypeSplitVector)
5162 SDValue MaskLo, MaskHi, Lo, Hi;
5163 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5166 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5168 SDValue Chain = MST->getChain();
5169 SDValue Ptr = MST->getBasePtr();
5171 EVT MemoryVT = MST->getMemoryVT();
5172 unsigned Alignment = MST->getOriginalAlignment();
5174 // if Alignment is equal to the vector size,
5175 // take the half of it for the second part
5176 unsigned SecondHalfAlignment =
5177 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5178 Alignment/2 : Alignment;
5180 EVT LoMemVT, HiMemVT;
5181 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5183 SDValue DataLo, DataHi;
5184 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5186 MachineMemOperand *MMO = DAG.getMachineFunction().
5187 getMachineMemOperand(MST->getPointerInfo(),
5188 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5189 Alignment, MST->getAAInfo(), MST->getRanges());
5191 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5192 MST->isTruncatingStore());
5194 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5195 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5196 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5198 MMO = DAG.getMachineFunction().
5199 getMachineMemOperand(MST->getPointerInfo(),
5200 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5201 SecondHalfAlignment, MST->getAAInfo(),
5204 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5205 MST->isTruncatingStore());
5207 AddToWorklist(Lo.getNode());
5208 AddToWorklist(Hi.getNode());
5210 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5215 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5217 if (Level >= AfterLegalizeTypes)
5220 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5221 SDValue Mask = MGT->getMask();
5224 // If the MGATHER result requires splitting and the mask is provided by a
5225 // SETCC, then split both nodes and its operands before legalization. This
5226 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5227 // and enables future optimizations (e.g. min/max pattern matching on X86).
5229 if (Mask.getOpcode() != ISD::SETCC)
5232 EVT VT = N->getValueType(0);
5234 // Check if any splitting is required.
5235 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5236 TargetLowering::TypeSplitVector)
5239 SDValue MaskLo, MaskHi, Lo, Hi;
5240 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5242 SDValue Src0 = MGT->getValue();
5243 SDValue Src0Lo, Src0Hi;
5244 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5247 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5249 SDValue Chain = MGT->getChain();
5250 EVT MemoryVT = MGT->getMemoryVT();
5251 unsigned Alignment = MGT->getOriginalAlignment();
5253 EVT LoMemVT, HiMemVT;
5254 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5256 SDValue BasePtr = MGT->getBasePtr();
5257 SDValue Index = MGT->getIndex();
5258 SDValue IndexLo, IndexHi;
5259 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5261 MachineMemOperand *MMO = DAG.getMachineFunction().
5262 getMachineMemOperand(MGT->getPointerInfo(),
5263 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5264 Alignment, MGT->getAAInfo(), MGT->getRanges());
5266 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5267 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5270 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5271 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5274 AddToWorklist(Lo.getNode());
5275 AddToWorklist(Hi.getNode());
5277 // Build a factor node to remember that this load is independent of the
5279 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5282 // Legalized the chain result - switch anything that used the old chain to
5284 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5286 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5288 SDValue RetOps[] = { GatherRes, Chain };
5289 return DAG.getMergeValues(RetOps, DL);
5292 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5294 if (Level >= AfterLegalizeTypes)
5297 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5298 SDValue Mask = MLD->getMask();
5301 // If the MLOAD result requires splitting and the mask is provided by a
5302 // SETCC, then split both nodes and its operands before legalization. This
5303 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5304 // and enables future optimizations (e.g. min/max pattern matching on X86).
5306 if (Mask.getOpcode() == ISD::SETCC) {
5307 EVT VT = N->getValueType(0);
5309 // Check if any splitting is required.
5310 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5311 TargetLowering::TypeSplitVector)
5314 SDValue MaskLo, MaskHi, Lo, Hi;
5315 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5317 SDValue Src0 = MLD->getSrc0();
5318 SDValue Src0Lo, Src0Hi;
5319 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5322 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5324 SDValue Chain = MLD->getChain();
5325 SDValue Ptr = MLD->getBasePtr();
5326 EVT MemoryVT = MLD->getMemoryVT();
5327 unsigned Alignment = MLD->getOriginalAlignment();
5329 // if Alignment is equal to the vector size,
5330 // take the half of it for the second part
5331 unsigned SecondHalfAlignment =
5332 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5333 Alignment/2 : Alignment;
5335 EVT LoMemVT, HiMemVT;
5336 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5338 MachineMemOperand *MMO = DAG.getMachineFunction().
5339 getMachineMemOperand(MLD->getPointerInfo(),
5340 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5341 Alignment, MLD->getAAInfo(), MLD->getRanges());
5343 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5346 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5347 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5348 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5350 MMO = DAG.getMachineFunction().
5351 getMachineMemOperand(MLD->getPointerInfo(),
5352 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5353 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5355 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5358 AddToWorklist(Lo.getNode());
5359 AddToWorklist(Hi.getNode());
5361 // Build a factor node to remember that this load is independent of the
5363 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5366 // Legalized the chain result - switch anything that used the old chain to
5368 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5370 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5372 SDValue RetOps[] = { LoadRes, Chain };
5373 return DAG.getMergeValues(RetOps, DL);
5378 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5379 SDValue N0 = N->getOperand(0);
5380 SDValue N1 = N->getOperand(1);
5381 SDValue N2 = N->getOperand(2);
5384 // Canonicalize integer abs.
5385 // vselect (setg[te] X, 0), X, -X ->
5386 // vselect (setgt X, -1), X, -X ->
5387 // vselect (setl[te] X, 0), -X, X ->
5388 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5389 if (N0.getOpcode() == ISD::SETCC) {
5390 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5391 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5393 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5395 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5396 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5397 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5398 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5399 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5400 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5401 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5404 EVT VT = LHS.getValueType();
5405 SDValue Shift = DAG.getNode(
5406 ISD::SRA, DL, VT, LHS,
5407 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5408 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5409 AddToWorklist(Shift.getNode());
5410 AddToWorklist(Add.getNode());
5411 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5415 if (SimplifySelectOps(N, N1, N2))
5416 return SDValue(N, 0); // Don't revisit N.
5418 // If the VSELECT result requires splitting and the mask is provided by a
5419 // SETCC, then split both nodes and its operands before legalization. This
5420 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5421 // and enables future optimizations (e.g. min/max pattern matching on X86).
5422 if (N0.getOpcode() == ISD::SETCC) {
5423 EVT VT = N->getValueType(0);
5425 // Check if any splitting is required.
5426 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5427 TargetLowering::TypeSplitVector)
5430 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5431 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5432 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5433 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5435 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5436 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5438 // Add the new VSELECT nodes to the work list in case they need to be split
5440 AddToWorklist(Lo.getNode());
5441 AddToWorklist(Hi.getNode());
5443 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5446 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5447 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5449 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5450 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5453 // The ConvertSelectToConcatVector function is assuming both the above
5454 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5456 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5457 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5458 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5459 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5467 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5468 SDValue N0 = N->getOperand(0);
5469 SDValue N1 = N->getOperand(1);
5470 SDValue N2 = N->getOperand(2);
5471 SDValue N3 = N->getOperand(3);
5472 SDValue N4 = N->getOperand(4);
5473 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5475 // fold select_cc lhs, rhs, x, x, cc -> x
5479 // Determine if the condition we're dealing with is constant
5480 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5481 N0, N1, CC, SDLoc(N), false);
5482 if (SCC.getNode()) {
5483 AddToWorklist(SCC.getNode());
5485 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5486 if (!SCCC->isNullValue())
5487 return N2; // cond always true -> true val
5489 return N3; // cond always false -> false val
5490 } else if (SCC->getOpcode() == ISD::UNDEF) {
5491 // When the condition is UNDEF, just return the first operand. This is
5492 // coherent the DAG creation, no setcc node is created in this case
5494 } else if (SCC.getOpcode() == ISD::SETCC) {
5495 // Fold to a simpler select_cc
5496 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5497 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5502 // If we can fold this based on the true/false value, do so.
5503 if (SimplifySelectOps(N, N2, N3))
5504 return SDValue(N, 0); // Don't revisit N.
5506 // fold select_cc into other things, such as min/max/abs
5507 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5510 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5511 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5512 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5516 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5517 // dag node into a ConstantSDNode or a build_vector of constants.
5518 // This function is called by the DAGCombiner when visiting sext/zext/aext
5519 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5520 // Vector extends are not folded if operations are legal; this is to
5521 // avoid introducing illegal build_vector dag nodes.
5522 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5523 SelectionDAG &DAG, bool LegalTypes,
5524 bool LegalOperations) {
5525 unsigned Opcode = N->getOpcode();
5526 SDValue N0 = N->getOperand(0);
5527 EVT VT = N->getValueType(0);
5529 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5530 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5532 // fold (sext c1) -> c1
5533 // fold (zext c1) -> c1
5534 // fold (aext c1) -> c1
5535 if (isa<ConstantSDNode>(N0))
5536 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5538 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5539 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5540 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5541 EVT SVT = VT.getScalarType();
5542 if (!(VT.isVector() &&
5543 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5544 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5547 // We can fold this node into a build_vector.
5548 unsigned VTBits = SVT.getSizeInBits();
5549 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5550 unsigned ShAmt = VTBits - EVTBits;
5551 SmallVector<SDValue, 8> Elts;
5552 unsigned NumElts = N0->getNumOperands();
5555 for (unsigned i=0; i != NumElts; ++i) {
5556 SDValue Op = N0->getOperand(i);
5557 if (Op->getOpcode() == ISD::UNDEF) {
5558 Elts.push_back(DAG.getUNDEF(SVT));
5563 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5564 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5565 if (Opcode == ISD::SIGN_EXTEND)
5566 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5569 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5573 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5576 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5577 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5578 // transformation. Returns true if extension are possible and the above
5579 // mentioned transformation is profitable.
5580 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5582 SmallVectorImpl<SDNode *> &ExtendNodes,
5583 const TargetLowering &TLI) {
5584 bool HasCopyToRegUses = false;
5585 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5586 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5587 UE = N0.getNode()->use_end();
5592 if (UI.getUse().getResNo() != N0.getResNo())
5594 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5595 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5596 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5597 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5598 // Sign bits will be lost after a zext.
5601 for (unsigned i = 0; i != 2; ++i) {
5602 SDValue UseOp = User->getOperand(i);
5605 if (!isa<ConstantSDNode>(UseOp))
5610 ExtendNodes.push_back(User);
5613 // If truncates aren't free and there are users we can't
5614 // extend, it isn't worthwhile.
5617 // Remember if this value is live-out.
5618 if (User->getOpcode() == ISD::CopyToReg)
5619 HasCopyToRegUses = true;
5622 if (HasCopyToRegUses) {
5623 bool BothLiveOut = false;
5624 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5626 SDUse &Use = UI.getUse();
5627 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5633 // Both unextended and extended values are live out. There had better be
5634 // a good reason for the transformation.
5635 return ExtendNodes.size();
5640 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5641 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5642 ISD::NodeType ExtType) {
5643 // Extend SetCC uses if necessary.
5644 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5645 SDNode *SetCC = SetCCs[i];
5646 SmallVector<SDValue, 4> Ops;
5648 for (unsigned j = 0; j != 2; ++j) {
5649 SDValue SOp = SetCC->getOperand(j);
5651 Ops.push_back(ExtLoad);
5653 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5656 Ops.push_back(SetCC->getOperand(2));
5657 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5661 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5662 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5663 SDValue N0 = N->getOperand(0);
5664 EVT DstVT = N->getValueType(0);
5665 EVT SrcVT = N0.getValueType();
5667 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5668 N->getOpcode() == ISD::ZERO_EXTEND) &&
5669 "Unexpected node type (not an extend)!");
5671 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5672 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5673 // (v8i32 (sext (v8i16 (load x))))
5675 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5676 // (v4i32 (sextload (x + 16)))))
5677 // Where uses of the original load, i.e.:
5679 // are replaced with:
5681 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5682 // (v4i32 (sextload (x + 16)))))))
5684 // This combine is only applicable to illegal, but splittable, vectors.
5685 // All legal types, and illegal non-vector types, are handled elsewhere.
5686 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5688 if (N0->getOpcode() != ISD::LOAD)
5691 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5693 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5694 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5695 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5698 SmallVector<SDNode *, 4> SetCCs;
5699 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5702 ISD::LoadExtType ExtType =
5703 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5705 // Try to split the vector types to get down to legal types.
5706 EVT SplitSrcVT = SrcVT;
5707 EVT SplitDstVT = DstVT;
5708 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5709 SplitSrcVT.getVectorNumElements() > 1) {
5710 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5711 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5714 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5718 const unsigned NumSplits =
5719 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5720 const unsigned Stride = SplitSrcVT.getStoreSize();
5721 SmallVector<SDValue, 4> Loads;
5722 SmallVector<SDValue, 4> Chains;
5724 SDValue BasePtr = LN0->getBasePtr();
5725 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5726 const unsigned Offset = Idx * Stride;
5727 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5729 SDValue SplitLoad = DAG.getExtLoad(
5730 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5731 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5732 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5733 Align, LN0->getAAInfo());
5735 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5736 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5738 Loads.push_back(SplitLoad.getValue(0));
5739 Chains.push_back(SplitLoad.getValue(1));
5742 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5743 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5745 CombineTo(N, NewValue);
5747 // Replace uses of the original load (before extension)
5748 // with a truncate of the concatenated sextloaded vectors.
5750 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5751 CombineTo(N0.getNode(), Trunc, NewChain);
5752 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5753 (ISD::NodeType)N->getOpcode());
5754 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5757 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5758 SDValue N0 = N->getOperand(0);
5759 EVT VT = N->getValueType(0);
5761 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5763 return SDValue(Res, 0);
5765 // fold (sext (sext x)) -> (sext x)
5766 // fold (sext (aext x)) -> (sext x)
5767 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5768 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5771 if (N0.getOpcode() == ISD::TRUNCATE) {
5772 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5773 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5774 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5775 if (NarrowLoad.getNode()) {
5776 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5777 if (NarrowLoad.getNode() != N0.getNode()) {
5778 CombineTo(N0.getNode(), NarrowLoad);
5779 // CombineTo deleted the truncate, if needed, but not what's under it.
5782 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5785 // See if the value being truncated is already sign extended. If so, just
5786 // eliminate the trunc/sext pair.
5787 SDValue Op = N0.getOperand(0);
5788 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5789 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5790 unsigned DestBits = VT.getScalarType().getSizeInBits();
5791 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5793 if (OpBits == DestBits) {
5794 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5795 // bits, it is already ready.
5796 if (NumSignBits > DestBits-MidBits)
5798 } else if (OpBits < DestBits) {
5799 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5800 // bits, just sext from i32.
5801 if (NumSignBits > OpBits-MidBits)
5802 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5804 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5805 // bits, just truncate to i32.
5806 if (NumSignBits > OpBits-MidBits)
5807 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5810 // fold (sext (truncate x)) -> (sextinreg x).
5811 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5812 N0.getValueType())) {
5813 if (OpBits < DestBits)
5814 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5815 else if (OpBits > DestBits)
5816 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5817 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5818 DAG.getValueType(N0.getValueType()));
5822 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5823 // Only generate vector extloads when 1) they're legal, and 2) they are
5824 // deemed desirable by the target.
5825 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5826 ((!LegalOperations && !VT.isVector() &&
5827 !cast<LoadSDNode>(N0)->isVolatile()) ||
5828 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5829 bool DoXform = true;
5830 SmallVector<SDNode*, 4> SetCCs;
5831 if (!N0.hasOneUse())
5832 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5834 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5836 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5837 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5839 LN0->getBasePtr(), N0.getValueType(),
5840 LN0->getMemOperand());
5841 CombineTo(N, ExtLoad);
5842 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5843 N0.getValueType(), ExtLoad);
5844 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5845 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5847 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5851 // fold (sext (load x)) to multiple smaller sextloads.
5852 // Only on illegal but splittable vectors.
5853 if (SDValue ExtLoad = CombineExtLoad(N))
5856 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5857 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5858 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5859 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5860 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5861 EVT MemVT = LN0->getMemoryVT();
5862 if ((!LegalOperations && !LN0->isVolatile()) ||
5863 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5864 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5866 LN0->getBasePtr(), MemVT,
5867 LN0->getMemOperand());
5868 CombineTo(N, ExtLoad);
5869 CombineTo(N0.getNode(),
5870 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5871 N0.getValueType(), ExtLoad),
5872 ExtLoad.getValue(1));
5873 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5877 // fold (sext (and/or/xor (load x), cst)) ->
5878 // (and/or/xor (sextload x), (sext cst))
5879 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5880 N0.getOpcode() == ISD::XOR) &&
5881 isa<LoadSDNode>(N0.getOperand(0)) &&
5882 N0.getOperand(1).getOpcode() == ISD::Constant &&
5883 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5884 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5885 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5886 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5887 bool DoXform = true;
5888 SmallVector<SDNode*, 4> SetCCs;
5889 if (!N0.hasOneUse())
5890 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5893 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5894 LN0->getChain(), LN0->getBasePtr(),
5896 LN0->getMemOperand());
5897 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5898 Mask = Mask.sext(VT.getSizeInBits());
5900 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5901 ExtLoad, DAG.getConstant(Mask, DL, VT));
5902 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5903 SDLoc(N0.getOperand(0)),
5904 N0.getOperand(0).getValueType(), ExtLoad);
5906 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5907 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5909 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5914 if (N0.getOpcode() == ISD::SETCC) {
5915 EVT N0VT = N0.getOperand(0).getValueType();
5916 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5917 // Only do this before legalize for now.
5918 if (VT.isVector() && !LegalOperations &&
5919 TLI.getBooleanContents(N0VT) ==
5920 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5921 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5922 // of the same size as the compared operands. Only optimize sext(setcc())
5923 // if this is the case.
5924 EVT SVT = getSetCCResultType(N0VT);
5926 // We know that the # elements of the results is the same as the
5927 // # elements of the compare (and the # elements of the compare result
5928 // for that matter). Check to see that they are the same size. If so,
5929 // we know that the element size of the sext'd result matches the
5930 // element size of the compare operands.
5931 if (VT.getSizeInBits() == SVT.getSizeInBits())
5932 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5934 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5936 // If the desired elements are smaller or larger than the source
5937 // elements we can use a matching integer vector type and then
5938 // truncate/sign extend
5939 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5940 if (SVT == MatchingVectorType) {
5941 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5942 N0.getOperand(0), N0.getOperand(1),
5943 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5944 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5948 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5949 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5952 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5954 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5955 NegOne, DAG.getConstant(0, DL, VT),
5956 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5957 if (SCC.getNode()) return SCC;
5959 if (!VT.isVector()) {
5960 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5961 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5963 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5964 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5965 N0.getOperand(0), N0.getOperand(1), CC);
5966 return DAG.getSelect(DL, VT, SetCC,
5967 NegOne, DAG.getConstant(0, DL, VT));
5972 // fold (sext x) -> (zext x) if the sign bit is known zero.
5973 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5974 DAG.SignBitIsZero(N0))
5975 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5980 // isTruncateOf - If N is a truncate of some other value, return true, record
5981 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5982 // This function computes KnownZero to avoid a duplicated call to
5983 // computeKnownBits in the caller.
5984 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5987 if (N->getOpcode() == ISD::TRUNCATE) {
5988 Op = N->getOperand(0);
5989 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5993 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5994 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5997 SDValue Op0 = N->getOperand(0);
5998 SDValue Op1 = N->getOperand(1);
5999 assert(Op0.getValueType() == Op1.getValueType());
6001 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
6002 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
6003 if (COp0 && COp0->isNullValue())
6005 else if (COp1 && COp1->isNullValue())
6010 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6012 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6018 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6019 SDValue N0 = N->getOperand(0);
6020 EVT VT = N->getValueType(0);
6022 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6024 return SDValue(Res, 0);
6026 // fold (zext (zext x)) -> (zext x)
6027 // fold (zext (aext x)) -> (zext x)
6028 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6029 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6032 // fold (zext (truncate x)) -> (zext x) or
6033 // (zext (truncate x)) -> (truncate x)
6034 // This is valid when the truncated bits of x are already zero.
6035 // FIXME: We should extend this to work for vectors too.
6038 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6039 APInt TruncatedBits =
6040 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6041 APInt(Op.getValueSizeInBits(), 0) :
6042 APInt::getBitsSet(Op.getValueSizeInBits(),
6043 N0.getValueSizeInBits(),
6044 std::min(Op.getValueSizeInBits(),
6045 VT.getSizeInBits()));
6046 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6047 if (VT.bitsGT(Op.getValueType()))
6048 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6049 if (VT.bitsLT(Op.getValueType()))
6050 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6056 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6057 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6058 if (N0.getOpcode() == ISD::TRUNCATE) {
6059 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6060 if (NarrowLoad.getNode()) {
6061 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6062 if (NarrowLoad.getNode() != N0.getNode()) {
6063 CombineTo(N0.getNode(), NarrowLoad);
6064 // CombineTo deleted the truncate, if needed, but not what's under it.
6067 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6071 // fold (zext (truncate x)) -> (and x, mask)
6072 if (N0.getOpcode() == ISD::TRUNCATE &&
6073 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6075 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6076 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6077 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6078 if (NarrowLoad.getNode()) {
6079 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6080 if (NarrowLoad.getNode() != N0.getNode()) {
6081 CombineTo(N0.getNode(), NarrowLoad);
6082 // CombineTo deleted the truncate, if needed, but not what's under it.
6085 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6088 SDValue Op = N0.getOperand(0);
6089 if (Op.getValueType().bitsLT(VT)) {
6090 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6091 AddToWorklist(Op.getNode());
6092 } else if (Op.getValueType().bitsGT(VT)) {
6093 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6094 AddToWorklist(Op.getNode());
6096 return DAG.getZeroExtendInReg(Op, SDLoc(N),
6097 N0.getValueType().getScalarType());
6100 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6101 // if either of the casts is not free.
6102 if (N0.getOpcode() == ISD::AND &&
6103 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6104 N0.getOperand(1).getOpcode() == ISD::Constant &&
6105 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6106 N0.getValueType()) ||
6107 !TLI.isZExtFree(N0.getValueType(), VT))) {
6108 SDValue X = N0.getOperand(0).getOperand(0);
6109 if (X.getValueType().bitsLT(VT)) {
6110 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6111 } else if (X.getValueType().bitsGT(VT)) {
6112 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6114 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6115 Mask = Mask.zext(VT.getSizeInBits());
6117 return DAG.getNode(ISD::AND, DL, VT,
6118 X, DAG.getConstant(Mask, DL, VT));
6121 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6122 // Only generate vector extloads when 1) they're legal, and 2) they are
6123 // deemed desirable by the target.
6124 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6125 ((!LegalOperations && !VT.isVector() &&
6126 !cast<LoadSDNode>(N0)->isVolatile()) ||
6127 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6128 bool DoXform = true;
6129 SmallVector<SDNode*, 4> SetCCs;
6130 if (!N0.hasOneUse())
6131 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6133 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6135 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6136 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6138 LN0->getBasePtr(), N0.getValueType(),
6139 LN0->getMemOperand());
6140 CombineTo(N, ExtLoad);
6141 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6142 N0.getValueType(), ExtLoad);
6143 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6145 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6147 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6151 // fold (zext (load x)) to multiple smaller zextloads.
6152 // Only on illegal but splittable vectors.
6153 if (SDValue ExtLoad = CombineExtLoad(N))
6156 // fold (zext (and/or/xor (load x), cst)) ->
6157 // (and/or/xor (zextload x), (zext cst))
6158 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6159 N0.getOpcode() == ISD::XOR) &&
6160 isa<LoadSDNode>(N0.getOperand(0)) &&
6161 N0.getOperand(1).getOpcode() == ISD::Constant &&
6162 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6163 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6164 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6165 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6166 bool DoXform = true;
6167 SmallVector<SDNode*, 4> SetCCs;
6168 if (!N0.hasOneUse())
6169 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6172 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6173 LN0->getChain(), LN0->getBasePtr(),
6175 LN0->getMemOperand());
6176 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6177 Mask = Mask.zext(VT.getSizeInBits());
6179 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6180 ExtLoad, DAG.getConstant(Mask, DL, VT));
6181 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6182 SDLoc(N0.getOperand(0)),
6183 N0.getOperand(0).getValueType(), ExtLoad);
6185 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6186 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6188 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6193 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6194 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6195 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6196 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6197 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6198 EVT MemVT = LN0->getMemoryVT();
6199 if ((!LegalOperations && !LN0->isVolatile()) ||
6200 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6201 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6203 LN0->getBasePtr(), MemVT,
6204 LN0->getMemOperand());
6205 CombineTo(N, ExtLoad);
6206 CombineTo(N0.getNode(),
6207 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6209 ExtLoad.getValue(1));
6210 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6214 if (N0.getOpcode() == ISD::SETCC) {
6215 if (!LegalOperations && VT.isVector() &&
6216 N0.getValueType().getVectorElementType() == MVT::i1) {
6217 EVT N0VT = N0.getOperand(0).getValueType();
6218 if (getSetCCResultType(N0VT) == N0.getValueType())
6221 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6222 // Only do this before legalize for now.
6223 EVT EltVT = VT.getVectorElementType();
6225 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6226 DAG.getConstant(1, DL, EltVT));
6227 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6228 // We know that the # elements of the results is the same as the
6229 // # elements of the compare (and the # elements of the compare result
6230 // for that matter). Check to see that they are the same size. If so,
6231 // we know that the element size of the sext'd result matches the
6232 // element size of the compare operands.
6233 return DAG.getNode(ISD::AND, DL, VT,
6234 DAG.getSetCC(DL, VT, N0.getOperand(0),
6236 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6237 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6240 // If the desired elements are smaller or larger than the source
6241 // elements we can use a matching integer vector type and then
6242 // truncate/sign extend
6243 EVT MatchingElementType =
6244 EVT::getIntegerVT(*DAG.getContext(),
6245 N0VT.getScalarType().getSizeInBits());
6246 EVT MatchingVectorType =
6247 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6248 N0VT.getVectorNumElements());
6250 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6252 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6253 return DAG.getNode(ISD::AND, DL, VT,
6254 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6255 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6258 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6261 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6262 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6263 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6264 if (SCC.getNode()) return SCC;
6267 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6268 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6269 isa<ConstantSDNode>(N0.getOperand(1)) &&
6270 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6272 SDValue ShAmt = N0.getOperand(1);
6273 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6274 if (N0.getOpcode() == ISD::SHL) {
6275 SDValue InnerZExt = N0.getOperand(0);
6276 // If the original shl may be shifting out bits, do not perform this
6278 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6279 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6280 if (ShAmtVal > KnownZeroBits)
6286 // Ensure that the shift amount is wide enough for the shifted value.
6287 if (VT.getSizeInBits() >= 256)
6288 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6290 return DAG.getNode(N0.getOpcode(), DL, VT,
6291 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6298 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6299 SDValue N0 = N->getOperand(0);
6300 EVT VT = N->getValueType(0);
6302 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6304 return SDValue(Res, 0);
6306 // fold (aext (aext x)) -> (aext x)
6307 // fold (aext (zext x)) -> (zext x)
6308 // fold (aext (sext x)) -> (sext x)
6309 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6310 N0.getOpcode() == ISD::ZERO_EXTEND ||
6311 N0.getOpcode() == ISD::SIGN_EXTEND)
6312 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6314 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6315 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6316 if (N0.getOpcode() == ISD::TRUNCATE) {
6317 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6318 if (NarrowLoad.getNode()) {
6319 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6320 if (NarrowLoad.getNode() != N0.getNode()) {
6321 CombineTo(N0.getNode(), NarrowLoad);
6322 // CombineTo deleted the truncate, if needed, but not what's under it.
6325 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6329 // fold (aext (truncate x))
6330 if (N0.getOpcode() == ISD::TRUNCATE) {
6331 SDValue TruncOp = N0.getOperand(0);
6332 if (TruncOp.getValueType() == VT)
6333 return TruncOp; // x iff x size == zext size.
6334 if (TruncOp.getValueType().bitsGT(VT))
6335 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6336 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6339 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6340 // if the trunc is not free.
6341 if (N0.getOpcode() == ISD::AND &&
6342 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6343 N0.getOperand(1).getOpcode() == ISD::Constant &&
6344 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6345 N0.getValueType())) {
6346 SDValue X = N0.getOperand(0).getOperand(0);
6347 if (X.getValueType().bitsLT(VT)) {
6348 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6349 } else if (X.getValueType().bitsGT(VT)) {
6350 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6352 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6353 Mask = Mask.zext(VT.getSizeInBits());
6355 return DAG.getNode(ISD::AND, DL, VT,
6356 X, DAG.getConstant(Mask, DL, VT));
6359 // fold (aext (load x)) -> (aext (truncate (extload x)))
6360 // None of the supported targets knows how to perform load and any_ext
6361 // on vectors in one instruction. We only perform this transformation on
6363 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6364 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6365 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6366 bool DoXform = true;
6367 SmallVector<SDNode*, 4> SetCCs;
6368 if (!N0.hasOneUse())
6369 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6371 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6372 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6374 LN0->getBasePtr(), N0.getValueType(),
6375 LN0->getMemOperand());
6376 CombineTo(N, ExtLoad);
6377 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6378 N0.getValueType(), ExtLoad);
6379 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6380 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6382 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6386 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6387 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6388 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6389 if (N0.getOpcode() == ISD::LOAD &&
6390 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6392 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6393 ISD::LoadExtType ExtType = LN0->getExtensionType();
6394 EVT MemVT = LN0->getMemoryVT();
6395 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6396 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6397 VT, LN0->getChain(), LN0->getBasePtr(),
6398 MemVT, LN0->getMemOperand());
6399 CombineTo(N, ExtLoad);
6400 CombineTo(N0.getNode(),
6401 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6402 N0.getValueType(), ExtLoad),
6403 ExtLoad.getValue(1));
6404 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6408 if (N0.getOpcode() == ISD::SETCC) {
6410 // aext(setcc) -> vsetcc
6411 // aext(setcc) -> truncate(vsetcc)
6412 // aext(setcc) -> aext(vsetcc)
6413 // Only do this before legalize for now.
6414 if (VT.isVector() && !LegalOperations) {
6415 EVT N0VT = N0.getOperand(0).getValueType();
6416 // We know that the # elements of the results is the same as the
6417 // # elements of the compare (and the # elements of the compare result
6418 // for that matter). Check to see that they are the same size. If so,
6419 // we know that the element size of the sext'd result matches the
6420 // element size of the compare operands.
6421 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6422 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6424 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6425 // If the desired elements are smaller or larger than the source
6426 // elements we can use a matching integer vector type and then
6427 // truncate/any extend
6429 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6431 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6433 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6434 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6438 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6441 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6442 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6443 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6451 /// See if the specified operand can be simplified with the knowledge that only
6452 /// the bits specified by Mask are used. If so, return the simpler operand,
6453 /// otherwise return a null SDValue.
6454 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6455 switch (V.getOpcode()) {
6457 case ISD::Constant: {
6458 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6459 assert(CV && "Const value should be ConstSDNode.");
6460 const APInt &CVal = CV->getAPIntValue();
6461 APInt NewVal = CVal & Mask;
6463 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6468 // If the LHS or RHS don't contribute bits to the or, drop them.
6469 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6470 return V.getOperand(1);
6471 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6472 return V.getOperand(0);
6475 // Only look at single-use SRLs.
6476 if (!V.getNode()->hasOneUse())
6478 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6479 // See if we can recursively simplify the LHS.
6480 unsigned Amt = RHSC->getZExtValue();
6482 // Watch out for shift count overflow though.
6483 if (Amt >= Mask.getBitWidth()) break;
6484 APInt NewMask = Mask << Amt;
6485 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6486 if (SimplifyLHS.getNode())
6487 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6488 SimplifyLHS, V.getOperand(1));
6494 /// If the result of a wider load is shifted to right of N bits and then
6495 /// truncated to a narrower type and where N is a multiple of number of bits of
6496 /// the narrower type, transform it to a narrower load from address + N / num of
6497 /// bits of new type. If the result is to be extended, also fold the extension
6498 /// to form a extending load.
6499 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6500 unsigned Opc = N->getOpcode();
6502 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6503 SDValue N0 = N->getOperand(0);
6504 EVT VT = N->getValueType(0);
6507 // This transformation isn't valid for vector loads.
6511 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6513 if (Opc == ISD::SIGN_EXTEND_INREG) {
6514 ExtType = ISD::SEXTLOAD;
6515 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6516 } else if (Opc == ISD::SRL) {
6517 // Another special-case: SRL is basically zero-extending a narrower value.
6518 ExtType = ISD::ZEXTLOAD;
6520 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6521 if (!N01) return SDValue();
6522 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6523 VT.getSizeInBits() - N01->getZExtValue());
6525 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6528 unsigned EVTBits = ExtVT.getSizeInBits();
6530 // Do not generate loads of non-round integer types since these can
6531 // be expensive (and would be wrong if the type is not byte sized).
6532 if (!ExtVT.isRound())
6536 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6537 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6538 ShAmt = N01->getZExtValue();
6539 // Is the shift amount a multiple of size of VT?
6540 if ((ShAmt & (EVTBits-1)) == 0) {
6541 N0 = N0.getOperand(0);
6542 // Is the load width a multiple of size of VT?
6543 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6547 // At this point, we must have a load or else we can't do the transform.
6548 if (!isa<LoadSDNode>(N0)) return SDValue();
6550 // Because a SRL must be assumed to *need* to zero-extend the high bits
6551 // (as opposed to anyext the high bits), we can't combine the zextload
6552 // lowering of SRL and an sextload.
6553 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6556 // If the shift amount is larger than the input type then we're not
6557 // accessing any of the loaded bytes. If the load was a zextload/extload
6558 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6559 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6564 // If the load is shifted left (and the result isn't shifted back right),
6565 // we can fold the truncate through the shift.
6566 unsigned ShLeftAmt = 0;
6567 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6568 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6569 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6570 ShLeftAmt = N01->getZExtValue();
6571 N0 = N0.getOperand(0);
6575 // If we haven't found a load, we can't narrow it. Don't transform one with
6576 // multiple uses, this would require adding a new load.
6577 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6580 // Don't change the width of a volatile load.
6581 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6582 if (LN0->isVolatile())
6585 // Verify that we are actually reducing a load width here.
6586 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6589 // For the transform to be legal, the load must produce only two values
6590 // (the value loaded and the chain). Don't transform a pre-increment
6591 // load, for example, which produces an extra value. Otherwise the
6592 // transformation is not equivalent, and the downstream logic to replace
6593 // uses gets things wrong.
6594 if (LN0->getNumValues() > 2)
6597 // If the load that we're shrinking is an extload and we're not just
6598 // discarding the extension we can't simply shrink the load. Bail.
6599 // TODO: It would be possible to merge the extensions in some cases.
6600 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6601 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6604 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6607 EVT PtrType = N0.getOperand(1).getValueType();
6609 if (PtrType == MVT::Untyped || PtrType.isExtended())
6610 // It's not possible to generate a constant of extended or untyped type.
6613 // For big endian targets, we need to adjust the offset to the pointer to
6614 // load the correct bytes.
6615 if (TLI.isBigEndian()) {
6616 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6617 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6618 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6621 uint64_t PtrOff = ShAmt / 8;
6622 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6624 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6625 PtrType, LN0->getBasePtr(),
6626 DAG.getConstant(PtrOff, DL, PtrType));
6627 AddToWorklist(NewPtr.getNode());
6630 if (ExtType == ISD::NON_EXTLOAD)
6631 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6632 LN0->getPointerInfo().getWithOffset(PtrOff),
6633 LN0->isVolatile(), LN0->isNonTemporal(),
6634 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6636 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6637 LN0->getPointerInfo().getWithOffset(PtrOff),
6638 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6639 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6641 // Replace the old load's chain with the new load's chain.
6642 WorklistRemover DeadNodes(*this);
6643 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6645 // Shift the result left, if we've swallowed a left shift.
6646 SDValue Result = Load;
6647 if (ShLeftAmt != 0) {
6648 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6649 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6651 // If the shift amount is as large as the result size (but, presumably,
6652 // no larger than the source) then the useful bits of the result are
6653 // zero; we can't simply return the shortened shift, because the result
6654 // of that operation is undefined.
6656 if (ShLeftAmt >= VT.getSizeInBits())
6657 Result = DAG.getConstant(0, DL, VT);
6659 Result = DAG.getNode(ISD::SHL, DL, VT,
6660 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6663 // Return the new loaded value.
6667 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6668 SDValue N0 = N->getOperand(0);
6669 SDValue N1 = N->getOperand(1);
6670 EVT VT = N->getValueType(0);
6671 EVT EVT = cast<VTSDNode>(N1)->getVT();
6672 unsigned VTBits = VT.getScalarType().getSizeInBits();
6673 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6675 // fold (sext_in_reg c1) -> c1
6676 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6677 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6679 // If the input is already sign extended, just drop the extension.
6680 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6683 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6684 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6685 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6686 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6687 N0.getOperand(0), N1);
6689 // fold (sext_in_reg (sext x)) -> (sext x)
6690 // fold (sext_in_reg (aext x)) -> (sext x)
6691 // if x is small enough.
6692 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6693 SDValue N00 = N0.getOperand(0);
6694 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6695 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6696 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6699 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6700 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6701 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6703 // fold operands of sext_in_reg based on knowledge that the top bits are not
6705 if (SimplifyDemandedBits(SDValue(N, 0)))
6706 return SDValue(N, 0);
6708 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6709 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6710 SDValue NarrowLoad = ReduceLoadWidth(N);
6711 if (NarrowLoad.getNode())
6714 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6715 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6716 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6717 if (N0.getOpcode() == ISD::SRL) {
6718 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6719 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6720 // We can turn this into an SRA iff the input to the SRL is already sign
6722 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6723 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6724 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6725 N0.getOperand(0), N0.getOperand(1));
6729 // fold (sext_inreg (extload x)) -> (sextload x)
6730 if (ISD::isEXTLoad(N0.getNode()) &&
6731 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6732 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6733 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6734 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6735 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6736 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6738 LN0->getBasePtr(), EVT,
6739 LN0->getMemOperand());
6740 CombineTo(N, ExtLoad);
6741 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6742 AddToWorklist(ExtLoad.getNode());
6743 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6745 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6746 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6748 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6749 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6750 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6751 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6752 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6754 LN0->getBasePtr(), EVT,
6755 LN0->getMemOperand());
6756 CombineTo(N, ExtLoad);
6757 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6758 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6761 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6762 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6763 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6764 N0.getOperand(1), false);
6765 if (BSwap.getNode())
6766 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6770 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6771 // into a build_vector.
6772 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6773 SmallVector<SDValue, 8> Elts;
6774 unsigned NumElts = N0->getNumOperands();
6775 unsigned ShAmt = VTBits - EVTBits;
6777 for (unsigned i = 0; i != NumElts; ++i) {
6778 SDValue Op = N0->getOperand(i);
6779 if (Op->getOpcode() == ISD::UNDEF) {
6784 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6785 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6786 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6787 SDLoc(Op), Op.getValueType()));
6790 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6796 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6797 SDValue N0 = N->getOperand(0);
6798 EVT VT = N->getValueType(0);
6799 bool isLE = TLI.isLittleEndian();
6802 if (N0.getValueType() == N->getValueType(0))
6804 // fold (truncate c1) -> c1
6805 if (isConstantIntBuildVectorOrConstantInt(N0))
6806 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6807 // fold (truncate (truncate x)) -> (truncate x)
6808 if (N0.getOpcode() == ISD::TRUNCATE)
6809 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6810 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6811 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6812 N0.getOpcode() == ISD::SIGN_EXTEND ||
6813 N0.getOpcode() == ISD::ANY_EXTEND) {
6814 if (N0.getOperand(0).getValueType().bitsLT(VT))
6815 // if the source is smaller than the dest, we still need an extend
6816 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6818 if (N0.getOperand(0).getValueType().bitsGT(VT))
6819 // if the source is larger than the dest, than we just need the truncate
6820 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6821 // if the source and dest are the same type, we can drop both the extend
6822 // and the truncate.
6823 return N0.getOperand(0);
6826 // Fold extract-and-trunc into a narrow extract. For example:
6827 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6828 // i32 y = TRUNCATE(i64 x)
6830 // v16i8 b = BITCAST (v2i64 val)
6831 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6833 // Note: We only run this optimization after type legalization (which often
6834 // creates this pattern) and before operation legalization after which
6835 // we need to be more careful about the vector instructions that we generate.
6836 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6837 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6839 EVT VecTy = N0.getOperand(0).getValueType();
6840 EVT ExTy = N0.getValueType();
6841 EVT TrTy = N->getValueType(0);
6843 unsigned NumElem = VecTy.getVectorNumElements();
6844 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6846 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6847 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6849 SDValue EltNo = N0->getOperand(1);
6850 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6851 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6852 EVT IndexTy = TLI.getVectorIdxTy();
6853 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6855 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6856 NVT, N0.getOperand(0));
6859 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6861 DAG.getConstant(Index, DL, IndexTy));
6865 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6866 if (N0.getOpcode() == ISD::SELECT) {
6867 EVT SrcVT = N0.getValueType();
6868 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6869 TLI.isTruncateFree(SrcVT, VT)) {
6871 SDValue Cond = N0.getOperand(0);
6872 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6873 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6874 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6878 // Fold a series of buildvector, bitcast, and truncate if possible.
6880 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6881 // (2xi32 (buildvector x, y)).
6882 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6883 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6884 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6885 N0.getOperand(0).hasOneUse()) {
6887 SDValue BuildVect = N0.getOperand(0);
6888 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6889 EVT TruncVecEltTy = VT.getVectorElementType();
6891 // Check that the element types match.
6892 if (BuildVectEltTy == TruncVecEltTy) {
6893 // Now we only need to compute the offset of the truncated elements.
6894 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6895 unsigned TruncVecNumElts = VT.getVectorNumElements();
6896 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6898 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6899 "Invalid number of elements");
6901 SmallVector<SDValue, 8> Opnds;
6902 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6903 Opnds.push_back(BuildVect.getOperand(i));
6905 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6909 // See if we can simplify the input to this truncate through knowledge that
6910 // only the low bits are being used.
6911 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6912 // Currently we only perform this optimization on scalars because vectors
6913 // may have different active low bits.
6914 if (!VT.isVector()) {
6916 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6917 VT.getSizeInBits()));
6918 if (Shorter.getNode())
6919 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6921 // fold (truncate (load x)) -> (smaller load x)
6922 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6923 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6924 SDValue Reduced = ReduceLoadWidth(N);
6925 if (Reduced.getNode())
6927 // Handle the case where the load remains an extending load even
6928 // after truncation.
6929 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6930 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6931 if (!LN0->isVolatile() &&
6932 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6933 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6934 VT, LN0->getChain(), LN0->getBasePtr(),
6936 LN0->getMemOperand());
6937 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6942 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6943 // where ... are all 'undef'.
6944 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6945 SmallVector<EVT, 8> VTs;
6948 unsigned NumDefs = 0;
6950 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6951 SDValue X = N0.getOperand(i);
6952 if (X.getOpcode() != ISD::UNDEF) {
6957 // Stop if more than one members are non-undef.
6960 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6961 VT.getVectorElementType(),
6962 X.getValueType().getVectorNumElements()));
6966 return DAG.getUNDEF(VT);
6969 assert(V.getNode() && "The single defined operand is empty!");
6970 SmallVector<SDValue, 8> Opnds;
6971 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6973 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6976 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6977 AddToWorklist(NV.getNode());
6978 Opnds.push_back(NV);
6980 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6984 // Simplify the operands using demanded-bits information.
6985 if (!VT.isVector() &&
6986 SimplifyDemandedBits(SDValue(N, 0)))
6987 return SDValue(N, 0);
6992 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6993 SDValue Elt = N->getOperand(i);
6994 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6995 return Elt.getNode();
6996 return Elt.getOperand(Elt.getResNo()).getNode();
6999 /// build_pair (load, load) -> load
7000 /// if load locations are consecutive.
7001 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7002 assert(N->getOpcode() == ISD::BUILD_PAIR);
7004 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7005 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7006 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7007 LD1->getAddressSpace() != LD2->getAddressSpace())
7009 EVT LD1VT = LD1->getValueType(0);
7011 if (ISD::isNON_EXTLoad(LD2) &&
7013 // If both are volatile this would reduce the number of volatile loads.
7014 // If one is volatile it might be ok, but play conservative and bail out.
7015 !LD1->isVolatile() &&
7016 !LD2->isVolatile() &&
7017 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7018 unsigned Align = LD1->getAlignment();
7019 unsigned NewAlign = TLI.getDataLayout()->
7020 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7022 if (NewAlign <= Align &&
7023 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7024 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7025 LD1->getBasePtr(), LD1->getPointerInfo(),
7026 false, false, false, Align);
7032 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7033 SDValue N0 = N->getOperand(0);
7034 EVT VT = N->getValueType(0);
7036 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7037 // Only do this before legalize, since afterward the target may be depending
7038 // on the bitconvert.
7039 // First check to see if this is all constant.
7041 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7043 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7045 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7046 assert(!DestEltVT.isVector() &&
7047 "Element type of vector ValueType must not be vector!");
7049 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7052 // If the input is a constant, let getNode fold it.
7053 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7054 // If we can't allow illegal operations, we need to check that this is just
7055 // a fp -> int or int -> conversion and that the resulting operation will
7057 if (!LegalOperations ||
7058 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7059 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7060 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7061 TLI.isOperationLegal(ISD::Constant, VT)))
7062 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7065 // (conv (conv x, t1), t2) -> (conv x, t2)
7066 if (N0.getOpcode() == ISD::BITCAST)
7067 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7070 // fold (conv (load x)) -> (load (conv*)x)
7071 // If the resultant load doesn't need a higher alignment than the original!
7072 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7073 // Do not change the width of a volatile load.
7074 !cast<LoadSDNode>(N0)->isVolatile() &&
7075 // Do not remove the cast if the types differ in endian layout.
7076 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7077 TLI.hasBigEndianPartOrdering(VT) &&
7078 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7079 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7080 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7081 unsigned Align = TLI.getDataLayout()->
7082 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7083 unsigned OrigAlign = LN0->getAlignment();
7085 if (Align <= OrigAlign) {
7086 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7087 LN0->getBasePtr(), LN0->getPointerInfo(),
7088 LN0->isVolatile(), LN0->isNonTemporal(),
7089 LN0->isInvariant(), OrigAlign,
7091 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7096 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7097 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7098 // This often reduces constant pool loads.
7099 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7100 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7101 N0.getNode()->hasOneUse() && VT.isInteger() &&
7102 !VT.isVector() && !N0.getValueType().isVector()) {
7103 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7105 AddToWorklist(NewConv.getNode());
7108 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7109 if (N0.getOpcode() == ISD::FNEG)
7110 return DAG.getNode(ISD::XOR, DL, VT,
7111 NewConv, DAG.getConstant(SignBit, DL, VT));
7112 assert(N0.getOpcode() == ISD::FABS);
7113 return DAG.getNode(ISD::AND, DL, VT,
7114 NewConv, DAG.getConstant(~SignBit, DL, VT));
7117 // fold (bitconvert (fcopysign cst, x)) ->
7118 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7119 // Note that we don't handle (copysign x, cst) because this can always be
7120 // folded to an fneg or fabs.
7121 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7122 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7123 VT.isInteger() && !VT.isVector()) {
7124 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7125 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7126 if (isTypeLegal(IntXVT)) {
7127 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7128 IntXVT, N0.getOperand(1));
7129 AddToWorklist(X.getNode());
7131 // If X has a different width than the result/lhs, sext it or truncate it.
7132 unsigned VTWidth = VT.getSizeInBits();
7133 if (OrigXWidth < VTWidth) {
7134 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7135 AddToWorklist(X.getNode());
7136 } else if (OrigXWidth > VTWidth) {
7137 // To get the sign bit in the right place, we have to shift it right
7138 // before truncating.
7140 X = DAG.getNode(ISD::SRL, DL,
7141 X.getValueType(), X,
7142 DAG.getConstant(OrigXWidth-VTWidth, DL,
7144 AddToWorklist(X.getNode());
7145 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7146 AddToWorklist(X.getNode());
7149 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7150 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7151 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7152 AddToWorklist(X.getNode());
7154 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7155 VT, N0.getOperand(0));
7156 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7157 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7158 AddToWorklist(Cst.getNode());
7160 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7164 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7165 if (N0.getOpcode() == ISD::BUILD_PAIR) {
7166 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7167 if (CombineLD.getNode())
7171 // Remove double bitcasts from shuffles - this is often a legacy of
7172 // XformToShuffleWithZero being used to combine bitmaskings (of
7173 // float vectors bitcast to integer vectors) into shuffles.
7174 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7175 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7176 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7177 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7178 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7179 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7181 // If operands are a bitcast, peek through if it casts the original VT.
7182 // If operands are a UNDEF or constant, just bitcast back to original VT.
7183 auto PeekThroughBitcast = [&](SDValue Op) {
7184 if (Op.getOpcode() == ISD::BITCAST &&
7185 Op.getOperand(0)->getValueType(0) == VT)
7186 return SDValue(Op.getOperand(0));
7187 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7188 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7189 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7193 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7194 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7199 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7200 SmallVector<int, 8> NewMask;
7201 for (int M : SVN->getMask())
7202 for (int i = 0; i != MaskScale; ++i)
7203 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7205 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7207 std::swap(SV0, SV1);
7208 ShuffleVectorSDNode::commuteMask(NewMask);
7209 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7213 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7219 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7220 EVT VT = N->getValueType(0);
7221 return CombineConsecutiveLoads(N, VT);
7224 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7225 /// operands. DstEltVT indicates the destination element value type.
7226 SDValue DAGCombiner::
7227 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7228 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7230 // If this is already the right type, we're done.
7231 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7233 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7234 unsigned DstBitSize = DstEltVT.getSizeInBits();
7236 // If this is a conversion of N elements of one type to N elements of another
7237 // type, convert each element. This handles FP<->INT cases.
7238 if (SrcBitSize == DstBitSize) {
7239 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7240 BV->getValueType(0).getVectorNumElements());
7242 // Due to the FP element handling below calling this routine recursively,
7243 // we can end up with a scalar-to-vector node here.
7244 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7245 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7246 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7247 DstEltVT, BV->getOperand(0)));
7249 SmallVector<SDValue, 8> Ops;
7250 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7251 SDValue Op = BV->getOperand(i);
7252 // If the vector element type is not legal, the BUILD_VECTOR operands
7253 // are promoted and implicitly truncated. Make that explicit here.
7254 if (Op.getValueType() != SrcEltVT)
7255 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7256 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7258 AddToWorklist(Ops.back().getNode());
7260 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7263 // Otherwise, we're growing or shrinking the elements. To avoid having to
7264 // handle annoying details of growing/shrinking FP values, we convert them to
7266 if (SrcEltVT.isFloatingPoint()) {
7267 // Convert the input float vector to a int vector where the elements are the
7269 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7270 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7274 // Now we know the input is an integer vector. If the output is a FP type,
7275 // convert to integer first, then to FP of the right size.
7276 if (DstEltVT.isFloatingPoint()) {
7277 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7278 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7280 // Next, convert to FP elements of the same size.
7281 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7286 // Okay, we know the src/dst types are both integers of differing types.
7287 // Handling growing first.
7288 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7289 if (SrcBitSize < DstBitSize) {
7290 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7292 SmallVector<SDValue, 8> Ops;
7293 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7294 i += NumInputsPerOutput) {
7295 bool isLE = TLI.isLittleEndian();
7296 APInt NewBits = APInt(DstBitSize, 0);
7297 bool EltIsUndef = true;
7298 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7299 // Shift the previously computed bits over.
7300 NewBits <<= SrcBitSize;
7301 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7302 if (Op.getOpcode() == ISD::UNDEF) continue;
7305 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7306 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7310 Ops.push_back(DAG.getUNDEF(DstEltVT));
7312 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7315 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7316 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7319 // Finally, this must be the case where we are shrinking elements: each input
7320 // turns into multiple outputs.
7321 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7322 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7323 NumOutputsPerInput*BV->getNumOperands());
7324 SmallVector<SDValue, 8> Ops;
7326 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7327 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7328 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7332 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7333 getAPIntValue().zextOrTrunc(SrcBitSize);
7335 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7336 APInt ThisVal = OpVal.trunc(DstBitSize);
7337 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7338 OpVal = OpVal.lshr(DstBitSize);
7341 // For big endian targets, swap the order of the pieces of each element.
7342 if (TLI.isBigEndian())
7343 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7346 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7349 /// Try to perform FMA combining on a given FADD node.
7350 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7351 SDValue N0 = N->getOperand(0);
7352 SDValue N1 = N->getOperand(1);
7353 EVT VT = N->getValueType(0);
7356 const TargetOptions &Options = DAG.getTarget().Options;
7357 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7358 Options.UnsafeFPMath);
7360 // Floating-point multiply-add with intermediate rounding.
7361 bool HasFMAD = (LegalOperations &&
7362 TLI.isOperationLegal(ISD::FMAD, VT));
7364 // Floating-point multiply-add without intermediate rounding.
7365 bool HasFMA = ((!LegalOperations ||
7366 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7367 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7370 // No valid opcode, do not combine.
7371 if (!HasFMAD && !HasFMA)
7374 // Always prefer FMAD to FMA for precision.
7375 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7376 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7377 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7379 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7380 if (N0.getOpcode() == ISD::FMUL &&
7381 (Aggressive || N0->hasOneUse())) {
7382 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7383 N0.getOperand(0), N0.getOperand(1), N1);
7386 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7387 // Note: Commutes FADD operands.
7388 if (N1.getOpcode() == ISD::FMUL &&
7389 (Aggressive || N1->hasOneUse())) {
7390 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7391 N1.getOperand(0), N1.getOperand(1), N0);
7394 // Look through FP_EXTEND nodes to do more combining.
7395 if (UnsafeFPMath && LookThroughFPExt) {
7396 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7397 if (N0.getOpcode() == ISD::FP_EXTEND) {
7398 SDValue N00 = N0.getOperand(0);
7399 if (N00.getOpcode() == ISD::FMUL)
7400 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7401 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7403 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7404 N00.getOperand(1)), N1);
7407 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7408 // Note: Commutes FADD operands.
7409 if (N1.getOpcode() == ISD::FP_EXTEND) {
7410 SDValue N10 = N1.getOperand(0);
7411 if (N10.getOpcode() == ISD::FMUL)
7412 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7413 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7415 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7416 N10.getOperand(1)), N0);
7420 // More folding opportunities when target permits.
7421 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7422 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7423 if (N0.getOpcode() == PreferredFusedOpcode &&
7424 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7425 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7426 N0.getOperand(0), N0.getOperand(1),
7427 DAG.getNode(PreferredFusedOpcode, SL, VT,
7428 N0.getOperand(2).getOperand(0),
7429 N0.getOperand(2).getOperand(1),
7433 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7434 if (N1->getOpcode() == PreferredFusedOpcode &&
7435 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7436 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7437 N1.getOperand(0), N1.getOperand(1),
7438 DAG.getNode(PreferredFusedOpcode, SL, VT,
7439 N1.getOperand(2).getOperand(0),
7440 N1.getOperand(2).getOperand(1),
7444 if (UnsafeFPMath && LookThroughFPExt) {
7445 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7446 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7447 auto FoldFAddFMAFPExtFMul = [&] (
7448 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7449 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7450 DAG.getNode(PreferredFusedOpcode, SL, VT,
7451 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7452 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7455 if (N0.getOpcode() == PreferredFusedOpcode) {
7456 SDValue N02 = N0.getOperand(2);
7457 if (N02.getOpcode() == ISD::FP_EXTEND) {
7458 SDValue N020 = N02.getOperand(0);
7459 if (N020.getOpcode() == ISD::FMUL)
7460 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7461 N020.getOperand(0), N020.getOperand(1),
7466 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7467 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7468 // FIXME: This turns two single-precision and one double-precision
7469 // operation into two double-precision operations, which might not be
7470 // interesting for all targets, especially GPUs.
7471 auto FoldFAddFPExtFMAFMul = [&] (
7472 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7473 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7474 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7475 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7476 DAG.getNode(PreferredFusedOpcode, SL, VT,
7477 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7478 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7481 if (N0.getOpcode() == ISD::FP_EXTEND) {
7482 SDValue N00 = N0.getOperand(0);
7483 if (N00.getOpcode() == PreferredFusedOpcode) {
7484 SDValue N002 = N00.getOperand(2);
7485 if (N002.getOpcode() == ISD::FMUL)
7486 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7487 N002.getOperand(0), N002.getOperand(1),
7492 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7493 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7494 if (N1.getOpcode() == PreferredFusedOpcode) {
7495 SDValue N12 = N1.getOperand(2);
7496 if (N12.getOpcode() == ISD::FP_EXTEND) {
7497 SDValue N120 = N12.getOperand(0);
7498 if (N120.getOpcode() == ISD::FMUL)
7499 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7500 N120.getOperand(0), N120.getOperand(1),
7505 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7506 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7507 // FIXME: This turns two single-precision and one double-precision
7508 // operation into two double-precision operations, which might not be
7509 // interesting for all targets, especially GPUs.
7510 if (N1.getOpcode() == ISD::FP_EXTEND) {
7511 SDValue N10 = N1.getOperand(0);
7512 if (N10.getOpcode() == PreferredFusedOpcode) {
7513 SDValue N102 = N10.getOperand(2);
7514 if (N102.getOpcode() == ISD::FMUL)
7515 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7516 N102.getOperand(0), N102.getOperand(1),
7526 /// Try to perform FMA combining on a given FSUB node.
7527 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7528 SDValue N0 = N->getOperand(0);
7529 SDValue N1 = N->getOperand(1);
7530 EVT VT = N->getValueType(0);
7533 const TargetOptions &Options = DAG.getTarget().Options;
7534 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7535 Options.UnsafeFPMath);
7537 // Floating-point multiply-add with intermediate rounding.
7538 bool HasFMAD = (LegalOperations &&
7539 TLI.isOperationLegal(ISD::FMAD, VT));
7541 // Floating-point multiply-add without intermediate rounding.
7542 bool HasFMA = ((!LegalOperations ||
7543 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7544 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7547 // No valid opcode, do not combine.
7548 if (!HasFMAD && !HasFMA)
7551 // Always prefer FMAD to FMA for precision.
7552 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7553 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7554 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7556 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7557 if (N0.getOpcode() == ISD::FMUL &&
7558 (Aggressive || N0->hasOneUse())) {
7559 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7560 N0.getOperand(0), N0.getOperand(1),
7561 DAG.getNode(ISD::FNEG, SL, VT, N1));
7564 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7565 // Note: Commutes FSUB operands.
7566 if (N1.getOpcode() == ISD::FMUL &&
7567 (Aggressive || N1->hasOneUse()))
7568 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7569 DAG.getNode(ISD::FNEG, SL, VT,
7571 N1.getOperand(1), N0);
7573 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7574 if (N0.getOpcode() == ISD::FNEG &&
7575 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7576 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7577 SDValue N00 = N0.getOperand(0).getOperand(0);
7578 SDValue N01 = N0.getOperand(0).getOperand(1);
7579 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7580 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7581 DAG.getNode(ISD::FNEG, SL, VT, N1));
7584 // Look through FP_EXTEND nodes to do more combining.
7585 if (UnsafeFPMath && LookThroughFPExt) {
7586 // fold (fsub (fpext (fmul x, y)), z)
7587 // -> (fma (fpext x), (fpext y), (fneg z))
7588 if (N0.getOpcode() == ISD::FP_EXTEND) {
7589 SDValue N00 = N0.getOperand(0);
7590 if (N00.getOpcode() == ISD::FMUL)
7591 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7592 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7594 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7596 DAG.getNode(ISD::FNEG, SL, VT, N1));
7599 // fold (fsub x, (fpext (fmul y, z)))
7600 // -> (fma (fneg (fpext y)), (fpext z), x)
7601 // Note: Commutes FSUB operands.
7602 if (N1.getOpcode() == ISD::FP_EXTEND) {
7603 SDValue N10 = N1.getOperand(0);
7604 if (N10.getOpcode() == ISD::FMUL)
7605 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7606 DAG.getNode(ISD::FNEG, SL, VT,
7607 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7608 N10.getOperand(0))),
7609 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7614 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7615 // -> (fneg (fma (fpext x), (fpext y), z))
7616 // Note: This could be removed with appropriate canonicalization of the
7617 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7618 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7619 // from implementing the canonicalization in visitFSUB.
7620 if (N0.getOpcode() == ISD::FP_EXTEND) {
7621 SDValue N00 = N0.getOperand(0);
7622 if (N00.getOpcode() == ISD::FNEG) {
7623 SDValue N000 = N00.getOperand(0);
7624 if (N000.getOpcode() == ISD::FMUL) {
7625 return DAG.getNode(ISD::FNEG, SL, VT,
7626 DAG.getNode(PreferredFusedOpcode, SL, VT,
7627 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7628 N000.getOperand(0)),
7629 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7630 N000.getOperand(1)),
7636 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7637 // -> (fneg (fma (fpext x)), (fpext y), z)
7638 // Note: This could be removed with appropriate canonicalization of the
7639 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7640 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7641 // from implementing the canonicalization in visitFSUB.
7642 if (N0.getOpcode() == ISD::FNEG) {
7643 SDValue N00 = N0.getOperand(0);
7644 if (N00.getOpcode() == ISD::FP_EXTEND) {
7645 SDValue N000 = N00.getOperand(0);
7646 if (N000.getOpcode() == ISD::FMUL) {
7647 return DAG.getNode(ISD::FNEG, SL, VT,
7648 DAG.getNode(PreferredFusedOpcode, SL, VT,
7649 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7650 N000.getOperand(0)),
7651 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7652 N000.getOperand(1)),
7660 // More folding opportunities when target permits.
7661 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7662 // fold (fsub (fma x, y, (fmul u, v)), z)
7663 // -> (fma x, y (fma u, v, (fneg z)))
7664 if (N0.getOpcode() == PreferredFusedOpcode &&
7665 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7666 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7667 N0.getOperand(0), N0.getOperand(1),
7668 DAG.getNode(PreferredFusedOpcode, SL, VT,
7669 N0.getOperand(2).getOperand(0),
7670 N0.getOperand(2).getOperand(1),
7671 DAG.getNode(ISD::FNEG, SL, VT,
7675 // fold (fsub x, (fma y, z, (fmul u, v)))
7676 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7677 if (N1.getOpcode() == PreferredFusedOpcode &&
7678 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7679 SDValue N20 = N1.getOperand(2).getOperand(0);
7680 SDValue N21 = N1.getOperand(2).getOperand(1);
7681 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7682 DAG.getNode(ISD::FNEG, SL, VT,
7685 DAG.getNode(PreferredFusedOpcode, SL, VT,
7686 DAG.getNode(ISD::FNEG, SL, VT, N20),
7691 if (UnsafeFPMath && LookThroughFPExt) {
7692 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7693 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7694 if (N0.getOpcode() == PreferredFusedOpcode) {
7695 SDValue N02 = N0.getOperand(2);
7696 if (N02.getOpcode() == ISD::FP_EXTEND) {
7697 SDValue N020 = N02.getOperand(0);
7698 if (N020.getOpcode() == ISD::FMUL)
7699 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7700 N0.getOperand(0), N0.getOperand(1),
7701 DAG.getNode(PreferredFusedOpcode, SL, VT,
7702 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7703 N020.getOperand(0)),
7704 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7705 N020.getOperand(1)),
7706 DAG.getNode(ISD::FNEG, SL, VT,
7711 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7712 // -> (fma (fpext x), (fpext y),
7713 // (fma (fpext u), (fpext v), (fneg z)))
7714 // FIXME: This turns two single-precision and one double-precision
7715 // operation into two double-precision operations, which might not be
7716 // interesting for all targets, especially GPUs.
7717 if (N0.getOpcode() == ISD::FP_EXTEND) {
7718 SDValue N00 = N0.getOperand(0);
7719 if (N00.getOpcode() == PreferredFusedOpcode) {
7720 SDValue N002 = N00.getOperand(2);
7721 if (N002.getOpcode() == ISD::FMUL)
7722 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7723 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7725 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7727 DAG.getNode(PreferredFusedOpcode, SL, VT,
7728 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7729 N002.getOperand(0)),
7730 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7731 N002.getOperand(1)),
7732 DAG.getNode(ISD::FNEG, SL, VT,
7737 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7738 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7739 if (N1.getOpcode() == PreferredFusedOpcode &&
7740 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7741 SDValue N120 = N1.getOperand(2).getOperand(0);
7742 if (N120.getOpcode() == ISD::FMUL) {
7743 SDValue N1200 = N120.getOperand(0);
7744 SDValue N1201 = N120.getOperand(1);
7745 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7746 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7748 DAG.getNode(PreferredFusedOpcode, SL, VT,
7749 DAG.getNode(ISD::FNEG, SL, VT,
7750 DAG.getNode(ISD::FP_EXTEND, SL,
7752 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7758 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7759 // -> (fma (fneg (fpext y)), (fpext z),
7760 // (fma (fneg (fpext u)), (fpext v), x))
7761 // FIXME: This turns two single-precision and one double-precision
7762 // operation into two double-precision operations, which might not be
7763 // interesting for all targets, especially GPUs.
7764 if (N1.getOpcode() == ISD::FP_EXTEND &&
7765 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7766 SDValue N100 = N1.getOperand(0).getOperand(0);
7767 SDValue N101 = N1.getOperand(0).getOperand(1);
7768 SDValue N102 = N1.getOperand(0).getOperand(2);
7769 if (N102.getOpcode() == ISD::FMUL) {
7770 SDValue N1020 = N102.getOperand(0);
7771 SDValue N1021 = N102.getOperand(1);
7772 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7773 DAG.getNode(ISD::FNEG, SL, VT,
7774 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7776 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7777 DAG.getNode(PreferredFusedOpcode, SL, VT,
7778 DAG.getNode(ISD::FNEG, SL, VT,
7779 DAG.getNode(ISD::FP_EXTEND, SL,
7781 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7792 SDValue DAGCombiner::visitFADD(SDNode *N) {
7793 SDValue N0 = N->getOperand(0);
7794 SDValue N1 = N->getOperand(1);
7795 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7796 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7797 EVT VT = N->getValueType(0);
7799 const TargetOptions &Options = DAG.getTarget().Options;
7803 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7806 // fold (fadd c1, c2) -> c1 + c2
7808 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7810 // canonicalize constant to RHS
7811 if (N0CFP && !N1CFP)
7812 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7814 // fold (fadd A, (fneg B)) -> (fsub A, B)
7815 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7816 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7817 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7818 GetNegatedExpression(N1, DAG, LegalOperations));
7820 // fold (fadd (fneg A), B) -> (fsub B, A)
7821 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7822 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7823 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7824 GetNegatedExpression(N0, DAG, LegalOperations));
7826 // If 'unsafe math' is enabled, fold lots of things.
7827 if (Options.UnsafeFPMath) {
7828 // No FP constant should be created after legalization as Instruction
7829 // Selection pass has a hard time dealing with FP constants.
7830 bool AllowNewConst = (Level < AfterLegalizeDAG);
7832 // fold (fadd A, 0) -> A
7833 if (N1CFP && N1CFP->getValueAPF().isZero())
7836 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7837 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7838 isa<ConstantFPSDNode>(N0.getOperand(1)))
7839 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7840 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7842 // If allowed, fold (fadd (fneg x), x) -> 0.0
7843 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7844 return DAG.getConstantFP(0.0, DL, VT);
7846 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7847 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7848 return DAG.getConstantFP(0.0, DL, VT);
7850 // We can fold chains of FADD's of the same value into multiplications.
7851 // This transform is not safe in general because we are reducing the number
7852 // of rounding steps.
7853 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7854 if (N0.getOpcode() == ISD::FMUL) {
7855 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7856 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7858 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7859 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7860 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7861 DAG.getConstantFP(1.0, DL, VT));
7862 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7865 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7866 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7867 N1.getOperand(0) == N1.getOperand(1) &&
7868 N0.getOperand(0) == N1.getOperand(0)) {
7869 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7870 DAG.getConstantFP(2.0, DL, VT));
7871 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7875 if (N1.getOpcode() == ISD::FMUL) {
7876 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7877 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7879 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7880 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7881 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7882 DAG.getConstantFP(1.0, DL, VT));
7883 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7886 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7887 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7888 N0.getOperand(0) == N0.getOperand(1) &&
7889 N1.getOperand(0) == N0.getOperand(0)) {
7890 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7891 DAG.getConstantFP(2.0, DL, VT));
7892 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7896 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7897 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7898 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7899 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7900 (N0.getOperand(0) == N1)) {
7901 return DAG.getNode(ISD::FMUL, DL, VT,
7902 N1, DAG.getConstantFP(3.0, DL, VT));
7906 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7907 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7908 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7909 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7910 N1.getOperand(0) == N0) {
7911 return DAG.getNode(ISD::FMUL, DL, VT,
7912 N0, DAG.getConstantFP(3.0, DL, VT));
7916 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7917 if (AllowNewConst &&
7918 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7919 N0.getOperand(0) == N0.getOperand(1) &&
7920 N1.getOperand(0) == N1.getOperand(1) &&
7921 N0.getOperand(0) == N1.getOperand(0)) {
7922 return DAG.getNode(ISD::FMUL, DL, VT,
7923 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7926 } // enable-unsafe-fp-math
7928 // FADD -> FMA combines:
7929 SDValue Fused = visitFADDForFMACombine(N);
7931 AddToWorklist(Fused.getNode());
7938 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7939 SDValue N0 = N->getOperand(0);
7940 SDValue N1 = N->getOperand(1);
7941 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7942 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7943 EVT VT = N->getValueType(0);
7945 const TargetOptions &Options = DAG.getTarget().Options;
7949 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7952 // fold (fsub c1, c2) -> c1-c2
7954 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7956 // fold (fsub A, (fneg B)) -> (fadd A, B)
7957 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7958 return DAG.getNode(ISD::FADD, dl, VT, N0,
7959 GetNegatedExpression(N1, DAG, LegalOperations));
7961 // If 'unsafe math' is enabled, fold lots of things.
7962 if (Options.UnsafeFPMath) {
7964 if (N1CFP && N1CFP->getValueAPF().isZero())
7967 // (fsub 0, B) -> -B
7968 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7969 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7970 return GetNegatedExpression(N1, DAG, LegalOperations);
7971 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7972 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7975 // (fsub x, x) -> 0.0
7977 return DAG.getConstantFP(0.0f, dl, VT);
7979 // (fsub x, (fadd x, y)) -> (fneg y)
7980 // (fsub x, (fadd y, x)) -> (fneg y)
7981 if (N1.getOpcode() == ISD::FADD) {
7982 SDValue N10 = N1->getOperand(0);
7983 SDValue N11 = N1->getOperand(1);
7985 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7986 return GetNegatedExpression(N11, DAG, LegalOperations);
7988 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7989 return GetNegatedExpression(N10, DAG, LegalOperations);
7993 // FSUB -> FMA combines:
7994 SDValue Fused = visitFSUBForFMACombine(N);
7996 AddToWorklist(Fused.getNode());
8003 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8004 SDValue N0 = N->getOperand(0);
8005 SDValue N1 = N->getOperand(1);
8006 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8007 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8008 EVT VT = N->getValueType(0);
8010 const TargetOptions &Options = DAG.getTarget().Options;
8013 if (VT.isVector()) {
8014 // This just handles C1 * C2 for vectors. Other vector folds are below.
8015 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8019 // fold (fmul c1, c2) -> c1*c2
8021 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8023 // canonicalize constant to RHS
8024 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8025 !isConstantFPBuildVectorOrConstantFP(N1))
8026 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8028 // fold (fmul A, 1.0) -> A
8029 if (N1CFP && N1CFP->isExactlyValue(1.0))
8032 if (Options.UnsafeFPMath) {
8033 // fold (fmul A, 0) -> 0
8034 if (N1CFP && N1CFP->getValueAPF().isZero())
8037 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8038 if (N0.getOpcode() == ISD::FMUL) {
8039 // Fold scalars or any vector constants (not just splats).
8040 // This fold is done in general by InstCombine, but extra fmul insts
8041 // may have been generated during lowering.
8042 SDValue N00 = N0.getOperand(0);
8043 SDValue N01 = N0.getOperand(1);
8044 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8045 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8046 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8048 // Check 1: Make sure that the first operand of the inner multiply is NOT
8049 // a constant. Otherwise, we may induce infinite looping.
8050 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8051 // Check 2: Make sure that the second operand of the inner multiply and
8052 // the second operand of the outer multiply are constants.
8053 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8054 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8055 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8056 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8061 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8062 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8063 // during an early run of DAGCombiner can prevent folding with fmuls
8064 // inserted during lowering.
8065 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8066 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8067 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8068 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8072 // fold (fmul X, 2.0) -> (fadd X, X)
8073 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8074 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8076 // fold (fmul X, -1.0) -> (fneg X)
8077 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8078 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8079 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8081 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8082 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8083 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8084 // Both can be negated for free, check to see if at least one is cheaper
8086 if (LHSNeg == 2 || RHSNeg == 2)
8087 return DAG.getNode(ISD::FMUL, DL, VT,
8088 GetNegatedExpression(N0, DAG, LegalOperations),
8089 GetNegatedExpression(N1, DAG, LegalOperations));
8096 SDValue DAGCombiner::visitFMA(SDNode *N) {
8097 SDValue N0 = N->getOperand(0);
8098 SDValue N1 = N->getOperand(1);
8099 SDValue N2 = N->getOperand(2);
8100 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8101 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8102 EVT VT = N->getValueType(0);
8104 const TargetOptions &Options = DAG.getTarget().Options;
8106 // Constant fold FMA.
8107 if (isa<ConstantFPSDNode>(N0) &&
8108 isa<ConstantFPSDNode>(N1) &&
8109 isa<ConstantFPSDNode>(N2)) {
8110 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8113 if (Options.UnsafeFPMath) {
8114 if (N0CFP && N0CFP->isZero())
8116 if (N1CFP && N1CFP->isZero())
8119 if (N0CFP && N0CFP->isExactlyValue(1.0))
8120 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8121 if (N1CFP && N1CFP->isExactlyValue(1.0))
8122 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8124 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8125 if (N0CFP && !N1CFP)
8126 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8128 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8129 if (Options.UnsafeFPMath && N1CFP &&
8130 N2.getOpcode() == ISD::FMUL &&
8131 N0 == N2.getOperand(0) &&
8132 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8133 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8134 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8138 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8139 if (Options.UnsafeFPMath &&
8140 N0.getOpcode() == ISD::FMUL && N1CFP &&
8141 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8142 return DAG.getNode(ISD::FMA, dl, VT,
8144 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8148 // (fma x, 1, y) -> (fadd x, y)
8149 // (fma x, -1, y) -> (fadd (fneg x), y)
8151 if (N1CFP->isExactlyValue(1.0))
8152 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8154 if (N1CFP->isExactlyValue(-1.0) &&
8155 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8156 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8157 AddToWorklist(RHSNeg.getNode());
8158 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8162 // (fma x, c, x) -> (fmul x, (c+1))
8163 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8164 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8165 DAG.getNode(ISD::FADD, dl, VT,
8166 N1, DAG.getConstantFP(1.0, dl, VT)));
8168 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8169 if (Options.UnsafeFPMath && N1CFP &&
8170 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8171 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8172 DAG.getNode(ISD::FADD, dl, VT,
8173 N1, DAG.getConstantFP(-1.0, dl, VT)));
8179 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8180 SDValue N0 = N->getOperand(0);
8181 SDValue N1 = N->getOperand(1);
8182 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8183 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8184 EVT VT = N->getValueType(0);
8186 const TargetOptions &Options = DAG.getTarget().Options;
8190 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8193 // fold (fdiv c1, c2) -> c1/c2
8195 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8197 if (Options.UnsafeFPMath) {
8198 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8200 // Compute the reciprocal 1.0 / c2.
8201 APFloat N1APF = N1CFP->getValueAPF();
8202 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8203 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8204 // Only do the transform if the reciprocal is a legal fp immediate that
8205 // isn't too nasty (eg NaN, denormal, ...).
8206 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8207 (!LegalOperations ||
8208 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8209 // backend)... we should handle this gracefully after Legalize.
8210 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8211 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8212 TLI.isFPImmLegal(Recip, VT)))
8213 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8214 DAG.getConstantFP(Recip, DL, VT));
8217 // If this FDIV is part of a reciprocal square root, it may be folded
8218 // into a target-specific square root estimate instruction.
8219 if (N1.getOpcode() == ISD::FSQRT) {
8220 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8221 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8223 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8224 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8225 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8226 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8227 AddToWorklist(RV.getNode());
8228 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8230 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8231 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8232 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8233 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8234 AddToWorklist(RV.getNode());
8235 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8237 } else if (N1.getOpcode() == ISD::FMUL) {
8238 // Look through an FMUL. Even though this won't remove the FDIV directly,
8239 // it's still worthwhile to get rid of the FSQRT if possible.
8242 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8243 SqrtOp = N1.getOperand(0);
8244 OtherOp = N1.getOperand(1);
8245 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8246 SqrtOp = N1.getOperand(1);
8247 OtherOp = N1.getOperand(0);
8249 if (SqrtOp.getNode()) {
8250 // We found a FSQRT, so try to make this fold:
8251 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8252 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8253 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8254 AddToWorklist(RV.getNode());
8255 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8260 // Fold into a reciprocal estimate and multiply instead of a real divide.
8261 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8262 AddToWorklist(RV.getNode());
8263 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8267 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8268 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8269 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8270 // Both can be negated for free, check to see if at least one is cheaper
8272 if (LHSNeg == 2 || RHSNeg == 2)
8273 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8274 GetNegatedExpression(N0, DAG, LegalOperations),
8275 GetNegatedExpression(N1, DAG, LegalOperations));
8279 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8281 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8282 // Notice that this is not always beneficial. One reason is different target
8283 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8284 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8285 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8286 if (Options.UnsafeFPMath) {
8287 // Skip if current node is a reciprocal.
8288 if (N0CFP && N0CFP->isExactlyValue(1.0))
8291 SmallVector<SDNode *, 4> Users;
8292 // Find all FDIV users of the same divisor.
8293 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8294 UE = N1.getNode()->use_end();
8296 SDNode *User = UI.getUse().getUser();
8297 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8298 Users.push_back(User);
8301 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8303 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8304 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8306 // Dividend / Divisor -> Dividend * Reciprocal
8307 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8308 if ((*I)->getOperand(0) != FPOne) {
8309 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8310 (*I)->getOperand(0), Reciprocal);
8311 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8321 SDValue DAGCombiner::visitFREM(SDNode *N) {
8322 SDValue N0 = N->getOperand(0);
8323 SDValue N1 = N->getOperand(1);
8324 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8325 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8326 EVT VT = N->getValueType(0);
8328 // fold (frem c1, c2) -> fmod(c1,c2)
8330 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8335 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8336 if (DAG.getTarget().Options.UnsafeFPMath &&
8337 !TLI.isFsqrtCheap()) {
8338 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8339 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8340 EVT VT = RV.getValueType();
8342 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8343 AddToWorklist(RV.getNode());
8345 // Unfortunately, RV is now NaN if the input was exactly 0.
8346 // Select out this case and force the answer to 0.
8347 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8349 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8350 N->getOperand(0), Zero, ISD::SETEQ);
8351 AddToWorklist(ZeroCmp.getNode());
8352 AddToWorklist(RV.getNode());
8354 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8355 DL, VT, ZeroCmp, Zero, RV);
8362 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8363 SDValue N0 = N->getOperand(0);
8364 SDValue N1 = N->getOperand(1);
8365 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8366 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8367 EVT VT = N->getValueType(0);
8369 if (N0CFP && N1CFP) // Constant fold
8370 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8373 const APFloat& V = N1CFP->getValueAPF();
8374 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8375 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8376 if (!V.isNegative()) {
8377 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8378 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8380 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8381 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8382 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8386 // copysign(fabs(x), y) -> copysign(x, y)
8387 // copysign(fneg(x), y) -> copysign(x, y)
8388 // copysign(copysign(x,z), y) -> copysign(x, y)
8389 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8390 N0.getOpcode() == ISD::FCOPYSIGN)
8391 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8392 N0.getOperand(0), N1);
8394 // copysign(x, abs(y)) -> abs(x)
8395 if (N1.getOpcode() == ISD::FABS)
8396 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8398 // copysign(x, copysign(y,z)) -> copysign(x, z)
8399 if (N1.getOpcode() == ISD::FCOPYSIGN)
8400 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8401 N0, N1.getOperand(1));
8403 // copysign(x, fp_extend(y)) -> copysign(x, y)
8404 // copysign(x, fp_round(y)) -> copysign(x, y)
8405 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8406 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8407 N0, N1.getOperand(0));
8412 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8413 SDValue N0 = N->getOperand(0);
8414 EVT VT = N->getValueType(0);
8415 EVT OpVT = N0.getValueType();
8417 // fold (sint_to_fp c1) -> c1fp
8418 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8419 // ...but only if the target supports immediate floating-point values
8420 (!LegalOperations ||
8421 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8422 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8424 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8425 // but UINT_TO_FP is legal on this target, try to convert.
8426 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8427 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8428 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8429 if (DAG.SignBitIsZero(N0))
8430 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8433 // The next optimizations are desirable only if SELECT_CC can be lowered.
8434 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8435 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8436 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8438 (!LegalOperations ||
8439 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8442 { N0.getOperand(0), N0.getOperand(1),
8443 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8445 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8448 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8449 // (select_cc x, y, 1.0, 0.0,, cc)
8450 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8451 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8452 (!LegalOperations ||
8453 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8456 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8457 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8458 N0.getOperand(0).getOperand(2) };
8459 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8466 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8467 SDValue N0 = N->getOperand(0);
8468 EVT VT = N->getValueType(0);
8469 EVT OpVT = N0.getValueType();
8471 // fold (uint_to_fp c1) -> c1fp
8472 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8473 // ...but only if the target supports immediate floating-point values
8474 (!LegalOperations ||
8475 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8476 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8478 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8479 // but SINT_TO_FP is legal on this target, try to convert.
8480 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8481 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8482 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8483 if (DAG.SignBitIsZero(N0))
8484 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8487 // The next optimizations are desirable only if SELECT_CC can be lowered.
8488 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8489 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8491 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8492 (!LegalOperations ||
8493 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8496 { N0.getOperand(0), N0.getOperand(1),
8497 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8499 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8506 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8507 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8508 SDValue N0 = N->getOperand(0);
8509 EVT VT = N->getValueType(0);
8511 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8514 SDValue Src = N0.getOperand(0);
8515 EVT SrcVT = Src.getValueType();
8516 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8517 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8519 // We can safely assume the conversion won't overflow the output range,
8520 // because (for example) (uint8_t)18293.f is undefined behavior.
8522 // Since we can assume the conversion won't overflow, our decision as to
8523 // whether the input will fit in the float should depend on the minimum
8524 // of the input range and output range.
8526 // This means this is also safe for a signed input and unsigned output, since
8527 // a negative input would lead to undefined behavior.
8528 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8529 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8530 unsigned ActualSize = std::min(InputSize, OutputSize);
8531 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8533 // We can only fold away the float conversion if the input range can be
8534 // represented exactly in the float range.
8535 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8536 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8537 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8539 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8541 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8542 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8545 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8550 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8551 SDValue N0 = N->getOperand(0);
8552 EVT VT = N->getValueType(0);
8554 // fold (fp_to_sint c1fp) -> c1
8555 if (isConstantFPBuildVectorOrConstantFP(N0))
8556 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8558 return FoldIntToFPToInt(N, DAG);
8561 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8562 SDValue N0 = N->getOperand(0);
8563 EVT VT = N->getValueType(0);
8565 // fold (fp_to_uint c1fp) -> c1
8566 if (isConstantFPBuildVectorOrConstantFP(N0))
8567 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8569 return FoldIntToFPToInt(N, DAG);
8572 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8573 SDValue N0 = N->getOperand(0);
8574 SDValue N1 = N->getOperand(1);
8575 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8576 EVT VT = N->getValueType(0);
8578 // fold (fp_round c1fp) -> c1fp
8580 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8582 // fold (fp_round (fp_extend x)) -> x
8583 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8584 return N0.getOperand(0);
8586 // fold (fp_round (fp_round x)) -> (fp_round x)
8587 if (N0.getOpcode() == ISD::FP_ROUND) {
8588 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8589 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8590 // If the first fp_round isn't a value preserving truncation, it might
8591 // introduce a tie in the second fp_round, that wouldn't occur in the
8592 // single-step fp_round we want to fold to.
8593 // In other words, double rounding isn't the same as rounding.
8594 // Also, this is a value preserving truncation iff both fp_round's are.
8595 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8597 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8598 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8602 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8603 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8604 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8605 N0.getOperand(0), N1);
8606 AddToWorklist(Tmp.getNode());
8607 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8608 Tmp, N0.getOperand(1));
8614 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8615 SDValue N0 = N->getOperand(0);
8616 EVT VT = N->getValueType(0);
8617 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8618 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8620 // fold (fp_round_inreg c1fp) -> c1fp
8621 if (N0CFP && isTypeLegal(EVT)) {
8623 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8624 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8630 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8631 SDValue N0 = N->getOperand(0);
8632 EVT VT = N->getValueType(0);
8634 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8635 if (N->hasOneUse() &&
8636 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8639 // fold (fp_extend c1fp) -> c1fp
8640 if (isConstantFPBuildVectorOrConstantFP(N0))
8641 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8643 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8644 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8645 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8646 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8648 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8650 if (N0.getOpcode() == ISD::FP_ROUND
8651 && N0.getNode()->getConstantOperandVal(1) == 1) {
8652 SDValue In = N0.getOperand(0);
8653 if (In.getValueType() == VT) return In;
8654 if (VT.bitsLT(In.getValueType()))
8655 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8656 In, N0.getOperand(1));
8657 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8660 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8661 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8662 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8663 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8664 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8666 LN0->getBasePtr(), N0.getValueType(),
8667 LN0->getMemOperand());
8668 CombineTo(N, ExtLoad);
8669 CombineTo(N0.getNode(),
8670 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8671 N0.getValueType(), ExtLoad,
8672 DAG.getIntPtrConstant(1, SDLoc(N0))),
8673 ExtLoad.getValue(1));
8674 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8680 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8681 SDValue N0 = N->getOperand(0);
8682 EVT VT = N->getValueType(0);
8684 // fold (fceil c1) -> fceil(c1)
8685 if (isConstantFPBuildVectorOrConstantFP(N0))
8686 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8691 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8692 SDValue N0 = N->getOperand(0);
8693 EVT VT = N->getValueType(0);
8695 // fold (ftrunc c1) -> ftrunc(c1)
8696 if (isConstantFPBuildVectorOrConstantFP(N0))
8697 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8702 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8703 SDValue N0 = N->getOperand(0);
8704 EVT VT = N->getValueType(0);
8706 // fold (ffloor c1) -> ffloor(c1)
8707 if (isConstantFPBuildVectorOrConstantFP(N0))
8708 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8713 // FIXME: FNEG and FABS have a lot in common; refactor.
8714 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8715 SDValue N0 = N->getOperand(0);
8716 EVT VT = N->getValueType(0);
8718 // Constant fold FNEG.
8719 if (isConstantFPBuildVectorOrConstantFP(N0))
8720 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8722 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8723 &DAG.getTarget().Options))
8724 return GetNegatedExpression(N0, DAG, LegalOperations);
8726 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8727 // constant pool values.
8728 if (!TLI.isFNegFree(VT) &&
8729 N0.getOpcode() == ISD::BITCAST &&
8730 N0.getNode()->hasOneUse()) {
8731 SDValue Int = N0.getOperand(0);
8732 EVT IntVT = Int.getValueType();
8733 if (IntVT.isInteger() && !IntVT.isVector()) {
8735 if (N0.getValueType().isVector()) {
8736 // For a vector, get a mask such as 0x80... per scalar element
8738 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8739 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8741 // For a scalar, just generate 0x80...
8742 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8745 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8746 DAG.getConstant(SignMask, DL0, IntVT));
8747 AddToWorklist(Int.getNode());
8748 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8752 // (fneg (fmul c, x)) -> (fmul -c, x)
8753 if (N0.getOpcode() == ISD::FMUL) {
8754 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8756 APFloat CVal = CFP1->getValueAPF();
8758 if (Level >= AfterLegalizeDAG &&
8759 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8760 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8762 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8763 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8770 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8771 SDValue N0 = N->getOperand(0);
8772 SDValue N1 = N->getOperand(1);
8773 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8774 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8776 if (N0CFP && N1CFP) {
8777 const APFloat &C0 = N0CFP->getValueAPF();
8778 const APFloat &C1 = N1CFP->getValueAPF();
8779 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8783 EVT VT = N->getValueType(0);
8784 // Canonicalize to constant on RHS.
8785 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8791 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8792 SDValue N0 = N->getOperand(0);
8793 SDValue N1 = N->getOperand(1);
8794 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8795 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8797 if (N0CFP && N1CFP) {
8798 const APFloat &C0 = N0CFP->getValueAPF();
8799 const APFloat &C1 = N1CFP->getValueAPF();
8800 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8804 EVT VT = N->getValueType(0);
8805 // Canonicalize to constant on RHS.
8806 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8812 SDValue DAGCombiner::visitFABS(SDNode *N) {
8813 SDValue N0 = N->getOperand(0);
8814 EVT VT = N->getValueType(0);
8816 // fold (fabs c1) -> fabs(c1)
8817 if (isConstantFPBuildVectorOrConstantFP(N0))
8818 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8820 // fold (fabs (fabs x)) -> (fabs x)
8821 if (N0.getOpcode() == ISD::FABS)
8822 return N->getOperand(0);
8824 // fold (fabs (fneg x)) -> (fabs x)
8825 // fold (fabs (fcopysign x, y)) -> (fabs x)
8826 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8827 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8829 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8830 // constant pool values.
8831 if (!TLI.isFAbsFree(VT) &&
8832 N0.getOpcode() == ISD::BITCAST &&
8833 N0.getNode()->hasOneUse()) {
8834 SDValue Int = N0.getOperand(0);
8835 EVT IntVT = Int.getValueType();
8836 if (IntVT.isInteger() && !IntVT.isVector()) {
8838 if (N0.getValueType().isVector()) {
8839 // For a vector, get a mask such as 0x7f... per scalar element
8841 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8842 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8844 // For a scalar, just generate 0x7f...
8845 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8848 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8849 DAG.getConstant(SignMask, DL, IntVT));
8850 AddToWorklist(Int.getNode());
8851 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8858 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8859 SDValue Chain = N->getOperand(0);
8860 SDValue N1 = N->getOperand(1);
8861 SDValue N2 = N->getOperand(2);
8863 // If N is a constant we could fold this into a fallthrough or unconditional
8864 // branch. However that doesn't happen very often in normal code, because
8865 // Instcombine/SimplifyCFG should have handled the available opportunities.
8866 // If we did this folding here, it would be necessary to update the
8867 // MachineBasicBlock CFG, which is awkward.
8869 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8871 if (N1.getOpcode() == ISD::SETCC &&
8872 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8873 N1.getOperand(0).getValueType())) {
8874 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8875 Chain, N1.getOperand(2),
8876 N1.getOperand(0), N1.getOperand(1), N2);
8879 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8880 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8881 (N1.getOperand(0).hasOneUse() &&
8882 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8883 SDNode *Trunc = nullptr;
8884 if (N1.getOpcode() == ISD::TRUNCATE) {
8885 // Look pass the truncate.
8886 Trunc = N1.getNode();
8887 N1 = N1.getOperand(0);
8890 // Match this pattern so that we can generate simpler code:
8893 // %b = and i32 %a, 2
8894 // %c = srl i32 %b, 1
8895 // brcond i32 %c ...
8900 // %b = and i32 %a, 2
8901 // %c = setcc eq %b, 0
8904 // This applies only when the AND constant value has one bit set and the
8905 // SRL constant is equal to the log2 of the AND constant. The back-end is
8906 // smart enough to convert the result into a TEST/JMP sequence.
8907 SDValue Op0 = N1.getOperand(0);
8908 SDValue Op1 = N1.getOperand(1);
8910 if (Op0.getOpcode() == ISD::AND &&
8911 Op1.getOpcode() == ISD::Constant) {
8912 SDValue AndOp1 = Op0.getOperand(1);
8914 if (AndOp1.getOpcode() == ISD::Constant) {
8915 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8917 if (AndConst.isPowerOf2() &&
8918 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8922 getSetCCResultType(Op0.getValueType()),
8923 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8926 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8927 MVT::Other, Chain, SetCC, N2);
8928 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8929 // will convert it back to (X & C1) >> C2.
8930 CombineTo(N, NewBRCond, false);
8931 // Truncate is dead.
8933 deleteAndRecombine(Trunc);
8934 // Replace the uses of SRL with SETCC
8935 WorklistRemover DeadNodes(*this);
8936 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8937 deleteAndRecombine(N1.getNode());
8938 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8944 // Restore N1 if the above transformation doesn't match.
8945 N1 = N->getOperand(1);
8948 // Transform br(xor(x, y)) -> br(x != y)
8949 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8950 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8951 SDNode *TheXor = N1.getNode();
8952 SDValue Op0 = TheXor->getOperand(0);
8953 SDValue Op1 = TheXor->getOperand(1);
8954 if (Op0.getOpcode() == Op1.getOpcode()) {
8955 // Avoid missing important xor optimizations.
8956 SDValue Tmp = visitXOR(TheXor);
8957 if (Tmp.getNode()) {
8958 if (Tmp.getNode() != TheXor) {
8959 DEBUG(dbgs() << "\nReplacing.8 ";
8961 dbgs() << "\nWith: ";
8962 Tmp.getNode()->dump(&DAG);
8964 WorklistRemover DeadNodes(*this);
8965 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8966 deleteAndRecombine(TheXor);
8967 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8968 MVT::Other, Chain, Tmp, N2);
8971 // visitXOR has changed XOR's operands or replaced the XOR completely,
8973 return SDValue(N, 0);
8977 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8979 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8980 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8981 Op0.getOpcode() == ISD::XOR) {
8982 TheXor = Op0.getNode();
8986 EVT SetCCVT = N1.getValueType();
8988 SetCCVT = getSetCCResultType(SetCCVT);
8989 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8992 Equal ? ISD::SETEQ : ISD::SETNE);
8993 // Replace the uses of XOR with SETCC
8994 WorklistRemover DeadNodes(*this);
8995 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8996 deleteAndRecombine(N1.getNode());
8997 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8998 MVT::Other, Chain, SetCC, N2);
9005 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9007 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9008 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9009 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9011 // If N is a constant we could fold this into a fallthrough or unconditional
9012 // branch. However that doesn't happen very often in normal code, because
9013 // Instcombine/SimplifyCFG should have handled the available opportunities.
9014 // If we did this folding here, it would be necessary to update the
9015 // MachineBasicBlock CFG, which is awkward.
9017 // Use SimplifySetCC to simplify SETCC's.
9018 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9019 CondLHS, CondRHS, CC->get(), SDLoc(N),
9021 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9023 // fold to a simpler setcc
9024 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9025 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9026 N->getOperand(0), Simp.getOperand(2),
9027 Simp.getOperand(0), Simp.getOperand(1),
9033 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9034 /// and that N may be folded in the load / store addressing mode.
9035 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9037 const TargetLowering &TLI) {
9039 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9040 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9042 VT = LD->getMemoryVT();
9043 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9044 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9046 VT = ST->getMemoryVT();
9050 TargetLowering::AddrMode AM;
9051 if (N->getOpcode() == ISD::ADD) {
9052 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9055 AM.BaseOffs = Offset->getSExtValue();
9059 } else if (N->getOpcode() == ISD::SUB) {
9060 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9063 AM.BaseOffs = -Offset->getSExtValue();
9070 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9073 /// Try turning a load/store into a pre-indexed load/store when the base
9074 /// pointer is an add or subtract and it has other uses besides the load/store.
9075 /// After the transformation, the new indexed load/store has effectively folded
9076 /// the add/subtract in and all of its other uses are redirected to the
9078 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9079 if (Level < AfterLegalizeDAG)
9085 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9086 if (LD->isIndexed())
9088 VT = LD->getMemoryVT();
9089 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9090 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9092 Ptr = LD->getBasePtr();
9093 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9094 if (ST->isIndexed())
9096 VT = ST->getMemoryVT();
9097 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9098 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9100 Ptr = ST->getBasePtr();
9106 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9107 // out. There is no reason to make this a preinc/predec.
9108 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9109 Ptr.getNode()->hasOneUse())
9112 // Ask the target to do addressing mode selection.
9115 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9116 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9119 // Backends without true r+i pre-indexed forms may need to pass a
9120 // constant base with a variable offset so that constant coercion
9121 // will work with the patterns in canonical form.
9122 bool Swapped = false;
9123 if (isa<ConstantSDNode>(BasePtr)) {
9124 std::swap(BasePtr, Offset);
9128 // Don't create a indexed load / store with zero offset.
9129 if (isa<ConstantSDNode>(Offset) &&
9130 cast<ConstantSDNode>(Offset)->isNullValue())
9133 // Try turning it into a pre-indexed load / store except when:
9134 // 1) The new base ptr is a frame index.
9135 // 2) If N is a store and the new base ptr is either the same as or is a
9136 // predecessor of the value being stored.
9137 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9138 // that would create a cycle.
9139 // 4) All uses are load / store ops that use it as old base ptr.
9141 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9142 // (plus the implicit offset) to a register to preinc anyway.
9143 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9148 SDValue Val = cast<StoreSDNode>(N)->getValue();
9149 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9153 // If the offset is a constant, there may be other adds of constants that
9154 // can be folded with this one. We should do this to avoid having to keep
9155 // a copy of the original base pointer.
9156 SmallVector<SDNode *, 16> OtherUses;
9157 if (isa<ConstantSDNode>(Offset))
9158 for (SDNode *Use : BasePtr.getNode()->uses()) {
9159 if (Use == Ptr.getNode())
9162 if (Use->isPredecessorOf(N))
9165 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
9170 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
9171 if (Op1.getNode() == BasePtr.getNode())
9172 std::swap(Op0, Op1);
9173 assert(Op0.getNode() == BasePtr.getNode() &&
9174 "Use of ADD/SUB but not an operand");
9176 if (!isa<ConstantSDNode>(Op1)) {
9181 // FIXME: In some cases, we can be smarter about this.
9182 if (Op1.getValueType() != Offset.getValueType()) {
9187 OtherUses.push_back(Use);
9191 std::swap(BasePtr, Offset);
9193 // Now check for #3 and #4.
9194 bool RealUse = false;
9196 // Caches for hasPredecessorHelper
9197 SmallPtrSet<const SDNode *, 32> Visited;
9198 SmallVector<const SDNode *, 16> Worklist;
9200 for (SDNode *Use : Ptr.getNode()->uses()) {
9203 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9206 // If Ptr may be folded in addressing mode of other use, then it's
9207 // not profitable to do this transformation.
9208 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9217 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9218 BasePtr, Offset, AM);
9220 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9221 BasePtr, Offset, AM);
9224 DEBUG(dbgs() << "\nReplacing.4 ";
9226 dbgs() << "\nWith: ";
9227 Result.getNode()->dump(&DAG);
9229 WorklistRemover DeadNodes(*this);
9231 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9232 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9234 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9237 // Finally, since the node is now dead, remove it from the graph.
9238 deleteAndRecombine(N);
9241 std::swap(BasePtr, Offset);
9243 // Replace other uses of BasePtr that can be updated to use Ptr
9244 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9245 unsigned OffsetIdx = 1;
9246 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9248 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9249 BasePtr.getNode() && "Expected BasePtr operand");
9251 // We need to replace ptr0 in the following expression:
9252 // x0 * offset0 + y0 * ptr0 = t0
9254 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9256 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9257 // indexed load/store and the expresion that needs to be re-written.
9259 // Therefore, we have:
9260 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9262 ConstantSDNode *CN =
9263 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9265 APInt Offset0 = CN->getAPIntValue();
9266 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9268 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9269 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9270 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9271 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9273 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9275 APInt CNV = Offset0;
9276 if (X0 < 0) CNV = -CNV;
9277 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9278 else CNV = CNV - Offset1;
9280 SDLoc DL(OtherUses[i]);
9282 // We can now generate the new expression.
9283 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9284 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9286 SDValue NewUse = DAG.getNode(Opcode,
9288 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9289 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9290 deleteAndRecombine(OtherUses[i]);
9293 // Replace the uses of Ptr with uses of the updated base value.
9294 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9295 deleteAndRecombine(Ptr.getNode());
9300 /// Try to combine a load/store with a add/sub of the base pointer node into a
9301 /// post-indexed load/store. The transformation folded the add/subtract into the
9302 /// new indexed load/store effectively and all of its uses are redirected to the
9304 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9305 if (Level < AfterLegalizeDAG)
9311 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9312 if (LD->isIndexed())
9314 VT = LD->getMemoryVT();
9315 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9316 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9318 Ptr = LD->getBasePtr();
9319 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9320 if (ST->isIndexed())
9322 VT = ST->getMemoryVT();
9323 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9324 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9326 Ptr = ST->getBasePtr();
9332 if (Ptr.getNode()->hasOneUse())
9335 for (SDNode *Op : Ptr.getNode()->uses()) {
9337 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9342 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9343 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9344 // Don't create a indexed load / store with zero offset.
9345 if (isa<ConstantSDNode>(Offset) &&
9346 cast<ConstantSDNode>(Offset)->isNullValue())
9349 // Try turning it into a post-indexed load / store except when
9350 // 1) All uses are load / store ops that use it as base ptr (and
9351 // it may be folded as addressing mmode).
9352 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9353 // nor a successor of N. Otherwise, if Op is folded that would
9356 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9360 bool TryNext = false;
9361 for (SDNode *Use : BasePtr.getNode()->uses()) {
9362 if (Use == Ptr.getNode())
9365 // If all the uses are load / store addresses, then don't do the
9367 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9368 bool RealUse = false;
9369 for (SDNode *UseUse : Use->uses()) {
9370 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9385 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9386 SDValue Result = isLoad
9387 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9388 BasePtr, Offset, AM)
9389 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9390 BasePtr, Offset, AM);
9393 DEBUG(dbgs() << "\nReplacing.5 ";
9395 dbgs() << "\nWith: ";
9396 Result.getNode()->dump(&DAG);
9398 WorklistRemover DeadNodes(*this);
9400 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9401 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9403 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9406 // Finally, since the node is now dead, remove it from the graph.
9407 deleteAndRecombine(N);
9409 // Replace the uses of Use with uses of the updated base value.
9410 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9411 Result.getValue(isLoad ? 1 : 0));
9412 deleteAndRecombine(Op);
9421 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9422 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9423 ISD::MemIndexedMode AM = LD->getAddressingMode();
9424 assert(AM != ISD::UNINDEXED);
9425 SDValue BP = LD->getOperand(1);
9426 SDValue Inc = LD->getOperand(2);
9428 // Some backends use TargetConstants for load offsets, but don't expect
9429 // TargetConstants in general ADD nodes. We can convert these constants into
9430 // regular Constants (if the constant is not opaque).
9431 assert((Inc.getOpcode() != ISD::TargetConstant ||
9432 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9433 "Cannot split out indexing using opaque target constants");
9434 if (Inc.getOpcode() == ISD::TargetConstant) {
9435 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9436 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9437 ConstInc->getValueType(0));
9441 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9442 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9445 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9446 LoadSDNode *LD = cast<LoadSDNode>(N);
9447 SDValue Chain = LD->getChain();
9448 SDValue Ptr = LD->getBasePtr();
9450 // If load is not volatile and there are no uses of the loaded value (and
9451 // the updated indexed value in case of indexed loads), change uses of the
9452 // chain value into uses of the chain input (i.e. delete the dead load).
9453 if (!LD->isVolatile()) {
9454 if (N->getValueType(1) == MVT::Other) {
9456 if (!N->hasAnyUseOfValue(0)) {
9457 // It's not safe to use the two value CombineTo variant here. e.g.
9458 // v1, chain2 = load chain1, loc
9459 // v2, chain3 = load chain2, loc
9461 // Now we replace use of chain2 with chain1. This makes the second load
9462 // isomorphic to the one we are deleting, and thus makes this load live.
9463 DEBUG(dbgs() << "\nReplacing.6 ";
9465 dbgs() << "\nWith chain: ";
9466 Chain.getNode()->dump(&DAG);
9468 WorklistRemover DeadNodes(*this);
9469 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9472 deleteAndRecombine(N);
9474 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9478 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9480 // If this load has an opaque TargetConstant offset, then we cannot split
9481 // the indexing into an add/sub directly (that TargetConstant may not be
9482 // valid for a different type of node, and we cannot convert an opaque
9483 // target constant into a regular constant).
9484 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9485 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9487 if (!N->hasAnyUseOfValue(0) &&
9488 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9489 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9491 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9492 Index = SplitIndexingFromLoad(LD);
9493 // Try to fold the base pointer arithmetic into subsequent loads and
9495 AddUsersToWorklist(N);
9497 Index = DAG.getUNDEF(N->getValueType(1));
9498 DEBUG(dbgs() << "\nReplacing.7 ";
9500 dbgs() << "\nWith: ";
9501 Undef.getNode()->dump(&DAG);
9502 dbgs() << " and 2 other values\n");
9503 WorklistRemover DeadNodes(*this);
9504 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9505 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9506 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9507 deleteAndRecombine(N);
9508 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9513 // If this load is directly stored, replace the load value with the stored
9515 // TODO: Handle store large -> read small portion.
9516 // TODO: Handle TRUNCSTORE/LOADEXT
9517 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9518 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9519 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9520 if (PrevST->getBasePtr() == Ptr &&
9521 PrevST->getValue().getValueType() == N->getValueType(0))
9522 return CombineTo(N, Chain.getOperand(1), Chain);
9526 // Try to infer better alignment information than the load already has.
9527 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9528 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9529 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9531 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9532 LD->getValueType(0),
9533 Chain, Ptr, LD->getPointerInfo(),
9535 LD->isVolatile(), LD->isNonTemporal(),
9536 LD->isInvariant(), Align, LD->getAAInfo());
9537 if (NewLoad.getNode() != N)
9538 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9543 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9544 : DAG.getSubtarget().useAA();
9546 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9547 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9550 if (UseAA && LD->isUnindexed()) {
9551 // Walk up chain skipping non-aliasing memory nodes.
9552 SDValue BetterChain = FindBetterChain(N, Chain);
9554 // If there is a better chain.
9555 if (Chain != BetterChain) {
9558 // Replace the chain to void dependency.
9559 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9560 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9561 BetterChain, Ptr, LD->getMemOperand());
9563 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9564 LD->getValueType(0),
9565 BetterChain, Ptr, LD->getMemoryVT(),
9566 LD->getMemOperand());
9569 // Create token factor to keep old chain connected.
9570 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9571 MVT::Other, Chain, ReplLoad.getValue(1));
9573 // Make sure the new and old chains are cleaned up.
9574 AddToWorklist(Token.getNode());
9576 // Replace uses with load result and token factor. Don't add users
9578 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9582 // Try transforming N to an indexed load.
9583 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9584 return SDValue(N, 0);
9586 // Try to slice up N to more direct loads if the slices are mapped to
9587 // different register banks or pairing can take place.
9589 return SDValue(N, 0);
9595 /// \brief Helper structure used to slice a load in smaller loads.
9596 /// Basically a slice is obtained from the following sequence:
9597 /// Origin = load Ty1, Base
9598 /// Shift = srl Ty1 Origin, CstTy Amount
9599 /// Inst = trunc Shift to Ty2
9601 /// Then, it will be rewriten into:
9602 /// Slice = load SliceTy, Base + SliceOffset
9603 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9605 /// SliceTy is deduced from the number of bits that are actually used to
9607 struct LoadedSlice {
9608 /// \brief Helper structure used to compute the cost of a slice.
9610 /// Are we optimizing for code size.
9615 unsigned CrossRegisterBanksCopies;
9619 Cost(bool ForCodeSize = false)
9620 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9621 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9623 /// \brief Get the cost of one isolated slice.
9624 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9625 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9626 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9627 EVT TruncType = LS.Inst->getValueType(0);
9628 EVT LoadedType = LS.getLoadedType();
9629 if (TruncType != LoadedType &&
9630 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9634 /// \brief Account for slicing gain in the current cost.
9635 /// Slicing provide a few gains like removing a shift or a
9636 /// truncate. This method allows to grow the cost of the original
9637 /// load with the gain from this slice.
9638 void addSliceGain(const LoadedSlice &LS) {
9639 // Each slice saves a truncate.
9640 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9641 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9642 LS.Inst->getOperand(0).getValueType()))
9644 // If there is a shift amount, this slice gets rid of it.
9647 // If this slice can merge a cross register bank copy, account for it.
9648 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9649 ++CrossRegisterBanksCopies;
9652 Cost &operator+=(const Cost &RHS) {
9654 Truncates += RHS.Truncates;
9655 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9661 bool operator==(const Cost &RHS) const {
9662 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9663 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9664 ZExts == RHS.ZExts && Shift == RHS.Shift;
9667 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9669 bool operator<(const Cost &RHS) const {
9670 // Assume cross register banks copies are as expensive as loads.
9671 // FIXME: Do we want some more target hooks?
9672 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9673 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9674 // Unless we are optimizing for code size, consider the
9675 // expensive operation first.
9676 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9677 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9678 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9679 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9682 bool operator>(const Cost &RHS) const { return RHS < *this; }
9684 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9686 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9688 // The last instruction that represent the slice. This should be a
9689 // truncate instruction.
9691 // The original load instruction.
9693 // The right shift amount in bits from the original load.
9695 // The DAG from which Origin came from.
9696 // This is used to get some contextual information about legal types, etc.
9699 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9700 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9701 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9703 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9704 /// \return Result is \p BitWidth and has used bits set to 1 and
9705 /// not used bits set to 0.
9706 APInt getUsedBits() const {
9707 // Reproduce the trunc(lshr) sequence:
9708 // - Start from the truncated value.
9709 // - Zero extend to the desired bit width.
9711 assert(Origin && "No original load to compare against.");
9712 unsigned BitWidth = Origin->getValueSizeInBits(0);
9713 assert(Inst && "This slice is not bound to an instruction");
9714 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9715 "Extracted slice is bigger than the whole type!");
9716 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9717 UsedBits.setAllBits();
9718 UsedBits = UsedBits.zext(BitWidth);
9723 /// \brief Get the size of the slice to be loaded in bytes.
9724 unsigned getLoadedSize() const {
9725 unsigned SliceSize = getUsedBits().countPopulation();
9726 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9727 return SliceSize / 8;
9730 /// \brief Get the type that will be loaded for this slice.
9731 /// Note: This may not be the final type for the slice.
9732 EVT getLoadedType() const {
9733 assert(DAG && "Missing context");
9734 LLVMContext &Ctxt = *DAG->getContext();
9735 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9738 /// \brief Get the alignment of the load used for this slice.
9739 unsigned getAlignment() const {
9740 unsigned Alignment = Origin->getAlignment();
9741 unsigned Offset = getOffsetFromBase();
9743 Alignment = MinAlign(Alignment, Alignment + Offset);
9747 /// \brief Check if this slice can be rewritten with legal operations.
9748 bool isLegal() const {
9749 // An invalid slice is not legal.
9750 if (!Origin || !Inst || !DAG)
9753 // Offsets are for indexed load only, we do not handle that.
9754 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9757 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9759 // Check that the type is legal.
9760 EVT SliceType = getLoadedType();
9761 if (!TLI.isTypeLegal(SliceType))
9764 // Check that the load is legal for this type.
9765 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9768 // Check that the offset can be computed.
9769 // 1. Check its type.
9770 EVT PtrType = Origin->getBasePtr().getValueType();
9771 if (PtrType == MVT::Untyped || PtrType.isExtended())
9774 // 2. Check that it fits in the immediate.
9775 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9778 // 3. Check that the computation is legal.
9779 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9782 // Check that the zext is legal if it needs one.
9783 EVT TruncateType = Inst->getValueType(0);
9784 if (TruncateType != SliceType &&
9785 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9791 /// \brief Get the offset in bytes of this slice in the original chunk of
9793 /// \pre DAG != nullptr.
9794 uint64_t getOffsetFromBase() const {
9795 assert(DAG && "Missing context.");
9797 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9798 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9799 uint64_t Offset = Shift / 8;
9800 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9801 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9802 "The size of the original loaded type is not a multiple of a"
9804 // If Offset is bigger than TySizeInBytes, it means we are loading all
9805 // zeros. This should have been optimized before in the process.
9806 assert(TySizeInBytes > Offset &&
9807 "Invalid shift amount for given loaded size");
9809 Offset = TySizeInBytes - Offset - getLoadedSize();
9813 /// \brief Generate the sequence of instructions to load the slice
9814 /// represented by this object and redirect the uses of this slice to
9815 /// this new sequence of instructions.
9816 /// \pre this->Inst && this->Origin are valid Instructions and this
9817 /// object passed the legal check: LoadedSlice::isLegal returned true.
9818 /// \return The last instruction of the sequence used to load the slice.
9819 SDValue loadSlice() const {
9820 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9821 const SDValue &OldBaseAddr = Origin->getBasePtr();
9822 SDValue BaseAddr = OldBaseAddr;
9823 // Get the offset in that chunk of bytes w.r.t. the endianess.
9824 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9825 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9827 // BaseAddr = BaseAddr + Offset.
9828 EVT ArithType = BaseAddr.getValueType();
9830 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9831 DAG->getConstant(Offset, DL, ArithType));
9834 // Create the type of the loaded slice according to its size.
9835 EVT SliceType = getLoadedType();
9837 // Create the load for the slice.
9838 SDValue LastInst = DAG->getLoad(
9839 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9840 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9841 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9842 // If the final type is not the same as the loaded type, this means that
9843 // we have to pad with zero. Create a zero extend for that.
9844 EVT FinalType = Inst->getValueType(0);
9845 if (SliceType != FinalType)
9847 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9851 /// \brief Check if this slice can be merged with an expensive cross register
9852 /// bank copy. E.g.,
9854 /// f = bitcast i32 i to float
9855 bool canMergeExpensiveCrossRegisterBankCopy() const {
9856 if (!Inst || !Inst->hasOneUse())
9858 SDNode *Use = *Inst->use_begin();
9859 if (Use->getOpcode() != ISD::BITCAST)
9861 assert(DAG && "Missing context");
9862 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9863 EVT ResVT = Use->getValueType(0);
9864 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9865 const TargetRegisterClass *ArgRC =
9866 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9867 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9870 // At this point, we know that we perform a cross-register-bank copy.
9871 // Check if it is expensive.
9872 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9873 // Assume bitcasts are cheap, unless both register classes do not
9874 // explicitly share a common sub class.
9875 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9878 // Check if it will be merged with the load.
9879 // 1. Check the alignment constraint.
9880 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9881 ResVT.getTypeForEVT(*DAG->getContext()));
9883 if (RequiredAlignment > getAlignment())
9886 // 2. Check that the load is a legal operation for that type.
9887 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9890 // 3. Check that we do not have a zext in the way.
9891 if (Inst->getValueType(0) != getLoadedType())
9899 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9900 /// \p UsedBits looks like 0..0 1..1 0..0.
9901 static bool areUsedBitsDense(const APInt &UsedBits) {
9902 // If all the bits are one, this is dense!
9903 if (UsedBits.isAllOnesValue())
9906 // Get rid of the unused bits on the right.
9907 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9908 // Get rid of the unused bits on the left.
9909 if (NarrowedUsedBits.countLeadingZeros())
9910 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9911 // Check that the chunk of bits is completely used.
9912 return NarrowedUsedBits.isAllOnesValue();
9915 /// \brief Check whether or not \p First and \p Second are next to each other
9916 /// in memory. This means that there is no hole between the bits loaded
9917 /// by \p First and the bits loaded by \p Second.
9918 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9919 const LoadedSlice &Second) {
9920 assert(First.Origin == Second.Origin && First.Origin &&
9921 "Unable to match different memory origins.");
9922 APInt UsedBits = First.getUsedBits();
9923 assert((UsedBits & Second.getUsedBits()) == 0 &&
9924 "Slices are not supposed to overlap.");
9925 UsedBits |= Second.getUsedBits();
9926 return areUsedBitsDense(UsedBits);
9929 /// \brief Adjust the \p GlobalLSCost according to the target
9930 /// paring capabilities and the layout of the slices.
9931 /// \pre \p GlobalLSCost should account for at least as many loads as
9932 /// there is in the slices in \p LoadedSlices.
9933 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9934 LoadedSlice::Cost &GlobalLSCost) {
9935 unsigned NumberOfSlices = LoadedSlices.size();
9936 // If there is less than 2 elements, no pairing is possible.
9937 if (NumberOfSlices < 2)
9940 // Sort the slices so that elements that are likely to be next to each
9941 // other in memory are next to each other in the list.
9942 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9943 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9944 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9945 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9947 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9948 // First (resp. Second) is the first (resp. Second) potentially candidate
9949 // to be placed in a paired load.
9950 const LoadedSlice *First = nullptr;
9951 const LoadedSlice *Second = nullptr;
9952 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9953 // Set the beginning of the pair.
9956 Second = &LoadedSlices[CurrSlice];
9958 // If First is NULL, it means we start a new pair.
9959 // Get to the next slice.
9963 EVT LoadedType = First->getLoadedType();
9965 // If the types of the slices are different, we cannot pair them.
9966 if (LoadedType != Second->getLoadedType())
9969 // Check if the target supplies paired loads for this type.
9970 unsigned RequiredAlignment = 0;
9971 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9972 // move to the next pair, this type is hopeless.
9976 // Check if we meet the alignment requirement.
9977 if (RequiredAlignment > First->getAlignment())
9980 // Check that both loads are next to each other in memory.
9981 if (!areSlicesNextToEachOther(*First, *Second))
9984 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9985 --GlobalLSCost.Loads;
9986 // Move to the next pair.
9991 /// \brief Check the profitability of all involved LoadedSlice.
9992 /// Currently, it is considered profitable if there is exactly two
9993 /// involved slices (1) which are (2) next to each other in memory, and
9994 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9996 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9997 /// the elements themselves.
9999 /// FIXME: When the cost model will be mature enough, we can relax
10000 /// constraints (1) and (2).
10001 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10002 const APInt &UsedBits, bool ForCodeSize) {
10003 unsigned NumberOfSlices = LoadedSlices.size();
10004 if (StressLoadSlicing)
10005 return NumberOfSlices > 1;
10008 if (NumberOfSlices != 2)
10012 if (!areUsedBitsDense(UsedBits))
10016 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10017 // The original code has one big load.
10018 OrigCost.Loads = 1;
10019 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10020 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10021 // Accumulate the cost of all the slices.
10022 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10023 GlobalSlicingCost += SliceCost;
10025 // Account as cost in the original configuration the gain obtained
10026 // with the current slices.
10027 OrigCost.addSliceGain(LS);
10030 // If the target supports paired load, adjust the cost accordingly.
10031 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10032 return OrigCost > GlobalSlicingCost;
10035 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10036 /// operations, split it in the various pieces being extracted.
10038 /// This sort of thing is introduced by SROA.
10039 /// This slicing takes care not to insert overlapping loads.
10040 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10041 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10042 if (Level < AfterLegalizeDAG)
10045 LoadSDNode *LD = cast<LoadSDNode>(N);
10046 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10047 !LD->getValueType(0).isInteger())
10050 // Keep track of already used bits to detect overlapping values.
10051 // In that case, we will just abort the transformation.
10052 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10054 SmallVector<LoadedSlice, 4> LoadedSlices;
10056 // Check if this load is used as several smaller chunks of bits.
10057 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10058 // of computation for each trunc.
10059 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10060 UI != UIEnd; ++UI) {
10061 // Skip the uses of the chain.
10062 if (UI.getUse().getResNo() != 0)
10065 SDNode *User = *UI;
10066 unsigned Shift = 0;
10068 // Check if this is a trunc(lshr).
10069 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10070 isa<ConstantSDNode>(User->getOperand(1))) {
10071 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10072 User = *User->use_begin();
10075 // At this point, User is a Truncate, iff we encountered, trunc or
10077 if (User->getOpcode() != ISD::TRUNCATE)
10080 // The width of the type must be a power of 2 and greater than 8-bits.
10081 // Otherwise the load cannot be represented in LLVM IR.
10082 // Moreover, if we shifted with a non-8-bits multiple, the slice
10083 // will be across several bytes. We do not support that.
10084 unsigned Width = User->getValueSizeInBits(0);
10085 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10088 // Build the slice for this chain of computations.
10089 LoadedSlice LS(User, LD, Shift, &DAG);
10090 APInt CurrentUsedBits = LS.getUsedBits();
10092 // Check if this slice overlaps with another.
10093 if ((CurrentUsedBits & UsedBits) != 0)
10095 // Update the bits used globally.
10096 UsedBits |= CurrentUsedBits;
10098 // Check if the new slice would be legal.
10102 // Record the slice.
10103 LoadedSlices.push_back(LS);
10106 // Abort slicing if it does not seem to be profitable.
10107 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10112 // Rewrite each chain to use an independent load.
10113 // By construction, each chain can be represented by a unique load.
10115 // Prepare the argument for the new token factor for all the slices.
10116 SmallVector<SDValue, 8> ArgChains;
10117 for (SmallVectorImpl<LoadedSlice>::const_iterator
10118 LSIt = LoadedSlices.begin(),
10119 LSItEnd = LoadedSlices.end();
10120 LSIt != LSItEnd; ++LSIt) {
10121 SDValue SliceInst = LSIt->loadSlice();
10122 CombineTo(LSIt->Inst, SliceInst, true);
10123 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10124 SliceInst = SliceInst.getOperand(0);
10125 assert(SliceInst->getOpcode() == ISD::LOAD &&
10126 "It takes more than a zext to get to the loaded slice!!");
10127 ArgChains.push_back(SliceInst.getValue(1));
10130 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10132 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10136 /// Check to see if V is (and load (ptr), imm), where the load is having
10137 /// specific bytes cleared out. If so, return the byte size being masked out
10138 /// and the shift amount.
10139 static std::pair<unsigned, unsigned>
10140 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10141 std::pair<unsigned, unsigned> Result(0, 0);
10143 // Check for the structure we're looking for.
10144 if (V->getOpcode() != ISD::AND ||
10145 !isa<ConstantSDNode>(V->getOperand(1)) ||
10146 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10149 // Check the chain and pointer.
10150 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10151 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10153 // The store should be chained directly to the load or be an operand of a
10155 if (LD == Chain.getNode())
10157 else if (Chain->getOpcode() != ISD::TokenFactor)
10158 return Result; // Fail.
10161 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10162 if (Chain->getOperand(i).getNode() == LD) {
10166 if (!isOk) return Result;
10169 // This only handles simple types.
10170 if (V.getValueType() != MVT::i16 &&
10171 V.getValueType() != MVT::i32 &&
10172 V.getValueType() != MVT::i64)
10175 // Check the constant mask. Invert it so that the bits being masked out are
10176 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10177 // follow the sign bit for uniformity.
10178 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10179 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10180 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10181 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10182 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10183 if (NotMaskLZ == 64) return Result; // All zero mask.
10185 // See if we have a continuous run of bits. If so, we have 0*1+0*
10186 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10189 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10190 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10191 NotMaskLZ -= 64-V.getValueSizeInBits();
10193 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10194 switch (MaskedBytes) {
10198 default: return Result; // All one mask, or 5-byte mask.
10201 // Verify that the first bit starts at a multiple of mask so that the access
10202 // is aligned the same as the access width.
10203 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10205 Result.first = MaskedBytes;
10206 Result.second = NotMaskTZ/8;
10211 /// Check to see if IVal is something that provides a value as specified by
10212 /// MaskInfo. If so, replace the specified store with a narrower store of
10213 /// truncated IVal.
10215 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10216 SDValue IVal, StoreSDNode *St,
10218 unsigned NumBytes = MaskInfo.first;
10219 unsigned ByteShift = MaskInfo.second;
10220 SelectionDAG &DAG = DC->getDAG();
10222 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10223 // that uses this. If not, this is not a replacement.
10224 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10225 ByteShift*8, (ByteShift+NumBytes)*8);
10226 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10228 // Check that it is legal on the target to do this. It is legal if the new
10229 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10231 MVT VT = MVT::getIntegerVT(NumBytes*8);
10232 if (!DC->isTypeLegal(VT))
10235 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10236 // shifted by ByteShift and truncated down to NumBytes.
10239 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10240 DAG.getConstant(ByteShift*8, DL,
10241 DC->getShiftAmountTy(IVal.getValueType())));
10244 // Figure out the offset for the store and the alignment of the access.
10246 unsigned NewAlign = St->getAlignment();
10248 if (DAG.getTargetLoweringInfo().isLittleEndian())
10249 StOffset = ByteShift;
10251 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10253 SDValue Ptr = St->getBasePtr();
10256 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10257 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10258 NewAlign = MinAlign(NewAlign, StOffset);
10261 // Truncate down to the new size.
10262 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10265 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10266 St->getPointerInfo().getWithOffset(StOffset),
10267 false, false, NewAlign).getNode();
10271 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10272 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10273 /// narrowing the load and store if it would end up being a win for performance
10275 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10276 StoreSDNode *ST = cast<StoreSDNode>(N);
10277 if (ST->isVolatile())
10280 SDValue Chain = ST->getChain();
10281 SDValue Value = ST->getValue();
10282 SDValue Ptr = ST->getBasePtr();
10283 EVT VT = Value.getValueType();
10285 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10288 unsigned Opc = Value.getOpcode();
10290 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10291 // is a byte mask indicating a consecutive number of bytes, check to see if
10292 // Y is known to provide just those bytes. If so, we try to replace the
10293 // load + replace + store sequence with a single (narrower) store, which makes
10295 if (Opc == ISD::OR) {
10296 std::pair<unsigned, unsigned> MaskedLoad;
10297 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10298 if (MaskedLoad.first)
10299 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10300 Value.getOperand(1), ST,this))
10301 return SDValue(NewST, 0);
10303 // Or is commutative, so try swapping X and Y.
10304 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10305 if (MaskedLoad.first)
10306 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10307 Value.getOperand(0), ST,this))
10308 return SDValue(NewST, 0);
10311 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10312 Value.getOperand(1).getOpcode() != ISD::Constant)
10315 SDValue N0 = Value.getOperand(0);
10316 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10317 Chain == SDValue(N0.getNode(), 1)) {
10318 LoadSDNode *LD = cast<LoadSDNode>(N0);
10319 if (LD->getBasePtr() != Ptr ||
10320 LD->getPointerInfo().getAddrSpace() !=
10321 ST->getPointerInfo().getAddrSpace())
10324 // Find the type to narrow it the load / op / store to.
10325 SDValue N1 = Value.getOperand(1);
10326 unsigned BitWidth = N1.getValueSizeInBits();
10327 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10328 if (Opc == ISD::AND)
10329 Imm ^= APInt::getAllOnesValue(BitWidth);
10330 if (Imm == 0 || Imm.isAllOnesValue())
10332 unsigned ShAmt = Imm.countTrailingZeros();
10333 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10334 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10335 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10336 // The narrowing should be profitable, the load/store operation should be
10337 // legal (or custom) and the store size should be equal to the NewVT width.
10338 while (NewBW < BitWidth &&
10339 (NewVT.getStoreSizeInBits() != NewBW ||
10340 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10341 !TLI.isNarrowingProfitable(VT, NewVT))) {
10342 NewBW = NextPowerOf2(NewBW);
10343 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10345 if (NewBW >= BitWidth)
10348 // If the lsb changed does not start at the type bitwidth boundary,
10349 // start at the previous one.
10351 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10352 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10353 std::min(BitWidth, ShAmt + NewBW));
10354 if ((Imm & Mask) == Imm) {
10355 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10356 if (Opc == ISD::AND)
10357 NewImm ^= APInt::getAllOnesValue(NewBW);
10358 uint64_t PtrOff = ShAmt / 8;
10359 // For big endian targets, we need to adjust the offset to the pointer to
10360 // load the correct bytes.
10361 if (TLI.isBigEndian())
10362 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10364 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10365 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10366 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10369 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10370 Ptr.getValueType(), Ptr,
10371 DAG.getConstant(PtrOff, SDLoc(LD),
10372 Ptr.getValueType()));
10373 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10374 LD->getChain(), NewPtr,
10375 LD->getPointerInfo().getWithOffset(PtrOff),
10376 LD->isVolatile(), LD->isNonTemporal(),
10377 LD->isInvariant(), NewAlign,
10379 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10380 DAG.getConstant(NewImm, SDLoc(Value),
10382 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10384 ST->getPointerInfo().getWithOffset(PtrOff),
10385 false, false, NewAlign);
10387 AddToWorklist(NewPtr.getNode());
10388 AddToWorklist(NewLD.getNode());
10389 AddToWorklist(NewVal.getNode());
10390 WorklistRemover DeadNodes(*this);
10391 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10400 /// For a given floating point load / store pair, if the load value isn't used
10401 /// by any other operations, then consider transforming the pair to integer
10402 /// load / store operations if the target deems the transformation profitable.
10403 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10404 StoreSDNode *ST = cast<StoreSDNode>(N);
10405 SDValue Chain = ST->getChain();
10406 SDValue Value = ST->getValue();
10407 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10408 Value.hasOneUse() &&
10409 Chain == SDValue(Value.getNode(), 1)) {
10410 LoadSDNode *LD = cast<LoadSDNode>(Value);
10411 EVT VT = LD->getMemoryVT();
10412 if (!VT.isFloatingPoint() ||
10413 VT != ST->getMemoryVT() ||
10414 LD->isNonTemporal() ||
10415 ST->isNonTemporal() ||
10416 LD->getPointerInfo().getAddrSpace() != 0 ||
10417 ST->getPointerInfo().getAddrSpace() != 0)
10420 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10421 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10422 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10423 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10424 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10427 unsigned LDAlign = LD->getAlignment();
10428 unsigned STAlign = ST->getAlignment();
10429 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10430 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10431 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10434 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10435 LD->getChain(), LD->getBasePtr(),
10436 LD->getPointerInfo(),
10437 false, false, false, LDAlign);
10439 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10440 NewLD, ST->getBasePtr(),
10441 ST->getPointerInfo(),
10442 false, false, STAlign);
10444 AddToWorklist(NewLD.getNode());
10445 AddToWorklist(NewST.getNode());
10446 WorklistRemover DeadNodes(*this);
10447 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10456 /// Helper struct to parse and store a memory address as base + index + offset.
10457 /// We ignore sign extensions when it is safe to do so.
10458 /// The following two expressions are not equivalent. To differentiate we need
10459 /// to store whether there was a sign extension involved in the index
10461 /// (load (i64 add (i64 copyfromreg %c)
10462 /// (i64 signextend (add (i8 load %index)
10466 /// (load (i64 add (i64 copyfromreg %c)
10467 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10469 struct BaseIndexOffset {
10473 bool IsIndexSignExt;
10475 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10477 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10478 bool IsIndexSignExt) :
10479 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10481 bool equalBaseIndex(const BaseIndexOffset &Other) {
10482 return Other.Base == Base && Other.Index == Index &&
10483 Other.IsIndexSignExt == IsIndexSignExt;
10486 /// Parses tree in Ptr for base, index, offset addresses.
10487 static BaseIndexOffset match(SDValue Ptr) {
10488 bool IsIndexSignExt = false;
10490 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10491 // instruction, then it could be just the BASE or everything else we don't
10492 // know how to handle. Just use Ptr as BASE and give up.
10493 if (Ptr->getOpcode() != ISD::ADD)
10494 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10496 // We know that we have at least an ADD instruction. Try to pattern match
10497 // the simple case of BASE + OFFSET.
10498 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10499 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10500 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10504 // Inside a loop the current BASE pointer is calculated using an ADD and a
10505 // MUL instruction. In this case Ptr is the actual BASE pointer.
10506 // (i64 add (i64 %array_ptr)
10507 // (i64 mul (i64 %induction_var)
10508 // (i64 %element_size)))
10509 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10510 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10512 // Look at Base + Index + Offset cases.
10513 SDValue Base = Ptr->getOperand(0);
10514 SDValue IndexOffset = Ptr->getOperand(1);
10516 // Skip signextends.
10517 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10518 IndexOffset = IndexOffset->getOperand(0);
10519 IsIndexSignExt = true;
10522 // Either the case of Base + Index (no offset) or something else.
10523 if (IndexOffset->getOpcode() != ISD::ADD)
10524 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10526 // Now we have the case of Base + Index + offset.
10527 SDValue Index = IndexOffset->getOperand(0);
10528 SDValue Offset = IndexOffset->getOperand(1);
10530 if (!isa<ConstantSDNode>(Offset))
10531 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10533 // Ignore signextends.
10534 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10535 Index = Index->getOperand(0);
10536 IsIndexSignExt = true;
10537 } else IsIndexSignExt = false;
10539 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10540 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10545 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10546 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10547 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10548 // Make sure we have something to merge.
10552 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10553 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10554 unsigned LatestNodeUsed = 0;
10556 for (unsigned i=0; i < NumElem; ++i) {
10557 // Find a chain for the new wide-store operand. Notice that some
10558 // of the store nodes that we found may not be selected for inclusion
10559 // in the wide store. The chain we use needs to be the chain of the
10560 // latest store node which is *used* and replaced by the wide store.
10561 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10562 LatestNodeUsed = i;
10565 // The latest Node in the DAG.
10566 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10567 SDLoc DL(StoreNodes[0].MemNode);
10571 // Find a legal type for the vector store.
10572 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10573 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10574 if (IsConstantSrc) {
10575 // A vector store with a constant source implies that the constant is
10576 // zero; we only handle merging stores of constant zeros because the zero
10577 // can be materialized without a load.
10578 // It may be beneficial to loosen this restriction to allow non-zero
10580 StoredVal = DAG.getConstant(0, DL, Ty);
10582 SmallVector<SDValue, 8> Ops;
10583 for (unsigned i = 0; i < NumElem ; ++i) {
10584 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10585 SDValue Val = St->getValue();
10586 // All of the operands of a BUILD_VECTOR must have the same type.
10587 if (Val.getValueType() != MemVT)
10589 Ops.push_back(Val);
10592 // Build the extracted vector elements back into a vector.
10593 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10596 // We should always use a vector store when merging extracted vector
10597 // elements, so this path implies a store of constants.
10598 assert(IsConstantSrc && "Merged vector elements should use vector store");
10600 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10601 APInt StoreInt(StoreBW, 0);
10603 // Construct a single integer constant which is made of the smaller
10604 // constant inputs.
10605 bool IsLE = TLI.isLittleEndian();
10606 for (unsigned i = 0; i < NumElem ; ++i) {
10607 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10608 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10609 SDValue Val = St->getValue();
10610 StoreInt <<= ElementSizeBytes*8;
10611 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10612 StoreInt |= C->getAPIntValue().zext(StoreBW);
10613 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10614 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10616 llvm_unreachable("Invalid constant element type");
10620 // Create the new Load and Store operations.
10621 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10622 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10625 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10626 FirstInChain->getBasePtr(),
10627 FirstInChain->getPointerInfo(),
10629 FirstInChain->getAlignment());
10631 // Replace the last store with the new store
10632 CombineTo(LatestOp, NewStore);
10633 // Erase all other stores.
10634 for (unsigned i = 0; i < NumElem ; ++i) {
10635 if (StoreNodes[i].MemNode == LatestOp)
10637 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10638 // ReplaceAllUsesWith will replace all uses that existed when it was
10639 // called, but graph optimizations may cause new ones to appear. For
10640 // example, the case in pr14333 looks like
10642 // St's chain -> St -> another store -> X
10644 // And the only difference from St to the other store is the chain.
10645 // When we change it's chain to be St's chain they become identical,
10646 // get CSEed and the net result is that X is now a use of St.
10647 // Since we know that St is redundant, just iterate.
10648 while (!St->use_empty())
10649 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10650 deleteAndRecombine(St);
10656 static bool allowableAlignment(const SelectionDAG &DAG,
10657 const TargetLowering &TLI, EVT EVTTy,
10658 unsigned AS, unsigned Align) {
10659 if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10662 Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10663 unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10664 return (Align >= ABIAlignment);
10667 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10668 if (OptLevel == CodeGenOpt::None)
10671 EVT MemVT = St->getMemoryVT();
10672 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10673 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10674 Attribute::NoImplicitFloat);
10676 // This function cannot currently deal with non-byte-sized memory sizes.
10677 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10680 // Don't merge vectors into wider inputs.
10681 if (MemVT.isVector() || !MemVT.isSimple())
10684 // Perform an early exit check. Do not bother looking at stored values that
10685 // are not constants, loads, or extracted vector elements.
10686 SDValue StoredVal = St->getValue();
10687 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10688 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10689 isa<ConstantFPSDNode>(StoredVal);
10690 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10692 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10695 // Only look at ends of store sequences.
10696 SDValue Chain = SDValue(St, 0);
10697 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10700 // This holds the base pointer, index, and the offset in bytes from the base
10702 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10704 // We must have a base and an offset.
10705 if (!BasePtr.Base.getNode())
10708 // Do not handle stores to undef base pointers.
10709 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10712 // Save the LoadSDNodes that we find in the chain.
10713 // We need to make sure that these nodes do not interfere with
10714 // any of the store nodes.
10715 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10717 // Save the StoreSDNodes that we find in the chain.
10718 SmallVector<MemOpLink, 8> StoreNodes;
10720 // Walk up the chain and look for nodes with offsets from the same
10721 // base pointer. Stop when reaching an instruction with a different kind
10722 // or instruction which has a different base pointer.
10724 StoreSDNode *Index = St;
10726 // If the chain has more than one use, then we can't reorder the mem ops.
10727 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10730 // Find the base pointer and offset for this memory node.
10731 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10733 // Check that the base pointer is the same as the original one.
10734 if (!Ptr.equalBaseIndex(BasePtr))
10737 // The memory operands must not be volatile.
10738 if (Index->isVolatile() || Index->isIndexed())
10742 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10743 if (St->isTruncatingStore())
10746 // The stored memory type must be the same.
10747 if (Index->getMemoryVT() != MemVT)
10750 // We found a potential memory operand to merge.
10751 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10753 // Find the next memory operand in the chain. If the next operand in the
10754 // chain is a store then move up and continue the scan with the next
10755 // memory operand. If the next operand is a load save it and use alias
10756 // information to check if it interferes with anything.
10757 SDNode *NextInChain = Index->getChain().getNode();
10759 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10760 // We found a store node. Use it for the next iteration.
10763 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10764 if (Ldn->isVolatile()) {
10769 // Save the load node for later. Continue the scan.
10770 AliasLoadNodes.push_back(Ldn);
10771 NextInChain = Ldn->getChain().getNode();
10780 // Check if there is anything to merge.
10781 if (StoreNodes.size() < 2)
10784 // Sort the memory operands according to their distance from the base pointer.
10785 std::sort(StoreNodes.begin(), StoreNodes.end(),
10786 [](MemOpLink LHS, MemOpLink RHS) {
10787 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10788 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10789 LHS.SequenceNum > RHS.SequenceNum);
10792 // Scan the memory operations on the chain and find the first non-consecutive
10793 // store memory address.
10794 unsigned LastConsecutiveStore = 0;
10795 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10796 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10798 // Check that the addresses are consecutive starting from the second
10799 // element in the list of stores.
10801 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10802 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10806 bool Alias = false;
10807 // Check if this store interferes with any of the loads that we found.
10808 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10809 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10813 // We found a load that alias with this store. Stop the sequence.
10817 // Mark this node as useful.
10818 LastConsecutiveStore = i;
10821 // The node with the lowest store address.
10822 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10823 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10824 unsigned FirstStoreAlign = FirstInChain->getAlignment();
10826 // Store the constants into memory as one consecutive store.
10827 if (IsConstantSrc) {
10828 unsigned LastLegalType = 0;
10829 unsigned LastLegalVectorType = 0;
10830 bool NonZero = false;
10831 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10832 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10833 SDValue StoredVal = St->getValue();
10835 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10836 NonZero |= !C->isNullValue();
10837 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10838 NonZero |= !C->getConstantFPValue()->isNullValue();
10844 // Find a legal type for the constant store.
10845 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10846 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10847 if (TLI.isTypeLegal(StoreTy) &&
10848 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10849 FirstStoreAlign)) {
10850 LastLegalType = i+1;
10851 // Or check whether a truncstore is legal.
10852 } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10853 TargetLowering::TypePromoteInteger) {
10854 EVT LegalizedStoredValueTy =
10855 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10856 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10857 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10858 FirstStoreAlign)) {
10859 LastLegalType = i + 1;
10863 // Find a legal type for the vector store.
10864 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10865 if (TLI.isTypeLegal(Ty) &&
10866 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10867 LastLegalVectorType = i + 1;
10871 // We only use vectors if the constant is known to be zero and the
10872 // function is not marked with the noimplicitfloat attribute.
10873 if (NonZero || NoVectors)
10874 LastLegalVectorType = 0;
10876 // Check if we found a legal integer type to store.
10877 if (LastLegalType == 0 && LastLegalVectorType == 0)
10880 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10881 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10883 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10887 // When extracting multiple vector elements, try to store them
10888 // in one vector store rather than a sequence of scalar stores.
10889 if (IsExtractVecEltSrc) {
10890 unsigned NumElem = 0;
10891 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10892 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10893 SDValue StoredVal = St->getValue();
10894 // This restriction could be loosened.
10895 // Bail out if any stored values are not elements extracted from a vector.
10896 // It should be possible to handle mixed sources, but load sources need
10897 // more careful handling (see the block of code below that handles
10898 // consecutive loads).
10899 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10902 // Find a legal type for the vector store.
10903 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10904 if (TLI.isTypeLegal(Ty) &&
10905 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10909 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10913 // Below we handle the case of multiple consecutive stores that
10914 // come from multiple consecutive loads. We merge them into a single
10915 // wide load and a single wide store.
10917 // Look for load nodes which are used by the stored values.
10918 SmallVector<MemOpLink, 8> LoadNodes;
10920 // Find acceptable loads. Loads need to have the same chain (token factor),
10921 // must not be zext, volatile, indexed, and they must be consecutive.
10922 BaseIndexOffset LdBasePtr;
10923 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10924 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10925 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10928 // Loads must only have one use.
10929 if (!Ld->hasNUsesOfValue(1, 0))
10932 // The memory operands must not be volatile.
10933 if (Ld->isVolatile() || Ld->isIndexed())
10936 // We do not accept ext loads.
10937 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10940 // The stored memory type must be the same.
10941 if (Ld->getMemoryVT() != MemVT)
10944 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10945 // If this is not the first ptr that we check.
10946 if (LdBasePtr.Base.getNode()) {
10947 // The base ptr must be the same.
10948 if (!LdPtr.equalBaseIndex(LdBasePtr))
10951 // Check that all other base pointers are the same as this one.
10955 // We found a potential memory operand to merge.
10956 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10959 if (LoadNodes.size() < 2)
10962 // If we have load/store pair instructions and we only have two values,
10964 unsigned RequiredAlignment;
10965 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10966 St->getAlignment() >= RequiredAlignment)
10969 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10970 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
10971 unsigned FirstLoadAlign = FirstLoad->getAlignment();
10973 // Scan the memory operations on the chain and find the first non-consecutive
10974 // load memory address. These variables hold the index in the store node
10976 unsigned LastConsecutiveLoad = 0;
10977 // This variable refers to the size and not index in the array.
10978 unsigned LastLegalVectorType = 0;
10979 unsigned LastLegalIntegerType = 0;
10980 StartAddress = LoadNodes[0].OffsetFromBase;
10981 SDValue FirstChain = FirstLoad->getChain();
10982 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10983 // All loads much share the same chain.
10984 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10987 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10988 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10990 LastConsecutiveLoad = i;
10992 // Find a legal type for the vector store.
10993 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10994 if (TLI.isTypeLegal(StoreTy) &&
10995 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10996 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
10997 LastLegalVectorType = i + 1;
11000 // Find a legal type for the integer store.
11001 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
11002 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11003 if (TLI.isTypeLegal(StoreTy) &&
11004 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11005 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11006 LastLegalIntegerType = i + 1;
11007 // Or check whether a truncstore and extload is legal.
11008 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11009 TargetLowering::TypePromoteInteger) {
11010 EVT LegalizedStoredValueTy =
11011 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11012 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11013 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11014 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11015 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11016 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11017 FirstStoreAlign) &&
11018 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11020 LastLegalIntegerType = i+1;
11024 // Only use vector types if the vector type is larger than the integer type.
11025 // If they are the same, use integers.
11026 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11027 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11029 // We add +1 here because the LastXXX variables refer to location while
11030 // the NumElem refers to array/index size.
11031 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11032 NumElem = std::min(LastLegalType, NumElem);
11037 // The latest Node in the DAG.
11038 unsigned LatestNodeUsed = 0;
11039 for (unsigned i=1; i<NumElem; ++i) {
11040 // Find a chain for the new wide-store operand. Notice that some
11041 // of the store nodes that we found may not be selected for inclusion
11042 // in the wide store. The chain we use needs to be the chain of the
11043 // latest store node which is *used* and replaced by the wide store.
11044 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11045 LatestNodeUsed = i;
11048 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11050 // Find if it is better to use vectors or integers to load and store
11054 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11056 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11057 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11060 SDLoc LoadDL(LoadNodes[0].MemNode);
11061 SDLoc StoreDL(StoreNodes[0].MemNode);
11063 SDValue NewLoad = DAG.getLoad(
11064 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11065 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11067 SDValue NewStore = DAG.getStore(
11068 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11069 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11071 // Replace one of the loads with the new load.
11072 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11073 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11074 SDValue(NewLoad.getNode(), 1));
11076 // Remove the rest of the load chains.
11077 for (unsigned i = 1; i < NumElem ; ++i) {
11078 // Replace all chain users of the old load nodes with the chain of the new
11080 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11081 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11084 // Replace the last store with the new store.
11085 CombineTo(LatestOp, NewStore);
11086 // Erase all other stores.
11087 for (unsigned i = 0; i < NumElem ; ++i) {
11088 // Remove all Store nodes.
11089 if (StoreNodes[i].MemNode == LatestOp)
11091 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11092 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11093 deleteAndRecombine(St);
11099 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11100 StoreSDNode *ST = cast<StoreSDNode>(N);
11101 SDValue Chain = ST->getChain();
11102 SDValue Value = ST->getValue();
11103 SDValue Ptr = ST->getBasePtr();
11105 // If this is a store of a bit convert, store the input value if the
11106 // resultant store does not need a higher alignment than the original.
11107 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11108 ST->isUnindexed()) {
11109 unsigned OrigAlign = ST->getAlignment();
11110 EVT SVT = Value.getOperand(0).getValueType();
11111 unsigned Align = TLI.getDataLayout()->
11112 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11113 if (Align <= OrigAlign &&
11114 ((!LegalOperations && !ST->isVolatile()) ||
11115 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11116 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11117 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11118 ST->isNonTemporal(), OrigAlign,
11122 // Turn 'store undef, Ptr' -> nothing.
11123 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11126 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11127 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11128 // NOTE: If the original store is volatile, this transform must not increase
11129 // the number of stores. For example, on x86-32 an f64 can be stored in one
11130 // processor operation but an i64 (which is not legal) requires two. So the
11131 // transform should not be done in this case.
11132 if (Value.getOpcode() != ISD::TargetConstantFP) {
11134 switch (CFP->getSimpleValueType(0).SimpleTy) {
11135 default: llvm_unreachable("Unknown FP type");
11136 case MVT::f16: // We don't do this for these yet.
11142 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11143 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11145 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11146 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11148 return DAG.getStore(Chain, SDLoc(N), Tmp,
11149 Ptr, ST->getMemOperand());
11153 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11154 !ST->isVolatile()) ||
11155 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11157 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11158 getZExtValue(), SDLoc(CFP), MVT::i64);
11159 return DAG.getStore(Chain, SDLoc(N), Tmp,
11160 Ptr, ST->getMemOperand());
11163 if (!ST->isVolatile() &&
11164 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11165 // Many FP stores are not made apparent until after legalize, e.g. for
11166 // argument passing. Since this is so common, custom legalize the
11167 // 64-bit integer store into two 32-bit stores.
11168 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11169 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11170 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11171 if (TLI.isBigEndian()) std::swap(Lo, Hi);
11173 unsigned Alignment = ST->getAlignment();
11174 bool isVolatile = ST->isVolatile();
11175 bool isNonTemporal = ST->isNonTemporal();
11176 AAMDNodes AAInfo = ST->getAAInfo();
11180 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11181 Ptr, ST->getPointerInfo(),
11182 isVolatile, isNonTemporal,
11183 ST->getAlignment(), AAInfo);
11184 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11185 DAG.getConstant(4, DL, Ptr.getValueType()));
11186 Alignment = MinAlign(Alignment, 4U);
11187 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11188 Ptr, ST->getPointerInfo().getWithOffset(4),
11189 isVolatile, isNonTemporal,
11190 Alignment, AAInfo);
11191 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11200 // Try to infer better alignment information than the store already has.
11201 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11202 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11203 if (Align > ST->getAlignment()) {
11205 DAG.getTruncStore(Chain, SDLoc(N), Value,
11206 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11207 ST->isVolatile(), ST->isNonTemporal(), Align,
11209 if (NewStore.getNode() != N)
11210 return CombineTo(ST, NewStore, true);
11215 // Try transforming a pair floating point load / store ops to integer
11216 // load / store ops.
11217 SDValue NewST = TransformFPLoadStorePair(N);
11218 if (NewST.getNode())
11221 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11222 : DAG.getSubtarget().useAA();
11224 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11225 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11228 if (UseAA && ST->isUnindexed()) {
11229 // Walk up chain skipping non-aliasing memory nodes.
11230 SDValue BetterChain = FindBetterChain(N, Chain);
11232 // If there is a better chain.
11233 if (Chain != BetterChain) {
11236 // Replace the chain to avoid dependency.
11237 if (ST->isTruncatingStore()) {
11238 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11239 ST->getMemoryVT(), ST->getMemOperand());
11241 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11242 ST->getMemOperand());
11245 // Create token to keep both nodes around.
11246 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11247 MVT::Other, Chain, ReplStore);
11249 // Make sure the new and old chains are cleaned up.
11250 AddToWorklist(Token.getNode());
11252 // Don't add users to work list.
11253 return CombineTo(N, Token, false);
11257 // Try transforming N to an indexed store.
11258 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11259 return SDValue(N, 0);
11261 // FIXME: is there such a thing as a truncating indexed store?
11262 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11263 Value.getValueType().isInteger()) {
11264 // See if we can simplify the input to this truncstore with knowledge that
11265 // only the low bits are being used. For example:
11266 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11268 GetDemandedBits(Value,
11269 APInt::getLowBitsSet(
11270 Value.getValueType().getScalarType().getSizeInBits(),
11271 ST->getMemoryVT().getScalarType().getSizeInBits()));
11272 AddToWorklist(Value.getNode());
11273 if (Shorter.getNode())
11274 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11275 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11277 // Otherwise, see if we can simplify the operation with
11278 // SimplifyDemandedBits, which only works if the value has a single use.
11279 if (SimplifyDemandedBits(Value,
11280 APInt::getLowBitsSet(
11281 Value.getValueType().getScalarType().getSizeInBits(),
11282 ST->getMemoryVT().getScalarType().getSizeInBits())))
11283 return SDValue(N, 0);
11286 // If this is a load followed by a store to the same location, then the store
11288 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11289 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11290 ST->isUnindexed() && !ST->isVolatile() &&
11291 // There can't be any side effects between the load and store, such as
11292 // a call or store.
11293 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11294 // The store is dead, remove it.
11299 // If this is a store followed by a store with the same value to the same
11300 // location, then the store is dead/noop.
11301 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11302 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11303 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11304 ST1->isUnindexed() && !ST1->isVolatile()) {
11305 // The store is dead, remove it.
11310 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11311 // truncating store. We can do this even if this is already a truncstore.
11312 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11313 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11314 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11315 ST->getMemoryVT())) {
11316 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11317 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11320 // Only perform this optimization before the types are legal, because we
11321 // don't want to perform this optimization on every DAGCombine invocation.
11323 bool EverChanged = false;
11326 // There can be multiple store sequences on the same chain.
11327 // Keep trying to merge store sequences until we are unable to do so
11328 // or until we merge the last store on the chain.
11329 bool Changed = MergeConsecutiveStores(ST);
11330 EverChanged |= Changed;
11331 if (!Changed) break;
11332 } while (ST->getOpcode() != ISD::DELETED_NODE);
11335 return SDValue(N, 0);
11338 return ReduceLoadOpStoreWidth(N);
11341 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11342 SDValue InVec = N->getOperand(0);
11343 SDValue InVal = N->getOperand(1);
11344 SDValue EltNo = N->getOperand(2);
11347 // If the inserted element is an UNDEF, just use the input vector.
11348 if (InVal.getOpcode() == ISD::UNDEF)
11351 EVT VT = InVec.getValueType();
11353 // If we can't generate a legal BUILD_VECTOR, exit
11354 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11357 // Check that we know which element is being inserted
11358 if (!isa<ConstantSDNode>(EltNo))
11360 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11362 // Canonicalize insert_vector_elt dag nodes.
11364 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11365 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11367 // Do this only if the child insert_vector node has one use; also
11368 // do this only if indices are both constants and Idx1 < Idx0.
11369 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11370 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11371 unsigned OtherElt =
11372 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11373 if (Elt < OtherElt) {
11375 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11376 InVec.getOperand(0), InVal, EltNo);
11377 AddToWorklist(NewOp.getNode());
11378 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11379 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11383 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11384 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11385 // vector elements.
11386 SmallVector<SDValue, 8> Ops;
11387 // Do not combine these two vectors if the output vector will not replace
11388 // the input vector.
11389 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11390 Ops.append(InVec.getNode()->op_begin(),
11391 InVec.getNode()->op_end());
11392 } else if (InVec.getOpcode() == ISD::UNDEF) {
11393 unsigned NElts = VT.getVectorNumElements();
11394 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11399 // Insert the element
11400 if (Elt < Ops.size()) {
11401 // All the operands of BUILD_VECTOR must have the same type;
11402 // we enforce that here.
11403 EVT OpVT = Ops[0].getValueType();
11404 if (InVal.getValueType() != OpVT)
11405 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11406 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11407 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11411 // Return the new vector
11412 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11415 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11416 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11417 EVT ResultVT = EVE->getValueType(0);
11418 EVT VecEltVT = InVecVT.getVectorElementType();
11419 unsigned Align = OriginalLoad->getAlignment();
11420 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11421 VecEltVT.getTypeForEVT(*DAG.getContext()));
11423 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11428 SDValue NewPtr = OriginalLoad->getBasePtr();
11430 EVT PtrType = NewPtr.getValueType();
11431 MachinePointerInfo MPI;
11433 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11434 int Elt = ConstEltNo->getZExtValue();
11435 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11436 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11437 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11439 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11440 Offset = DAG.getNode(
11441 ISD::MUL, DL, PtrType, Offset,
11442 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11443 MPI = OriginalLoad->getPointerInfo();
11445 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11447 // The replacement we need to do here is a little tricky: we need to
11448 // replace an extractelement of a load with a load.
11449 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11450 // Note that this replacement assumes that the extractvalue is the only
11451 // use of the load; that's okay because we don't want to perform this
11452 // transformation in other cases anyway.
11455 if (ResultVT.bitsGT(VecEltVT)) {
11456 // If the result type of vextract is wider than the load, then issue an
11457 // extending load instead.
11458 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11462 Load = DAG.getExtLoad(
11463 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11464 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11465 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11466 Chain = Load.getValue(1);
11468 Load = DAG.getLoad(
11469 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11470 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11471 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11472 Chain = Load.getValue(1);
11473 if (ResultVT.bitsLT(VecEltVT))
11474 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11476 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11478 WorklistRemover DeadNodes(*this);
11479 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11480 SDValue To[] = { Load, Chain };
11481 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11482 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11483 // worklist explicitly as well.
11484 AddToWorklist(Load.getNode());
11485 AddUsersToWorklist(Load.getNode()); // Add users too
11486 // Make sure to revisit this node to clean it up; it will usually be dead.
11487 AddToWorklist(EVE);
11489 return SDValue(EVE, 0);
11492 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11493 // (vextract (scalar_to_vector val, 0) -> val
11494 SDValue InVec = N->getOperand(0);
11495 EVT VT = InVec.getValueType();
11496 EVT NVT = N->getValueType(0);
11498 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11499 // Check if the result type doesn't match the inserted element type. A
11500 // SCALAR_TO_VECTOR may truncate the inserted element and the
11501 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11502 SDValue InOp = InVec.getOperand(0);
11503 if (InOp.getValueType() != NVT) {
11504 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11505 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11510 SDValue EltNo = N->getOperand(1);
11511 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11513 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11514 // We only perform this optimization before the op legalization phase because
11515 // we may introduce new vector instructions which are not backed by TD
11516 // patterns. For example on AVX, extracting elements from a wide vector
11517 // without using extract_subvector. However, if we can find an underlying
11518 // scalar value, then we can always use that.
11519 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11521 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11522 int NumElem = VT.getVectorNumElements();
11523 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11524 // Find the new index to extract from.
11525 int OrigElt = SVOp->getMaskElt(Elt);
11527 // Extracting an undef index is undef.
11529 return DAG.getUNDEF(NVT);
11531 // Select the right vector half to extract from.
11533 if (OrigElt < NumElem) {
11534 SVInVec = InVec->getOperand(0);
11536 SVInVec = InVec->getOperand(1);
11537 OrigElt -= NumElem;
11540 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11541 SDValue InOp = SVInVec.getOperand(OrigElt);
11542 if (InOp.getValueType() != NVT) {
11543 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11544 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11550 // FIXME: We should handle recursing on other vector shuffles and
11551 // scalar_to_vector here as well.
11553 if (!LegalOperations) {
11554 EVT IndexTy = TLI.getVectorIdxTy();
11555 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11556 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11560 bool BCNumEltsChanged = false;
11561 EVT ExtVT = VT.getVectorElementType();
11564 // If the result of load has to be truncated, then it's not necessarily
11566 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11569 if (InVec.getOpcode() == ISD::BITCAST) {
11570 // Don't duplicate a load with other uses.
11571 if (!InVec.hasOneUse())
11574 EVT BCVT = InVec.getOperand(0).getValueType();
11575 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11577 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11578 BCNumEltsChanged = true;
11579 InVec = InVec.getOperand(0);
11580 ExtVT = BCVT.getVectorElementType();
11583 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11584 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11585 ISD::isNormalLoad(InVec.getNode()) &&
11586 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11587 SDValue Index = N->getOperand(1);
11588 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11589 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11593 // Perform only after legalization to ensure build_vector / vector_shuffle
11594 // optimizations have already been done.
11595 if (!LegalOperations) return SDValue();
11597 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11598 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11599 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11602 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11604 LoadSDNode *LN0 = nullptr;
11605 const ShuffleVectorSDNode *SVN = nullptr;
11606 if (ISD::isNormalLoad(InVec.getNode())) {
11607 LN0 = cast<LoadSDNode>(InVec);
11608 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11609 InVec.getOperand(0).getValueType() == ExtVT &&
11610 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11611 // Don't duplicate a load with other uses.
11612 if (!InVec.hasOneUse())
11615 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11616 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11617 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11619 // (load $addr+1*size)
11621 // Don't duplicate a load with other uses.
11622 if (!InVec.hasOneUse())
11625 // If the bit convert changed the number of elements, it is unsafe
11626 // to examine the mask.
11627 if (BCNumEltsChanged)
11630 // Select the input vector, guarding against out of range extract vector.
11631 unsigned NumElems = VT.getVectorNumElements();
11632 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11633 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11635 if (InVec.getOpcode() == ISD::BITCAST) {
11636 // Don't duplicate a load with other uses.
11637 if (!InVec.hasOneUse())
11640 InVec = InVec.getOperand(0);
11642 if (ISD::isNormalLoad(InVec.getNode())) {
11643 LN0 = cast<LoadSDNode>(InVec);
11644 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11645 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11649 // Make sure we found a non-volatile load and the extractelement is
11651 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11654 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11656 return DAG.getUNDEF(LVT);
11658 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11664 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11665 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11666 // We perform this optimization post type-legalization because
11667 // the type-legalizer often scalarizes integer-promoted vectors.
11668 // Performing this optimization before may create bit-casts which
11669 // will be type-legalized to complex code sequences.
11670 // We perform this optimization only before the operation legalizer because we
11671 // may introduce illegal operations.
11672 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11675 unsigned NumInScalars = N->getNumOperands();
11677 EVT VT = N->getValueType(0);
11679 // Check to see if this is a BUILD_VECTOR of a bunch of values
11680 // which come from any_extend or zero_extend nodes. If so, we can create
11681 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11682 // optimizations. We do not handle sign-extend because we can't fill the sign
11684 EVT SourceType = MVT::Other;
11685 bool AllAnyExt = true;
11687 for (unsigned i = 0; i != NumInScalars; ++i) {
11688 SDValue In = N->getOperand(i);
11689 // Ignore undef inputs.
11690 if (In.getOpcode() == ISD::UNDEF) continue;
11692 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11693 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11695 // Abort if the element is not an extension.
11696 if (!ZeroExt && !AnyExt) {
11697 SourceType = MVT::Other;
11701 // The input is a ZeroExt or AnyExt. Check the original type.
11702 EVT InTy = In.getOperand(0).getValueType();
11704 // Check that all of the widened source types are the same.
11705 if (SourceType == MVT::Other)
11708 else if (InTy != SourceType) {
11709 // Multiple income types. Abort.
11710 SourceType = MVT::Other;
11714 // Check if all of the extends are ANY_EXTENDs.
11715 AllAnyExt &= AnyExt;
11718 // In order to have valid types, all of the inputs must be extended from the
11719 // same source type and all of the inputs must be any or zero extend.
11720 // Scalar sizes must be a power of two.
11721 EVT OutScalarTy = VT.getScalarType();
11722 bool ValidTypes = SourceType != MVT::Other &&
11723 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11724 isPowerOf2_32(SourceType.getSizeInBits());
11726 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11727 // turn into a single shuffle instruction.
11731 bool isLE = TLI.isLittleEndian();
11732 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11733 assert(ElemRatio > 1 && "Invalid element size ratio");
11734 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11735 DAG.getConstant(0, SDLoc(N), SourceType);
11737 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11738 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11740 // Populate the new build_vector
11741 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11742 SDValue Cast = N->getOperand(i);
11743 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11744 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11745 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11747 if (Cast.getOpcode() == ISD::UNDEF)
11748 In = DAG.getUNDEF(SourceType);
11750 In = Cast->getOperand(0);
11751 unsigned Index = isLE ? (i * ElemRatio) :
11752 (i * ElemRatio + (ElemRatio - 1));
11754 assert(Index < Ops.size() && "Invalid index");
11758 // The type of the new BUILD_VECTOR node.
11759 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11760 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11761 "Invalid vector size");
11762 // Check if the new vector type is legal.
11763 if (!isTypeLegal(VecVT)) return SDValue();
11765 // Make the new BUILD_VECTOR.
11766 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11768 // The new BUILD_VECTOR node has the potential to be further optimized.
11769 AddToWorklist(BV.getNode());
11770 // Bitcast to the desired type.
11771 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11774 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11775 EVT VT = N->getValueType(0);
11777 unsigned NumInScalars = N->getNumOperands();
11780 EVT SrcVT = MVT::Other;
11781 unsigned Opcode = ISD::DELETED_NODE;
11782 unsigned NumDefs = 0;
11784 for (unsigned i = 0; i != NumInScalars; ++i) {
11785 SDValue In = N->getOperand(i);
11786 unsigned Opc = In.getOpcode();
11788 if (Opc == ISD::UNDEF)
11791 // If all scalar values are floats and converted from integers.
11792 if (Opcode == ISD::DELETED_NODE &&
11793 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11800 EVT InVT = In.getOperand(0).getValueType();
11802 // If all scalar values are typed differently, bail out. It's chosen to
11803 // simplify BUILD_VECTOR of integer types.
11804 if (SrcVT == MVT::Other)
11811 // If the vector has just one element defined, it's not worth to fold it into
11812 // a vectorized one.
11816 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11817 && "Should only handle conversion from integer to float.");
11818 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11820 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11822 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11825 // Just because the floating-point vector type is legal does not necessarily
11826 // mean that the corresponding integer vector type is.
11827 if (!isTypeLegal(NVT))
11830 SmallVector<SDValue, 8> Opnds;
11831 for (unsigned i = 0; i != NumInScalars; ++i) {
11832 SDValue In = N->getOperand(i);
11834 if (In.getOpcode() == ISD::UNDEF)
11835 Opnds.push_back(DAG.getUNDEF(SrcVT));
11837 Opnds.push_back(In.getOperand(0));
11839 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11840 AddToWorklist(BV.getNode());
11842 return DAG.getNode(Opcode, dl, VT, BV);
11845 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11846 unsigned NumInScalars = N->getNumOperands();
11848 EVT VT = N->getValueType(0);
11850 // A vector built entirely of undefs is undef.
11851 if (ISD::allOperandsUndef(N))
11852 return DAG.getUNDEF(VT);
11854 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11857 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11860 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11861 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11862 // at most two distinct vectors, turn this into a shuffle node.
11864 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11865 if (!isTypeLegal(VT))
11868 // May only combine to shuffle after legalize if shuffle is legal.
11869 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11872 SDValue VecIn1, VecIn2;
11873 bool UsesZeroVector = false;
11874 for (unsigned i = 0; i != NumInScalars; ++i) {
11875 SDValue Op = N->getOperand(i);
11876 // Ignore undef inputs.
11877 if (Op.getOpcode() == ISD::UNDEF) continue;
11879 // See if we can combine this build_vector into a blend with a zero vector.
11880 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11881 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11882 (Op.getOpcode() == ISD::ConstantFP &&
11883 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11884 UsesZeroVector = true;
11888 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11889 // constant index, bail out.
11890 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11891 !isa<ConstantSDNode>(Op.getOperand(1))) {
11892 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11896 // We allow up to two distinct input vectors.
11897 SDValue ExtractedFromVec = Op.getOperand(0);
11898 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11901 if (!VecIn1.getNode()) {
11902 VecIn1 = ExtractedFromVec;
11903 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11904 VecIn2 = ExtractedFromVec;
11906 // Too many inputs.
11907 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11912 // If everything is good, we can make a shuffle operation.
11913 if (VecIn1.getNode()) {
11914 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11915 SmallVector<int, 8> Mask;
11916 for (unsigned i = 0; i != NumInScalars; ++i) {
11917 unsigned Opcode = N->getOperand(i).getOpcode();
11918 if (Opcode == ISD::UNDEF) {
11919 Mask.push_back(-1);
11923 // Operands can also be zero.
11924 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11925 assert(UsesZeroVector &&
11926 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11927 "Unexpected node found!");
11928 Mask.push_back(NumInScalars+i);
11932 // If extracting from the first vector, just use the index directly.
11933 SDValue Extract = N->getOperand(i);
11934 SDValue ExtVal = Extract.getOperand(1);
11935 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11936 if (Extract.getOperand(0) == VecIn1) {
11937 Mask.push_back(ExtIndex);
11941 // Otherwise, use InIdx + InputVecSize
11942 Mask.push_back(InNumElements + ExtIndex);
11945 // Avoid introducing illegal shuffles with zero.
11946 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11949 // We can't generate a shuffle node with mismatched input and output types.
11950 // Attempt to transform a single input vector to the correct type.
11951 if ((VT != VecIn1.getValueType())) {
11952 // If the input vector type has a different base type to the output
11953 // vector type, bail out.
11954 EVT VTElemType = VT.getVectorElementType();
11955 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11956 (VecIn2.getNode() &&
11957 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11960 // If the input vector is too small, widen it.
11961 // We only support widening of vectors which are half the size of the
11962 // output registers. For example XMM->YMM widening on X86 with AVX.
11963 EVT VecInT = VecIn1.getValueType();
11964 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11965 // If we only have one small input, widen it by adding undef values.
11966 if (!VecIn2.getNode())
11967 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11968 DAG.getUNDEF(VecIn1.getValueType()));
11969 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11970 // If we have two small inputs of the same type, try to concat them.
11971 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11972 VecIn2 = SDValue(nullptr, 0);
11975 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11976 // If the input vector is too large, try to split it.
11977 // We don't support having two input vectors that are too large.
11978 // If the zero vector was used, we can not split the vector,
11979 // since we'd need 3 inputs.
11980 if (UsesZeroVector || VecIn2.getNode())
11983 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11986 // Try to replace VecIn1 with two extract_subvectors
11987 // No need to update the masks, they should still be correct.
11988 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11989 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11990 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11991 DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11996 if (UsesZeroVector)
11997 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11998 DAG.getConstantFP(0.0, dl, VT);
12000 // If VecIn2 is unused then change it to undef.
12001 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12003 // Check that we were able to transform all incoming values to the same
12005 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12006 VecIn1.getValueType() != VT)
12009 // Return the new VECTOR_SHUFFLE node.
12013 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12019 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12020 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12021 EVT OpVT = N->getOperand(0).getValueType();
12023 // If the operands are legal vectors, leave them alone.
12024 if (TLI.isTypeLegal(OpVT))
12028 EVT VT = N->getValueType(0);
12029 SmallVector<SDValue, 8> Ops;
12031 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12032 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12034 // Keep track of what we encounter.
12035 bool AnyInteger = false;
12036 bool AnyFP = false;
12037 for (const SDValue &Op : N->ops()) {
12038 if (ISD::BITCAST == Op.getOpcode() &&
12039 !Op.getOperand(0).getValueType().isVector())
12040 Ops.push_back(Op.getOperand(0));
12041 else if (ISD::UNDEF == Op.getOpcode())
12042 Ops.push_back(ScalarUndef);
12046 // Note whether we encounter an integer or floating point scalar.
12047 // If it's neither, bail out, it could be something weird like x86mmx.
12048 EVT LastOpVT = Ops.back().getValueType();
12049 if (LastOpVT.isFloatingPoint())
12051 else if (LastOpVT.isInteger())
12057 // If any of the operands is a floating point scalar bitcast to a vector,
12058 // use floating point types throughout, and bitcast everything.
12059 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12061 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12062 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12064 for (SDValue &Op : Ops) {
12065 if (Op.getValueType() == SVT)
12067 if (Op.getOpcode() == ISD::UNDEF)
12070 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12075 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12076 VT.getSizeInBits() / SVT.getSizeInBits());
12077 return DAG.getNode(ISD::BITCAST, DL, VT,
12078 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12081 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12082 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12083 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
12084 // inputs come from at most two distinct vectors, turn this into a shuffle
12087 // If we only have one input vector, we don't need to do any concatenation.
12088 if (N->getNumOperands() == 1)
12089 return N->getOperand(0);
12091 // Check if all of the operands are undefs.
12092 EVT VT = N->getValueType(0);
12093 if (ISD::allOperandsUndef(N))
12094 return DAG.getUNDEF(VT);
12096 // Optimize concat_vectors where all but the first of the vectors are undef.
12097 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12098 return Op.getOpcode() == ISD::UNDEF;
12100 SDValue In = N->getOperand(0);
12101 assert(In.getValueType().isVector() && "Must concat vectors");
12103 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12104 if (In->getOpcode() == ISD::BITCAST &&
12105 !In->getOperand(0)->getValueType(0).isVector()) {
12106 SDValue Scalar = In->getOperand(0);
12108 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12109 // look through the trunc so we can still do the transform:
12110 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12111 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12112 !TLI.isTypeLegal(Scalar.getValueType()) &&
12113 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12114 Scalar = Scalar->getOperand(0);
12116 EVT SclTy = Scalar->getValueType(0);
12118 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12121 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12122 VT.getSizeInBits() / SclTy.getSizeInBits());
12123 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12126 SDLoc dl = SDLoc(N);
12127 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12128 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12132 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12133 // We have already tested above for an UNDEF only concatenation.
12134 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12135 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12136 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12137 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12139 bool AllBuildVectorsOrUndefs =
12140 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12141 if (AllBuildVectorsOrUndefs) {
12142 SmallVector<SDValue, 8> Opnds;
12143 EVT SVT = VT.getScalarType();
12146 if (!SVT.isFloatingPoint()) {
12147 // If BUILD_VECTOR are from built from integer, they may have different
12148 // operand types. Get the smallest type and truncate all operands to it.
12149 bool FoundMinVT = false;
12150 for (const SDValue &Op : N->ops())
12151 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12152 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12153 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12156 assert(FoundMinVT && "Concat vector type mismatch");
12159 for (const SDValue &Op : N->ops()) {
12160 EVT OpVT = Op.getValueType();
12161 unsigned NumElts = OpVT.getVectorNumElements();
12163 if (ISD::UNDEF == Op.getOpcode())
12164 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12166 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12167 if (SVT.isFloatingPoint()) {
12168 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12169 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12171 for (unsigned i = 0; i != NumElts; ++i)
12173 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12178 assert(VT.getVectorNumElements() == Opnds.size() &&
12179 "Concat vector type mismatch");
12180 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12183 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12184 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12187 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12188 // nodes often generate nop CONCAT_VECTOR nodes.
12189 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12190 // place the incoming vectors at the exact same location.
12191 SDValue SingleSource = SDValue();
12192 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12194 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12195 SDValue Op = N->getOperand(i);
12197 if (Op.getOpcode() == ISD::UNDEF)
12200 // Check if this is the identity extract:
12201 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12204 // Find the single incoming vector for the extract_subvector.
12205 if (SingleSource.getNode()) {
12206 if (Op.getOperand(0) != SingleSource)
12209 SingleSource = Op.getOperand(0);
12211 // Check the source type is the same as the type of the result.
12212 // If not, this concat may extend the vector, so we can not
12213 // optimize it away.
12214 if (SingleSource.getValueType() != N->getValueType(0))
12218 unsigned IdentityIndex = i * PartNumElem;
12219 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12220 // The extract index must be constant.
12224 // Check that we are reading from the identity index.
12225 if (CS->getZExtValue() != IdentityIndex)
12229 if (SingleSource.getNode())
12230 return SingleSource;
12235 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12236 EVT NVT = N->getValueType(0);
12237 SDValue V = N->getOperand(0);
12239 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12241 // (extract_subvec (concat V1, V2, ...), i)
12244 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12246 if (V->getOperand(0).getValueType() != NVT)
12248 unsigned Idx = N->getConstantOperandVal(1);
12249 unsigned NumElems = NVT.getVectorNumElements();
12250 assert((Idx % NumElems) == 0 &&
12251 "IDX in concat is not a multiple of the result vector length.");
12252 return V->getOperand(Idx / NumElems);
12256 if (V->getOpcode() == ISD::BITCAST)
12257 V = V.getOperand(0);
12259 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12261 // Handle only simple case where vector being inserted and vector
12262 // being extracted are of same type, and are half size of larger vectors.
12263 EVT BigVT = V->getOperand(0).getValueType();
12264 EVT SmallVT = V->getOperand(1).getValueType();
12265 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12268 // Only handle cases where both indexes are constants with the same type.
12269 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12270 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12272 if (InsIdx && ExtIdx &&
12273 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12274 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12276 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12278 // indices are equal or bit offsets are equal => V1
12279 // otherwise => (extract_subvec V1, ExtIdx)
12280 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12281 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12282 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12283 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12284 DAG.getNode(ISD::BITCAST, dl,
12285 N->getOperand(0).getValueType(),
12286 V->getOperand(0)), N->getOperand(1));
12293 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12294 SDValue V, SelectionDAG &DAG) {
12296 EVT VT = V.getValueType();
12298 switch (V.getOpcode()) {
12302 case ISD::CONCAT_VECTORS: {
12303 EVT OpVT = V->getOperand(0).getValueType();
12304 int OpSize = OpVT.getVectorNumElements();
12305 SmallBitVector OpUsedElements(OpSize, false);
12306 bool FoundSimplification = false;
12307 SmallVector<SDValue, 4> NewOps;
12308 NewOps.reserve(V->getNumOperands());
12309 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12310 SDValue Op = V->getOperand(i);
12311 bool OpUsed = false;
12312 for (int j = 0; j < OpSize; ++j)
12313 if (UsedElements[i * OpSize + j]) {
12314 OpUsedElements[j] = true;
12318 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12319 : DAG.getUNDEF(OpVT));
12320 FoundSimplification |= Op == NewOps.back();
12321 OpUsedElements.reset();
12323 if (FoundSimplification)
12324 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12328 case ISD::INSERT_SUBVECTOR: {
12329 SDValue BaseV = V->getOperand(0);
12330 SDValue SubV = V->getOperand(1);
12331 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12335 int SubSize = SubV.getValueType().getVectorNumElements();
12336 int Idx = IdxN->getZExtValue();
12337 bool SubVectorUsed = false;
12338 SmallBitVector SubUsedElements(SubSize, false);
12339 for (int i = 0; i < SubSize; ++i)
12340 if (UsedElements[i + Idx]) {
12341 SubVectorUsed = true;
12342 SubUsedElements[i] = true;
12343 UsedElements[i + Idx] = false;
12346 // Now recurse on both the base and sub vectors.
12347 SDValue SimplifiedSubV =
12349 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12350 : DAG.getUNDEF(SubV.getValueType());
12351 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12352 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12353 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12354 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12360 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12361 SDValue N1, SelectionDAG &DAG) {
12362 EVT VT = SVN->getValueType(0);
12363 int NumElts = VT.getVectorNumElements();
12364 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12365 for (int M : SVN->getMask())
12366 if (M >= 0 && M < NumElts)
12367 N0UsedElements[M] = true;
12368 else if (M >= NumElts)
12369 N1UsedElements[M - NumElts] = true;
12371 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12372 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12373 if (S0 == N0 && S1 == N1)
12376 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12379 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12380 // or turn a shuffle of a single concat into simpler shuffle then concat.
12381 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12382 EVT VT = N->getValueType(0);
12383 unsigned NumElts = VT.getVectorNumElements();
12385 SDValue N0 = N->getOperand(0);
12386 SDValue N1 = N->getOperand(1);
12387 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12389 SmallVector<SDValue, 4> Ops;
12390 EVT ConcatVT = N0.getOperand(0).getValueType();
12391 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12392 unsigned NumConcats = NumElts / NumElemsPerConcat;
12394 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12395 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12396 // half vector elements.
12397 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12398 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12399 SVN->getMask().end(), [](int i) { return i == -1; })) {
12400 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12401 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12402 N1 = DAG.getUNDEF(ConcatVT);
12403 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12406 // Look at every vector that's inserted. We're looking for exact
12407 // subvector-sized copies from a concatenated vector
12408 for (unsigned I = 0; I != NumConcats; ++I) {
12409 // Make sure we're dealing with a copy.
12410 unsigned Begin = I * NumElemsPerConcat;
12411 bool AllUndef = true, NoUndef = true;
12412 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12413 if (SVN->getMaskElt(J) >= 0)
12420 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12423 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12424 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12427 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12428 if (FirstElt < N0.getNumOperands())
12429 Ops.push_back(N0.getOperand(FirstElt));
12431 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12433 } else if (AllUndef) {
12434 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12435 } else { // Mixed with general masks and undefs, can't do optimization.
12440 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12443 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12444 EVT VT = N->getValueType(0);
12445 unsigned NumElts = VT.getVectorNumElements();
12447 SDValue N0 = N->getOperand(0);
12448 SDValue N1 = N->getOperand(1);
12450 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12452 // Canonicalize shuffle undef, undef -> undef
12453 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12454 return DAG.getUNDEF(VT);
12456 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12458 // Canonicalize shuffle v, v -> v, undef
12460 SmallVector<int, 8> NewMask;
12461 for (unsigned i = 0; i != NumElts; ++i) {
12462 int Idx = SVN->getMaskElt(i);
12463 if (Idx >= (int)NumElts) Idx -= NumElts;
12464 NewMask.push_back(Idx);
12466 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12470 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12471 if (N0.getOpcode() == ISD::UNDEF) {
12472 SmallVector<int, 8> NewMask;
12473 for (unsigned i = 0; i != NumElts; ++i) {
12474 int Idx = SVN->getMaskElt(i);
12476 if (Idx >= (int)NumElts)
12479 Idx = -1; // remove reference to lhs
12481 NewMask.push_back(Idx);
12483 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12487 // Remove references to rhs if it is undef
12488 if (N1.getOpcode() == ISD::UNDEF) {
12489 bool Changed = false;
12490 SmallVector<int, 8> NewMask;
12491 for (unsigned i = 0; i != NumElts; ++i) {
12492 int Idx = SVN->getMaskElt(i);
12493 if (Idx >= (int)NumElts) {
12497 NewMask.push_back(Idx);
12500 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12503 // If it is a splat, check if the argument vector is another splat or a
12505 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12506 SDNode *V = N0.getNode();
12508 // If this is a bit convert that changes the element type of the vector but
12509 // not the number of vector elements, look through it. Be careful not to
12510 // look though conversions that change things like v4f32 to v2f64.
12511 if (V->getOpcode() == ISD::BITCAST) {
12512 SDValue ConvInput = V->getOperand(0);
12513 if (ConvInput.getValueType().isVector() &&
12514 ConvInput.getValueType().getVectorNumElements() == NumElts)
12515 V = ConvInput.getNode();
12518 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12519 assert(V->getNumOperands() == NumElts &&
12520 "BUILD_VECTOR has wrong number of operands");
12522 bool AllSame = true;
12523 for (unsigned i = 0; i != NumElts; ++i) {
12524 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12525 Base = V->getOperand(i);
12529 // Splat of <u, u, u, u>, return <u, u, u, u>
12530 if (!Base.getNode())
12532 for (unsigned i = 0; i != NumElts; ++i) {
12533 if (V->getOperand(i) != Base) {
12538 // Splat of <x, x, x, x>, return <x, x, x, x>
12542 // Canonicalize any other splat as a build_vector.
12543 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12544 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12545 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12546 V->getValueType(0), Ops);
12548 // We may have jumped through bitcasts, so the type of the
12549 // BUILD_VECTOR may not match the type of the shuffle.
12550 if (V->getValueType(0) != VT)
12551 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12556 // There are various patterns used to build up a vector from smaller vectors,
12557 // subvectors, or elements. Scan chains of these and replace unused insertions
12558 // or components with undef.
12559 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12562 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12563 Level < AfterLegalizeVectorOps &&
12564 (N1.getOpcode() == ISD::UNDEF ||
12565 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12566 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12567 SDValue V = partitionShuffleOfConcats(N, DAG);
12573 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12574 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12575 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12576 SmallVector<SDValue, 8> Ops;
12577 for (int M : SVN->getMask()) {
12578 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12580 int Idx = M % NumElts;
12581 SDValue &S = (M < (int)NumElts ? N0 : N1);
12582 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12583 Op = S.getOperand(Idx);
12584 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12586 Op = S.getOperand(0);
12588 // Operand can't be combined - bail out.
12594 if (Ops.size() == VT.getVectorNumElements()) {
12595 // BUILD_VECTOR requires all inputs to be of the same type, find the
12596 // maximum type and extend them all.
12597 EVT SVT = VT.getScalarType();
12598 if (SVT.isInteger())
12599 for (SDValue &Op : Ops)
12600 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12601 if (SVT != VT.getScalarType())
12602 for (SDValue &Op : Ops)
12603 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12604 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12605 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12606 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12610 // If this shuffle only has a single input that is a bitcasted shuffle,
12611 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12612 // back to their original types.
12613 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12614 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12615 TLI.isTypeLegal(VT)) {
12617 // Peek through the bitcast only if there is one user.
12619 while (BC0.getOpcode() == ISD::BITCAST) {
12620 if (!BC0.hasOneUse())
12622 BC0 = BC0.getOperand(0);
12625 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12627 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12629 SmallVector<int, 8> NewMask;
12631 for (int s = 0; s != Scale; ++s)
12632 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12636 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12637 EVT SVT = VT.getScalarType();
12638 EVT InnerVT = BC0->getValueType(0);
12639 EVT InnerSVT = InnerVT.getScalarType();
12641 // Determine which shuffle works with the smaller scalar type.
12642 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12643 EVT ScaleSVT = ScaleVT.getScalarType();
12645 if (TLI.isTypeLegal(ScaleVT) &&
12646 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12647 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12649 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12650 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12652 // Scale the shuffle masks to the smaller scalar type.
12653 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12654 SmallVector<int, 8> InnerMask =
12655 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12656 SmallVector<int, 8> OuterMask =
12657 ScaleShuffleMask(SVN->getMask(), OuterScale);
12659 // Merge the shuffle masks.
12660 SmallVector<int, 8> NewMask;
12661 for (int M : OuterMask)
12662 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12664 // Test for shuffle mask legality over both commutations.
12665 SDValue SV0 = BC0->getOperand(0);
12666 SDValue SV1 = BC0->getOperand(1);
12667 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12669 std::swap(SV0, SV1);
12670 ShuffleVectorSDNode::commuteMask(NewMask);
12671 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12675 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12676 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12677 return DAG.getNode(
12678 ISD::BITCAST, SDLoc(N), VT,
12679 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12685 // Canonicalize shuffles according to rules:
12686 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12687 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12688 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12689 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12690 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12691 TLI.isTypeLegal(VT)) {
12692 // The incoming shuffle must be of the same type as the result of the
12693 // current shuffle.
12694 assert(N1->getOperand(0).getValueType() == VT &&
12695 "Shuffle types don't match");
12697 SDValue SV0 = N1->getOperand(0);
12698 SDValue SV1 = N1->getOperand(1);
12699 bool HasSameOp0 = N0 == SV0;
12700 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12701 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12702 // Commute the operands of this shuffle so that next rule
12704 return DAG.getCommutedVectorShuffle(*SVN);
12707 // Try to fold according to rules:
12708 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12709 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12710 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12711 // Don't try to fold shuffles with illegal type.
12712 // Only fold if this shuffle is the only user of the other shuffle.
12713 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12714 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12715 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12717 // The incoming shuffle must be of the same type as the result of the
12718 // current shuffle.
12719 assert(OtherSV->getOperand(0).getValueType() == VT &&
12720 "Shuffle types don't match");
12723 SmallVector<int, 4> Mask;
12724 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12725 // operand, and SV1 as the second operand.
12726 for (unsigned i = 0; i != NumElts; ++i) {
12727 int Idx = SVN->getMaskElt(i);
12729 // Propagate Undef.
12730 Mask.push_back(Idx);
12734 SDValue CurrentVec;
12735 if (Idx < (int)NumElts) {
12736 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12737 // shuffle mask to identify which vector is actually referenced.
12738 Idx = OtherSV->getMaskElt(Idx);
12740 // Propagate Undef.
12741 Mask.push_back(Idx);
12745 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12746 : OtherSV->getOperand(1);
12748 // This shuffle index references an element within N1.
12752 // Simple case where 'CurrentVec' is UNDEF.
12753 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12754 Mask.push_back(-1);
12758 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12759 // will be the first or second operand of the combined shuffle.
12760 Idx = Idx % NumElts;
12761 if (!SV0.getNode() || SV0 == CurrentVec) {
12762 // Ok. CurrentVec is the left hand side.
12763 // Update the mask accordingly.
12765 Mask.push_back(Idx);
12769 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12770 if (SV1.getNode() && SV1 != CurrentVec)
12773 // Ok. CurrentVec is the right hand side.
12774 // Update the mask accordingly.
12776 Mask.push_back(Idx + NumElts);
12779 // Check if all indices in Mask are Undef. In case, propagate Undef.
12780 bool isUndefMask = true;
12781 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12782 isUndefMask &= Mask[i] < 0;
12785 return DAG.getUNDEF(VT);
12787 if (!SV0.getNode())
12788 SV0 = DAG.getUNDEF(VT);
12789 if (!SV1.getNode())
12790 SV1 = DAG.getUNDEF(VT);
12792 // Avoid introducing shuffles with illegal mask.
12793 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12794 ShuffleVectorSDNode::commuteMask(Mask);
12796 if (!TLI.isShuffleMaskLegal(Mask, VT))
12799 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12800 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12801 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12802 std::swap(SV0, SV1);
12805 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12806 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12807 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12808 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12814 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12815 SDValue InVal = N->getOperand(0);
12816 EVT VT = N->getValueType(0);
12818 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12819 // with a VECTOR_SHUFFLE.
12820 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12821 SDValue InVec = InVal->getOperand(0);
12822 SDValue EltNo = InVal->getOperand(1);
12824 // FIXME: We could support implicit truncation if the shuffle can be
12825 // scaled to a smaller vector scalar type.
12826 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12827 if (C0 && VT == InVec.getValueType() &&
12828 VT.getScalarType() == InVal.getValueType()) {
12829 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12830 int Elt = C0->getZExtValue();
12833 if (TLI.isShuffleMaskLegal(NewMask, VT))
12834 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12842 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12843 SDValue N0 = N->getOperand(0);
12844 SDValue N2 = N->getOperand(2);
12846 // If the input vector is a concatenation, and the insert replaces
12847 // one of the halves, we can optimize into a single concat_vectors.
12848 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12849 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12850 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12851 EVT VT = N->getValueType(0);
12853 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12854 // (concat_vectors Z, Y)
12856 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12857 N->getOperand(1), N0.getOperand(1));
12859 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12860 // (concat_vectors X, Z)
12861 if (InsIdx == VT.getVectorNumElements()/2)
12862 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12863 N0.getOperand(0), N->getOperand(1));
12869 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12870 SDValue N0 = N->getOperand(0);
12872 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12873 if (N0->getOpcode() == ISD::FP16_TO_FP)
12874 return N0->getOperand(0);
12879 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12880 /// with the destination vector and a zero vector.
12881 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12882 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12883 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12884 EVT VT = N->getValueType(0);
12885 SDValue LHS = N->getOperand(0);
12886 SDValue RHS = N->getOperand(1);
12889 // Make sure we're not running after operation legalization where it
12890 // may have custom lowered the vector shuffles.
12891 if (LegalOperations)
12894 if (N->getOpcode() != ISD::AND)
12897 if (RHS.getOpcode() == ISD::BITCAST)
12898 RHS = RHS.getOperand(0);
12900 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12901 SmallVector<int, 8> Indices;
12902 unsigned NumElts = RHS.getNumOperands();
12904 for (unsigned i = 0; i != NumElts; ++i) {
12905 SDValue Elt = RHS.getOperand(i);
12906 if (!isa<ConstantSDNode>(Elt))
12909 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12910 Indices.push_back(i);
12911 else if (cast<ConstantSDNode>(Elt)->isNullValue())
12912 Indices.push_back(NumElts+i);
12917 // Let's see if the target supports this vector_shuffle.
12918 EVT RVT = RHS.getValueType();
12919 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12922 // Return the new VECTOR_SHUFFLE node.
12923 EVT EltVT = RVT.getVectorElementType();
12924 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12925 DAG.getConstant(0, dl, EltVT));
12926 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12927 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12928 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12929 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12935 /// Visit a binary vector operation, like ADD.
12936 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12937 assert(N->getValueType(0).isVector() &&
12938 "SimplifyVBinOp only works on vectors!");
12940 SDValue LHS = N->getOperand(0);
12941 SDValue RHS = N->getOperand(1);
12943 if (SDValue Shuffle = XformToShuffleWithZero(N))
12946 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12948 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12949 RHS.getOpcode() == ISD::BUILD_VECTOR) {
12950 // Check if both vectors are constants. If not bail out.
12951 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12952 cast<BuildVectorSDNode>(RHS)->isConstant()))
12955 SmallVector<SDValue, 8> Ops;
12956 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12957 SDValue LHSOp = LHS.getOperand(i);
12958 SDValue RHSOp = RHS.getOperand(i);
12960 // Can't fold divide by zero.
12961 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12962 N->getOpcode() == ISD::FDIV) {
12963 if ((RHSOp.getOpcode() == ISD::Constant &&
12964 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12965 (RHSOp.getOpcode() == ISD::ConstantFP &&
12966 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12970 EVT VT = LHSOp.getValueType();
12971 EVT RVT = RHSOp.getValueType();
12973 // Integer BUILD_VECTOR operands may have types larger than the element
12974 // size (e.g., when the element type is not legal). Prior to type
12975 // legalization, the types may not match between the two BUILD_VECTORS.
12976 // Truncate one of the operands to make them match.
12977 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12978 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12980 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12984 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12986 if (FoldOp.getOpcode() != ISD::UNDEF &&
12987 FoldOp.getOpcode() != ISD::Constant &&
12988 FoldOp.getOpcode() != ISD::ConstantFP)
12990 Ops.push_back(FoldOp);
12991 AddToWorklist(FoldOp.getNode());
12994 if (Ops.size() == LHS.getNumOperands())
12995 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12998 // Type legalization might introduce new shuffles in the DAG.
12999 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13000 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13001 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13002 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13003 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13004 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13005 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13006 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13008 if (SVN0->getMask().equals(SVN1->getMask())) {
13009 EVT VT = N->getValueType(0);
13010 SDValue UndefVector = LHS.getOperand(1);
13011 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13012 LHS.getOperand(0), RHS.getOperand(0));
13013 AddUsersToWorklist(N);
13014 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13015 &SVN0->getMask()[0]);
13022 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13023 SDValue N1, SDValue N2){
13024 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13026 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13027 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13029 // If we got a simplified select_cc node back from SimplifySelectCC, then
13030 // break it down into a new SETCC node, and a new SELECT node, and then return
13031 // the SELECT node, since we were called with a SELECT node.
13032 if (SCC.getNode()) {
13033 // Check to see if we got a select_cc back (to turn into setcc/select).
13034 // Otherwise, just return whatever node we got back, like fabs.
13035 if (SCC.getOpcode() == ISD::SELECT_CC) {
13036 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13038 SCC.getOperand(0), SCC.getOperand(1),
13039 SCC.getOperand(4));
13040 AddToWorklist(SETCC.getNode());
13041 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13042 SCC.getOperand(2), SCC.getOperand(3));
13050 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13051 /// being selected between, see if we can simplify the select. Callers of this
13052 /// should assume that TheSelect is deleted if this returns true. As such, they
13053 /// should return the appropriate thing (e.g. the node) back to the top-level of
13054 /// the DAG combiner loop to avoid it being looked at.
13055 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13058 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13059 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13060 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13061 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13062 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13063 SDValue Sqrt = RHS;
13066 const ConstantFPSDNode *NegZero = nullptr;
13068 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13069 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13070 CmpLHS = TheSelect->getOperand(0);
13071 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13073 // SELECT or VSELECT
13074 SDValue Cmp = TheSelect->getOperand(0);
13075 if (Cmp.getOpcode() == ISD::SETCC) {
13076 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13077 CmpLHS = Cmp.getOperand(0);
13078 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13081 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13082 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13083 CC == ISD::SETULT || CC == ISD::SETLT)) {
13084 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13085 CombineTo(TheSelect, Sqrt);
13090 // Cannot simplify select with vector condition
13091 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13093 // If this is a select from two identical things, try to pull the operation
13094 // through the select.
13095 if (LHS.getOpcode() != RHS.getOpcode() ||
13096 !LHS.hasOneUse() || !RHS.hasOneUse())
13099 // If this is a load and the token chain is identical, replace the select
13100 // of two loads with a load through a select of the address to load from.
13101 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13102 // constants have been dropped into the constant pool.
13103 if (LHS.getOpcode() == ISD::LOAD) {
13104 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13105 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13107 // Token chains must be identical.
13108 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13109 // Do not let this transformation reduce the number of volatile loads.
13110 LLD->isVolatile() || RLD->isVolatile() ||
13111 // FIXME: If either is a pre/post inc/dec load,
13112 // we'd need to split out the address adjustment.
13113 LLD->isIndexed() || RLD->isIndexed() ||
13114 // If this is an EXTLOAD, the VT's must match.
13115 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13116 // If this is an EXTLOAD, the kind of extension must match.
13117 (LLD->getExtensionType() != RLD->getExtensionType() &&
13118 // The only exception is if one of the extensions is anyext.
13119 LLD->getExtensionType() != ISD::EXTLOAD &&
13120 RLD->getExtensionType() != ISD::EXTLOAD) ||
13121 // FIXME: this discards src value information. This is
13122 // over-conservative. It would be beneficial to be able to remember
13123 // both potential memory locations. Since we are discarding
13124 // src value info, don't do the transformation if the memory
13125 // locations are not in the default address space.
13126 LLD->getPointerInfo().getAddrSpace() != 0 ||
13127 RLD->getPointerInfo().getAddrSpace() != 0 ||
13128 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13129 LLD->getBasePtr().getValueType()))
13132 // Check that the select condition doesn't reach either load. If so,
13133 // folding this will induce a cycle into the DAG. If not, this is safe to
13134 // xform, so create a select of the addresses.
13136 if (TheSelect->getOpcode() == ISD::SELECT) {
13137 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13138 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13139 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13141 // The loads must not depend on one another.
13142 if (LLD->isPredecessorOf(RLD) ||
13143 RLD->isPredecessorOf(LLD))
13145 Addr = DAG.getSelect(SDLoc(TheSelect),
13146 LLD->getBasePtr().getValueType(),
13147 TheSelect->getOperand(0), LLD->getBasePtr(),
13148 RLD->getBasePtr());
13149 } else { // Otherwise SELECT_CC
13150 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13151 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13153 if ((LLD->hasAnyUseOfValue(1) &&
13154 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13155 (RLD->hasAnyUseOfValue(1) &&
13156 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13159 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13160 LLD->getBasePtr().getValueType(),
13161 TheSelect->getOperand(0),
13162 TheSelect->getOperand(1),
13163 LLD->getBasePtr(), RLD->getBasePtr(),
13164 TheSelect->getOperand(4));
13168 // It is safe to replace the two loads if they have different alignments,
13169 // but the new load must be the minimum (most restrictive) alignment of the
13171 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13172 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13173 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13174 Load = DAG.getLoad(TheSelect->getValueType(0),
13176 // FIXME: Discards pointer and AA info.
13177 LLD->getChain(), Addr, MachinePointerInfo(),
13178 LLD->isVolatile(), LLD->isNonTemporal(),
13179 isInvariant, Alignment);
13181 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13182 RLD->getExtensionType() : LLD->getExtensionType(),
13184 TheSelect->getValueType(0),
13185 // FIXME: Discards pointer and AA info.
13186 LLD->getChain(), Addr, MachinePointerInfo(),
13187 LLD->getMemoryVT(), LLD->isVolatile(),
13188 LLD->isNonTemporal(), isInvariant, Alignment);
13191 // Users of the select now use the result of the load.
13192 CombineTo(TheSelect, Load);
13194 // Users of the old loads now use the new load's chain. We know the
13195 // old-load value is dead now.
13196 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13197 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13204 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13205 /// where 'cond' is the comparison specified by CC.
13206 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13207 SDValue N2, SDValue N3,
13208 ISD::CondCode CC, bool NotExtCompare) {
13209 // (x ? y : y) -> y.
13210 if (N2 == N3) return N2;
13212 EVT VT = N2.getValueType();
13213 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13214 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13215 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
13217 // Determine if the condition we're dealing with is constant
13218 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13219 N0, N1, CC, DL, false);
13220 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13221 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
13223 // fold select_cc true, x, y -> x
13224 if (SCCC && !SCCC->isNullValue())
13226 // fold select_cc false, x, y -> y
13227 if (SCCC && SCCC->isNullValue())
13230 // Check to see if we can simplify the select into an fabs node
13231 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13232 // Allow either -0.0 or 0.0
13233 if (CFP->getValueAPF().isZero()) {
13234 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13235 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13236 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13237 N2 == N3.getOperand(0))
13238 return DAG.getNode(ISD::FABS, DL, VT, N0);
13240 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13241 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13242 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13243 N2.getOperand(0) == N3)
13244 return DAG.getNode(ISD::FABS, DL, VT, N3);
13248 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13249 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13250 // in it. This is a win when the constant is not otherwise available because
13251 // it replaces two constant pool loads with one. We only do this if the FP
13252 // type is known to be legal, because if it isn't, then we are before legalize
13253 // types an we want the other legalization to happen first (e.g. to avoid
13254 // messing with soft float) and if the ConstantFP is not legal, because if
13255 // it is legal, we may not need to store the FP constant in a constant pool.
13256 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13257 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13258 if (TLI.isTypeLegal(N2.getValueType()) &&
13259 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13260 TargetLowering::Legal &&
13261 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13262 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13263 // If both constants have multiple uses, then we won't need to do an
13264 // extra load, they are likely around in registers for other users.
13265 (TV->hasOneUse() || FV->hasOneUse())) {
13266 Constant *Elts[] = {
13267 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13268 const_cast<ConstantFP*>(TV->getConstantFPValue())
13270 Type *FPTy = Elts[0]->getType();
13271 const DataLayout &TD = *TLI.getDataLayout();
13273 // Create a ConstantArray of the two constants.
13274 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13275 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13276 TD.getPrefTypeAlignment(FPTy));
13277 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13279 // Get the offsets to the 0 and 1 element of the array so that we can
13280 // select between them.
13281 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13282 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13283 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13285 SDValue Cond = DAG.getSetCC(DL,
13286 getSetCCResultType(N0.getValueType()),
13288 AddToWorklist(Cond.getNode());
13289 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13291 AddToWorklist(CstOffset.getNode());
13292 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13294 AddToWorklist(CPIdx.getNode());
13295 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13296 MachinePointerInfo::getConstantPool(), false,
13297 false, false, Alignment);
13301 // Check to see if we can perform the "gzip trick", transforming
13302 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13303 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13304 (N1C->isNullValue() || // (a < 0) ? b : 0
13305 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
13306 EVT XType = N0.getValueType();
13307 EVT AType = N2.getValueType();
13308 if (XType.bitsGE(AType)) {
13309 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13310 // single-bit constant.
13311 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13312 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13313 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13314 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13315 getShiftAmountTy(N0.getValueType()));
13316 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13318 AddToWorklist(Shift.getNode());
13320 if (XType.bitsGT(AType)) {
13321 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13322 AddToWorklist(Shift.getNode());
13325 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13328 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13330 DAG.getConstant(XType.getSizeInBits() - 1,
13332 getShiftAmountTy(N0.getValueType())));
13333 AddToWorklist(Shift.getNode());
13335 if (XType.bitsGT(AType)) {
13336 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13337 AddToWorklist(Shift.getNode());
13340 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13344 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13345 // where y is has a single bit set.
13346 // A plaintext description would be, we can turn the SELECT_CC into an AND
13347 // when the condition can be materialized as an all-ones register. Any
13348 // single bit-test can be materialized as an all-ones register with
13349 // shift-left and shift-right-arith.
13350 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13351 N0->getValueType(0) == VT &&
13352 N1C && N1C->isNullValue() &&
13353 N2C && N2C->isNullValue()) {
13354 SDValue AndLHS = N0->getOperand(0);
13355 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13356 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13357 // Shift the tested bit over the sign bit.
13358 APInt AndMask = ConstAndRHS->getAPIntValue();
13360 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13361 getShiftAmountTy(AndLHS.getValueType()));
13362 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13364 // Now arithmetic right shift it all the way over, so the result is either
13365 // all-ones, or zero.
13367 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13368 getShiftAmountTy(Shl.getValueType()));
13369 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13371 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13375 // fold select C, 16, 0 -> shl C, 4
13376 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13377 TLI.getBooleanContents(N0.getValueType()) ==
13378 TargetLowering::ZeroOrOneBooleanContent) {
13380 // If the caller doesn't want us to simplify this into a zext of a compare,
13382 if (NotExtCompare && N2C->getAPIntValue() == 1)
13385 // Get a SetCC of the condition
13386 // NOTE: Don't create a SETCC if it's not legal on this target.
13387 if (!LegalOperations ||
13388 TLI.isOperationLegal(ISD::SETCC,
13389 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13391 // cast from setcc result type to select result type
13393 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13395 if (N2.getValueType().bitsLT(SCC.getValueType()))
13396 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13397 N2.getValueType());
13399 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13400 N2.getValueType(), SCC);
13402 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13403 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13404 N2.getValueType(), SCC);
13407 AddToWorklist(SCC.getNode());
13408 AddToWorklist(Temp.getNode());
13410 if (N2C->getAPIntValue() == 1)
13413 // shl setcc result by log2 n2c
13414 return DAG.getNode(
13415 ISD::SHL, DL, N2.getValueType(), Temp,
13416 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13417 getShiftAmountTy(Temp.getValueType())));
13421 // Check to see if this is the equivalent of setcc
13422 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13423 // otherwise, go ahead with the folds.
13424 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13425 EVT XType = N0.getValueType();
13426 if (!LegalOperations ||
13427 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13428 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13429 if (Res.getValueType() != VT)
13430 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13434 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13435 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13436 (!LegalOperations ||
13437 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13438 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13439 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13440 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13442 getShiftAmountTy(Ctlz.getValueType())));
13444 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13445 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13447 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13448 XType, DAG.getConstant(0, DL, XType), N0);
13449 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13450 return DAG.getNode(ISD::SRL, DL, XType,
13451 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13452 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13453 getShiftAmountTy(XType)));
13455 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13456 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13458 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13459 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13460 getShiftAmountTy(N0.getValueType())));
13461 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13466 // Check to see if this is an integer abs.
13467 // select_cc setg[te] X, 0, X, -X ->
13468 // select_cc setgt X, -1, X, -X ->
13469 // select_cc setl[te] X, 0, -X, X ->
13470 // select_cc setlt X, 1, -X, X ->
13471 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13473 ConstantSDNode *SubC = nullptr;
13474 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13475 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13476 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13477 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13478 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13479 (N1C->isOne() && CC == ISD::SETLT)) &&
13480 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13481 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13483 EVT XType = N0.getValueType();
13484 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13486 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13488 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13489 getShiftAmountTy(N0.getValueType())));
13490 SDValue Add = DAG.getNode(ISD::ADD, DL,
13492 AddToWorklist(Shift.getNode());
13493 AddToWorklist(Add.getNode());
13494 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13501 /// This is a stub for TargetLowering::SimplifySetCC.
13502 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13503 SDValue N1, ISD::CondCode Cond,
13504 SDLoc DL, bool foldBooleans) {
13505 TargetLowering::DAGCombinerInfo
13506 DagCombineInfo(DAG, Level, false, this);
13507 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13510 /// Given an ISD::SDIV node expressing a divide by constant, return
13511 /// a DAG expression to select that will generate the same value by multiplying
13512 /// by a magic number.
13513 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13514 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13515 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13519 // Avoid division by zero.
13520 if (!C->getAPIntValue())
13523 std::vector<SDNode*> Built;
13525 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13527 for (SDNode *N : Built)
13532 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13533 /// DAG expression that will generate the same value by right shifting.
13534 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13535 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13539 // Avoid division by zero.
13540 if (!C->getAPIntValue())
13543 std::vector<SDNode *> Built;
13544 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13546 for (SDNode *N : Built)
13551 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13552 /// expression that will generate the same value by multiplying by a magic
13554 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13555 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13556 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13560 // Avoid division by zero.
13561 if (!C->getAPIntValue())
13564 std::vector<SDNode*> Built;
13566 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13568 for (SDNode *N : Built)
13573 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13574 if (Level >= AfterLegalizeDAG)
13577 // Expose the DAG combiner to the target combiner implementations.
13578 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13580 unsigned Iterations = 0;
13581 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13583 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13584 // For the reciprocal, we need to find the zero of the function:
13585 // F(X) = A X - 1 [which has a zero at X = 1/A]
13587 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13588 // does not require additional intermediate precision]
13589 EVT VT = Op.getValueType();
13591 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13593 AddToWorklist(Est.getNode());
13595 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13596 for (unsigned i = 0; i < Iterations; ++i) {
13597 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13598 AddToWorklist(NewEst.getNode());
13600 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13601 AddToWorklist(NewEst.getNode());
13603 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13604 AddToWorklist(NewEst.getNode());
13606 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13607 AddToWorklist(Est.getNode());
13616 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13617 /// For the reciprocal sqrt, we need to find the zero of the function:
13618 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13620 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13621 /// As a result, we precompute A/2 prior to the iteration loop.
13622 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13623 unsigned Iterations) {
13624 EVT VT = Arg.getValueType();
13626 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13628 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13629 // this entire sequence requires only one FP constant.
13630 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13631 AddToWorklist(HalfArg.getNode());
13633 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13634 AddToWorklist(HalfArg.getNode());
13636 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13637 for (unsigned i = 0; i < Iterations; ++i) {
13638 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13639 AddToWorklist(NewEst.getNode());
13641 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13642 AddToWorklist(NewEst.getNode());
13644 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13645 AddToWorklist(NewEst.getNode());
13647 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13648 AddToWorklist(Est.getNode());
13653 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13654 /// For the reciprocal sqrt, we need to find the zero of the function:
13655 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13657 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13658 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13659 unsigned Iterations) {
13660 EVT VT = Arg.getValueType();
13662 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13663 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13665 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13666 for (unsigned i = 0; i < Iterations; ++i) {
13667 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13668 AddToWorklist(HalfEst.getNode());
13670 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13671 AddToWorklist(Est.getNode());
13673 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13674 AddToWorklist(Est.getNode());
13676 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13677 AddToWorklist(Est.getNode());
13679 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13680 AddToWorklist(Est.getNode());
13685 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13686 if (Level >= AfterLegalizeDAG)
13689 // Expose the DAG combiner to the target combiner implementations.
13690 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13691 unsigned Iterations = 0;
13692 bool UseOneConstNR = false;
13693 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13694 AddToWorklist(Est.getNode());
13696 Est = UseOneConstNR ?
13697 BuildRsqrtNROneConst(Op, Est, Iterations) :
13698 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13706 /// Return true if base is a frame index, which is known not to alias with
13707 /// anything but itself. Provides base object and offset as results.
13708 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13709 const GlobalValue *&GV, const void *&CV) {
13710 // Assume it is a primitive operation.
13711 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13713 // If it's an adding a simple constant then integrate the offset.
13714 if (Base.getOpcode() == ISD::ADD) {
13715 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13716 Base = Base.getOperand(0);
13717 Offset += C->getZExtValue();
13721 // Return the underlying GlobalValue, and update the Offset. Return false
13722 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13723 // by multiple nodes with different offsets.
13724 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13725 GV = G->getGlobal();
13726 Offset += G->getOffset();
13730 // Return the underlying Constant value, and update the Offset. Return false
13731 // for ConstantSDNodes since the same constant pool entry may be represented
13732 // by multiple nodes with different offsets.
13733 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13734 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13735 : (const void *)C->getConstVal();
13736 Offset += C->getOffset();
13739 // If it's any of the following then it can't alias with anything but itself.
13740 return isa<FrameIndexSDNode>(Base);
13743 /// Return true if there is any possibility that the two addresses overlap.
13744 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13745 // If they are the same then they must be aliases.
13746 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13748 // If they are both volatile then they cannot be reordered.
13749 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13751 // Gather base node and offset information.
13752 SDValue Base1, Base2;
13753 int64_t Offset1, Offset2;
13754 const GlobalValue *GV1, *GV2;
13755 const void *CV1, *CV2;
13756 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13757 Base1, Offset1, GV1, CV1);
13758 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13759 Base2, Offset2, GV2, CV2);
13761 // If they have a same base address then check to see if they overlap.
13762 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13763 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13764 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13766 // It is possible for different frame indices to alias each other, mostly
13767 // when tail call optimization reuses return address slots for arguments.
13768 // To catch this case, look up the actual index of frame indices to compute
13769 // the real alias relationship.
13770 if (isFrameIndex1 && isFrameIndex2) {
13771 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13772 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13773 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13774 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13775 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13778 // Otherwise, if we know what the bases are, and they aren't identical, then
13779 // we know they cannot alias.
13780 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13783 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13784 // compared to the size and offset of the access, we may be able to prove they
13785 // do not alias. This check is conservative for now to catch cases created by
13786 // splitting vector types.
13787 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13788 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13789 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13790 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13791 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13792 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13793 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13795 // There is no overlap between these relatively aligned accesses of similar
13796 // size, return no alias.
13797 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13798 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13802 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13804 : DAG.getSubtarget().useAA();
13806 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13807 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13811 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13812 // Use alias analysis information.
13813 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13814 Op1->getSrcValueOffset());
13815 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13816 Op0->getSrcValueOffset() - MinOffset;
13817 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13818 Op1->getSrcValueOffset() - MinOffset;
13819 AliasAnalysis::AliasResult AAResult =
13820 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13822 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13823 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13825 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13826 if (AAResult == AliasAnalysis::NoAlias)
13830 // Otherwise we have to assume they alias.
13834 /// Walk up chain skipping non-aliasing memory nodes,
13835 /// looking for aliasing nodes and adding them to the Aliases vector.
13836 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13837 SmallVectorImpl<SDValue> &Aliases) {
13838 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13839 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13841 // Get alias information for node.
13842 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13845 Chains.push_back(OriginalChain);
13846 unsigned Depth = 0;
13848 // Look at each chain and determine if it is an alias. If so, add it to the
13849 // aliases list. If not, then continue up the chain looking for the next
13851 while (!Chains.empty()) {
13852 SDValue Chain = Chains.back();
13855 // For TokenFactor nodes, look at each operand and only continue up the
13856 // chain until we find two aliases. If we've seen two aliases, assume we'll
13857 // find more and revert to original chain since the xform is unlikely to be
13860 // FIXME: The depth check could be made to return the last non-aliasing
13861 // chain we found before we hit a tokenfactor rather than the original
13863 if (Depth > 6 || Aliases.size() == 2) {
13865 Aliases.push_back(OriginalChain);
13869 // Don't bother if we've been before.
13870 if (!Visited.insert(Chain.getNode()).second)
13873 switch (Chain.getOpcode()) {
13874 case ISD::EntryToken:
13875 // Entry token is ideal chain operand, but handled in FindBetterChain.
13880 // Get alias information for Chain.
13881 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13882 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13884 // If chain is alias then stop here.
13885 if (!(IsLoad && IsOpLoad) &&
13886 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13887 Aliases.push_back(Chain);
13889 // Look further up the chain.
13890 Chains.push_back(Chain.getOperand(0));
13896 case ISD::TokenFactor:
13897 // We have to check each of the operands of the token factor for "small"
13898 // token factors, so we queue them up. Adding the operands to the queue
13899 // (stack) in reverse order maintains the original order and increases the
13900 // likelihood that getNode will find a matching token factor (CSE.)
13901 if (Chain.getNumOperands() > 16) {
13902 Aliases.push_back(Chain);
13905 for (unsigned n = Chain.getNumOperands(); n;)
13906 Chains.push_back(Chain.getOperand(--n));
13911 // For all other instructions we will just have to take what we can get.
13912 Aliases.push_back(Chain);
13917 // We need to be careful here to also search for aliases through the
13918 // value operand of a store, etc. Consider the following situation:
13920 // L1 = load Token1, %52
13921 // S1 = store Token1, L1, %51
13922 // L2 = load Token1, %52+8
13923 // S2 = store Token1, L2, %51+8
13924 // Token2 = Token(S1, S2)
13925 // L3 = load Token2, %53
13926 // S3 = store Token2, L3, %52
13927 // L4 = load Token2, %53+8
13928 // S4 = store Token2, L4, %52+8
13929 // If we search for aliases of S3 (which loads address %52), and we look
13930 // only through the chain, then we'll miss the trivial dependence on L1
13931 // (which also loads from %52). We then might change all loads and
13932 // stores to use Token1 as their chain operand, which could result in
13933 // copying %53 into %52 before copying %52 into %51 (which should
13936 // The problem is, however, that searching for such data dependencies
13937 // can become expensive, and the cost is not directly related to the
13938 // chain depth. Instead, we'll rule out such configurations here by
13939 // insisting that we've visited all chain users (except for users
13940 // of the original chain, which is not necessary). When doing this,
13941 // we need to look through nodes we don't care about (otherwise, things
13942 // like register copies will interfere with trivial cases).
13944 SmallVector<const SDNode *, 16> Worklist;
13945 for (const SDNode *N : Visited)
13946 if (N != OriginalChain.getNode())
13947 Worklist.push_back(N);
13949 while (!Worklist.empty()) {
13950 const SDNode *M = Worklist.pop_back_val();
13952 // We have already visited M, and want to make sure we've visited any uses
13953 // of M that we care about. For uses that we've not visisted, and don't
13954 // care about, queue them to the worklist.
13956 for (SDNode::use_iterator UI = M->use_begin(),
13957 UIE = M->use_end(); UI != UIE; ++UI)
13958 if (UI.getUse().getValueType() == MVT::Other &&
13959 Visited.insert(*UI).second) {
13960 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13961 // We've not visited this use, and we care about it (it could have an
13962 // ordering dependency with the original node).
13964 Aliases.push_back(OriginalChain);
13968 // We've not visited this use, but we don't care about it. Mark it as
13969 // visited and enqueue it to the worklist.
13970 Worklist.push_back(*UI);
13975 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13976 /// (aliasing node.)
13977 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13978 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
13980 // Accumulate all the aliases to this node.
13981 GatherAllAliases(N, OldChain, Aliases);
13983 // If no operands then chain to entry token.
13984 if (Aliases.size() == 0)
13985 return DAG.getEntryNode();
13987 // If a single operand then chain to it. We don't need to revisit it.
13988 if (Aliases.size() == 1)
13991 // Construct a custom tailored token factor.
13992 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13995 /// This is the entry point for the file.
13996 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13997 CodeGenOpt::Level OptLevel) {
13998 /// This is the main entry point to this class.
13999 DAGCombiner(*this, AA, OptLevel).Run(Level);