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);
311 SDValue XformToShuffleWithZero(SDNode *N);
312 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
314 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
316 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
317 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
318 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
319 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
320 SDValue N3, ISD::CondCode CC,
321 bool NotExtCompare = false);
322 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
323 SDLoc DL, bool foldBooleans = true);
325 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
327 bool isOneUseSetCC(SDValue N) const;
329 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
331 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
332 SDValue CombineExtLoad(SDNode *N);
333 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
334 SDValue BuildSDIV(SDNode *N);
335 SDValue BuildSDIVPow2(SDNode *N);
336 SDValue BuildUDIV(SDNode *N);
337 SDValue BuildReciprocalEstimate(SDValue Op);
338 SDValue BuildRsqrtEstimate(SDValue Op);
339 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
340 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
341 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
342 bool DemandHighBits = true);
343 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
344 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
345 SDValue InnerPos, SDValue InnerNeg,
346 unsigned PosOpcode, unsigned NegOpcode,
348 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
349 SDValue ReduceLoadWidth(SDNode *N);
350 SDValue ReduceLoadOpStoreWidth(SDNode *N);
351 SDValue TransformFPLoadStorePair(SDNode *N);
352 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
353 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
355 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
357 /// Walk up chain skipping non-aliasing memory nodes,
358 /// looking for aliasing nodes and adding them to the Aliases vector.
359 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
360 SmallVectorImpl<SDValue> &Aliases);
362 /// Return true if there is any possibility that the two addresses overlap.
363 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
365 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
366 /// chain (aliasing node.)
367 SDValue FindBetterChain(SDNode *N, SDValue Chain);
369 /// Holds a pointer to an LSBaseSDNode as well as information on where it
370 /// is located in a sequence of memory operations connected by a chain.
372 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
373 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
374 // Ptr to the mem node.
375 LSBaseSDNode *MemNode;
376 // Offset from the base ptr.
377 int64_t OffsetFromBase;
378 // What is the sequence number of this mem node.
379 // Lowest mem operand in the DAG starts at zero.
380 unsigned SequenceNum;
383 /// This is a helper function for MergeConsecutiveStores. When the source
384 /// elements of the consecutive stores are all constants or all extracted
385 /// vector elements, try to merge them into one larger store.
386 /// \return True if a merged store was created.
387 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
388 EVT MemVT, unsigned NumElem,
389 bool IsConstantSrc, bool UseVector);
391 /// Merge consecutive store operations into a wide store.
392 /// This optimization uses wide integers or vectors when possible.
393 /// \return True if some memory operations were changed.
394 bool MergeConsecutiveStores(StoreSDNode *N);
396 /// \brief Try to transform a truncation where C is a constant:
397 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
399 /// \p N needs to be a truncation and its first operand an AND. Other
400 /// requirements are checked by the function (e.g. that trunc is
401 /// single-use) and if missed an empty SDValue is returned.
402 SDValue distributeTruncateThroughAnd(SDNode *N);
405 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
406 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
407 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
408 auto *F = DAG.getMachineFunction().getFunction();
409 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
410 F->hasFnAttribute(Attribute::MinSize);
413 /// Runs the dag combiner on all nodes in the work list
414 void Run(CombineLevel AtLevel);
416 SelectionDAG &getDAG() const { return DAG; }
418 /// Returns a type large enough to hold any valid shift amount - before type
419 /// legalization these can be huge.
420 EVT getShiftAmountTy(EVT LHSTy) {
421 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
422 if (LHSTy.isVector())
424 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
425 : TLI.getPointerTy();
428 /// This method returns true if we are running before type legalization or
429 /// if the specified VT is legal.
430 bool isTypeLegal(const EVT &VT) {
431 if (!LegalTypes) return true;
432 return TLI.isTypeLegal(VT);
435 /// Convenience wrapper around TargetLowering::getSetCCResultType
436 EVT getSetCCResultType(EVT VT) const {
437 return TLI.getSetCCResultType(*DAG.getContext(), VT);
444 /// This class is a DAGUpdateListener that removes any deleted
445 /// nodes from the worklist.
446 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
449 explicit WorklistRemover(DAGCombiner &dc)
450 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
452 void NodeDeleted(SDNode *N, SDNode *E) override {
453 DC.removeFromWorklist(N);
458 //===----------------------------------------------------------------------===//
459 // TargetLowering::DAGCombinerInfo implementation
460 //===----------------------------------------------------------------------===//
462 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
463 ((DAGCombiner*)DC)->AddToWorklist(N);
466 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
467 ((DAGCombiner*)DC)->removeFromWorklist(N);
470 SDValue TargetLowering::DAGCombinerInfo::
471 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
472 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
475 SDValue TargetLowering::DAGCombinerInfo::
476 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
477 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
483 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
486 void TargetLowering::DAGCombinerInfo::
487 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
488 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
491 //===----------------------------------------------------------------------===//
493 //===----------------------------------------------------------------------===//
495 void DAGCombiner::deleteAndRecombine(SDNode *N) {
496 removeFromWorklist(N);
498 // If the operands of this node are only used by the node, they will now be
499 // dead. Make sure to re-visit them and recursively delete dead nodes.
500 for (const SDValue &Op : N->ops())
501 // For an operand generating multiple values, one of the values may
502 // become dead allowing further simplification (e.g. split index
503 // arithmetic from an indexed load).
504 if (Op->hasOneUse() || Op->getNumValues() > 1)
505 AddToWorklist(Op.getNode());
510 /// Return 1 if we can compute the negated form of the specified expression for
511 /// the same cost as the expression itself, or 2 if we can compute the negated
512 /// form more cheaply than the expression itself.
513 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
514 const TargetLowering &TLI,
515 const TargetOptions *Options,
516 unsigned Depth = 0) {
517 // fneg is removable even if it has multiple uses.
518 if (Op.getOpcode() == ISD::FNEG) return 2;
520 // Don't allow anything with multiple uses.
521 if (!Op.hasOneUse()) return 0;
523 // Don't recurse exponentially.
524 if (Depth > 6) return 0;
526 switch (Op.getOpcode()) {
527 default: return false;
528 case ISD::ConstantFP:
529 // Don't invert constant FP values after legalize. The negated constant
530 // isn't necessarily legal.
531 return LegalOperations ? 0 : 1;
533 // FIXME: determine better conditions for this xform.
534 if (!Options->UnsafeFPMath) return 0;
536 // After operation legalization, it might not be legal to create new FSUBs.
537 if (LegalOperations &&
538 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
541 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
542 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
545 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
546 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
549 // We can't turn -(A-B) into B-A when we honor signed zeros.
550 if (!Options->UnsafeFPMath) return 0;
552 // fold (fneg (fsub A, B)) -> (fsub B, A)
557 if (Options->HonorSignDependentRoundingFPMath()) return 0;
559 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
560 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
564 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
570 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
575 /// If isNegatibleForFree returns true, return the newly negated expression.
576 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
577 bool LegalOperations, unsigned Depth = 0) {
578 const TargetOptions &Options = DAG.getTarget().Options;
579 // fneg is removable even if it has multiple uses.
580 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
582 // Don't allow anything with multiple uses.
583 assert(Op.hasOneUse() && "Unknown reuse!");
585 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
586 switch (Op.getOpcode()) {
587 default: llvm_unreachable("Unknown code");
588 case ISD::ConstantFP: {
589 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
591 return DAG.getConstantFP(V, Op.getValueType());
594 // FIXME: determine better conditions for this xform.
595 assert(Options.UnsafeFPMath);
597 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
598 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
599 DAG.getTargetLoweringInfo(), &Options, Depth+1))
600 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
601 GetNegatedExpression(Op.getOperand(0), DAG,
602 LegalOperations, Depth+1),
604 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
605 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
606 GetNegatedExpression(Op.getOperand(1), DAG,
607 LegalOperations, Depth+1),
610 // We can't turn -(A-B) into B-A when we honor signed zeros.
611 assert(Options.UnsafeFPMath);
613 // fold (fneg (fsub 0, B)) -> B
614 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
615 if (N0CFP->getValueAPF().isZero())
616 return Op.getOperand(1);
618 // fold (fneg (fsub A, B)) -> (fsub B, A)
619 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
620 Op.getOperand(1), Op.getOperand(0));
624 assert(!Options.HonorSignDependentRoundingFPMath());
626 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
627 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
628 DAG.getTargetLoweringInfo(), &Options, Depth+1))
629 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
630 GetNegatedExpression(Op.getOperand(0), DAG,
631 LegalOperations, Depth+1),
634 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
635 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
637 GetNegatedExpression(Op.getOperand(1), DAG,
638 LegalOperations, Depth+1));
642 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
643 GetNegatedExpression(Op.getOperand(0), DAG,
644 LegalOperations, Depth+1));
646 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
647 GetNegatedExpression(Op.getOperand(0), DAG,
648 LegalOperations, Depth+1),
653 // Return true if this node is a setcc, or is a select_cc
654 // that selects between the target values used for true and false, making it
655 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
656 // the appropriate nodes based on the type of node we are checking. This
657 // simplifies life a bit for the callers.
658 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
660 if (N.getOpcode() == ISD::SETCC) {
661 LHS = N.getOperand(0);
662 RHS = N.getOperand(1);
663 CC = N.getOperand(2);
667 if (N.getOpcode() != ISD::SELECT_CC ||
668 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
669 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
672 if (TLI.getBooleanContents(N.getValueType()) ==
673 TargetLowering::UndefinedBooleanContent)
676 LHS = N.getOperand(0);
677 RHS = N.getOperand(1);
678 CC = N.getOperand(4);
682 /// Return true if this is a SetCC-equivalent operation with only one use.
683 /// If this is true, it allows the users to invert the operation for free when
684 /// it is profitable to do so.
685 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
687 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
692 /// Returns true if N is a BUILD_VECTOR node whose
693 /// elements are all the same constant or undefined.
694 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
695 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
700 unsigned SplatBitSize;
702 EVT EltVT = N->getValueType(0).getVectorElementType();
703 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
705 EltVT.getSizeInBits() >= SplatBitSize);
708 // \brief Returns the SDNode if it is a constant integer BuildVector
709 // or constant integer.
710 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
711 if (isa<ConstantSDNode>(N))
713 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
718 // \brief Returns the SDNode if it is a constant float BuildVector
719 // or constant float.
720 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
721 if (isa<ConstantFPSDNode>(N))
723 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
728 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
730 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
731 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
734 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
735 BitVector UndefElements;
736 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
738 // BuildVectors can truncate their operands. Ignore that case here.
739 // FIXME: We blindly ignore splats which include undef which is overly
741 if (CN && UndefElements.none() &&
742 CN->getValueType(0) == N.getValueType().getScalarType())
749 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
751 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
752 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
755 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
756 BitVector UndefElements;
757 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
759 if (CN && UndefElements.none())
766 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
767 SDValue N0, SDValue N1) {
768 EVT VT = N0.getValueType();
769 if (N0.getOpcode() == Opc) {
770 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
771 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
772 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
773 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
774 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
777 if (N0.hasOneUse()) {
778 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
780 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
781 if (!OpNode.getNode())
783 AddToWorklist(OpNode.getNode());
784 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
789 if (N1.getOpcode() == Opc) {
790 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
791 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
792 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
793 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
794 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
797 if (N1.hasOneUse()) {
798 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
800 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
801 if (!OpNode.getNode())
803 AddToWorklist(OpNode.getNode());
804 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
812 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
814 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
816 DEBUG(dbgs() << "\nReplacing.1 ";
818 dbgs() << "\nWith: ";
819 To[0].getNode()->dump(&DAG);
820 dbgs() << " and " << NumTo-1 << " other values\n");
821 for (unsigned i = 0, e = NumTo; i != e; ++i)
822 assert((!To[i].getNode() ||
823 N->getValueType(i) == To[i].getValueType()) &&
824 "Cannot combine value to value of different type!");
826 WorklistRemover DeadNodes(*this);
827 DAG.ReplaceAllUsesWith(N, To);
829 // Push the new nodes and any users onto the worklist
830 for (unsigned i = 0, e = NumTo; i != e; ++i) {
831 if (To[i].getNode()) {
832 AddToWorklist(To[i].getNode());
833 AddUsersToWorklist(To[i].getNode());
838 // Finally, if the node is now dead, remove it from the graph. The node
839 // may not be dead if the replacement process recursively simplified to
840 // something else needing this node.
842 deleteAndRecombine(N);
843 return SDValue(N, 0);
847 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
848 // Replace all uses. If any nodes become isomorphic to other nodes and
849 // are deleted, make sure to remove them from our worklist.
850 WorklistRemover DeadNodes(*this);
851 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
853 // Push the new node and any (possibly new) users onto the worklist.
854 AddToWorklist(TLO.New.getNode());
855 AddUsersToWorklist(TLO.New.getNode());
857 // Finally, if the node is now dead, remove it from the graph. The node
858 // may not be dead if the replacement process recursively simplified to
859 // something else needing this node.
860 if (TLO.Old.getNode()->use_empty())
861 deleteAndRecombine(TLO.Old.getNode());
864 /// Check the specified integer node value to see if it can be simplified or if
865 /// things it uses can be simplified by bit propagation. If so, return true.
866 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
867 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
868 APInt KnownZero, KnownOne;
869 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
873 AddToWorklist(Op.getNode());
875 // Replace the old value with the new one.
877 DEBUG(dbgs() << "\nReplacing.2 ";
878 TLO.Old.getNode()->dump(&DAG);
879 dbgs() << "\nWith: ";
880 TLO.New.getNode()->dump(&DAG);
883 CommitTargetLoweringOpt(TLO);
887 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
889 EVT VT = Load->getValueType(0);
890 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
892 DEBUG(dbgs() << "\nReplacing.9 ";
894 dbgs() << "\nWith: ";
895 Trunc.getNode()->dump(&DAG);
897 WorklistRemover DeadNodes(*this);
898 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
899 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
900 deleteAndRecombine(Load);
901 AddToWorklist(Trunc.getNode());
904 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
907 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
908 EVT MemVT = LD->getMemoryVT();
909 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
910 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
912 : LD->getExtensionType();
914 return DAG.getExtLoad(ExtType, dl, PVT,
915 LD->getChain(), LD->getBasePtr(),
916 MemVT, LD->getMemOperand());
919 unsigned Opc = Op.getOpcode();
922 case ISD::AssertSext:
923 return DAG.getNode(ISD::AssertSext, dl, PVT,
924 SExtPromoteOperand(Op.getOperand(0), PVT),
926 case ISD::AssertZext:
927 return DAG.getNode(ISD::AssertZext, dl, PVT,
928 ZExtPromoteOperand(Op.getOperand(0), PVT),
930 case ISD::Constant: {
932 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
933 return DAG.getNode(ExtOpc, dl, PVT, Op);
937 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
939 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
942 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
943 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
945 EVT OldVT = Op.getValueType();
947 bool Replace = false;
948 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
949 if (!NewOp.getNode())
951 AddToWorklist(NewOp.getNode());
954 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
955 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
956 DAG.getValueType(OldVT));
959 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
960 EVT OldVT = Op.getValueType();
962 bool Replace = false;
963 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
964 if (!NewOp.getNode())
966 AddToWorklist(NewOp.getNode());
969 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
970 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
973 /// Promote the specified integer binary operation if the target indicates it is
974 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
975 /// i32 since i16 instructions are longer.
976 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
977 if (!LegalOperations)
980 EVT VT = Op.getValueType();
981 if (VT.isVector() || !VT.isInteger())
984 // If operation type is 'undesirable', e.g. i16 on x86, consider
986 unsigned Opc = Op.getOpcode();
987 if (TLI.isTypeDesirableForOp(Opc, VT))
991 // Consult target whether it is a good idea to promote this operation and
992 // what's the right type to promote it to.
993 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
994 assert(PVT != VT && "Don't know what type to promote to!");
996 bool Replace0 = false;
997 SDValue N0 = Op.getOperand(0);
998 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1002 bool Replace1 = false;
1003 SDValue N1 = Op.getOperand(1);
1008 NN1 = PromoteOperand(N1, PVT, Replace1);
1013 AddToWorklist(NN0.getNode());
1015 AddToWorklist(NN1.getNode());
1018 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1020 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1022 DEBUG(dbgs() << "\nPromoting ";
1023 Op.getNode()->dump(&DAG));
1025 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1026 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1031 /// Promote the specified integer shift operation if the target indicates it is
1032 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1033 /// i32 since i16 instructions are longer.
1034 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1035 if (!LegalOperations)
1038 EVT VT = Op.getValueType();
1039 if (VT.isVector() || !VT.isInteger())
1042 // If operation type is 'undesirable', e.g. i16 on x86, consider
1044 unsigned Opc = Op.getOpcode();
1045 if (TLI.isTypeDesirableForOp(Opc, VT))
1049 // Consult target whether it is a good idea to promote this operation and
1050 // what's the right type to promote it to.
1051 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052 assert(PVT != VT && "Don't know what type to promote to!");
1054 bool Replace = false;
1055 SDValue N0 = Op.getOperand(0);
1056 if (Opc == ISD::SRA)
1057 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1058 else if (Opc == ISD::SRL)
1059 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1061 N0 = PromoteOperand(N0, PVT, Replace);
1065 AddToWorklist(N0.getNode());
1067 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1069 DEBUG(dbgs() << "\nPromoting ";
1070 Op.getNode()->dump(&DAG));
1072 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1073 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1078 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1079 if (!LegalOperations)
1082 EVT VT = Op.getValueType();
1083 if (VT.isVector() || !VT.isInteger())
1086 // If operation type is 'undesirable', e.g. i16 on x86, consider
1088 unsigned Opc = Op.getOpcode();
1089 if (TLI.isTypeDesirableForOp(Opc, VT))
1093 // Consult target whether it is a good idea to promote this operation and
1094 // what's the right type to promote it to.
1095 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1096 assert(PVT != VT && "Don't know what type to promote to!");
1097 // fold (aext (aext x)) -> (aext x)
1098 // fold (aext (zext x)) -> (zext x)
1099 // fold (aext (sext x)) -> (sext x)
1100 DEBUG(dbgs() << "\nPromoting ";
1101 Op.getNode()->dump(&DAG));
1102 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1107 bool DAGCombiner::PromoteLoad(SDValue Op) {
1108 if (!LegalOperations)
1111 EVT VT = Op.getValueType();
1112 if (VT.isVector() || !VT.isInteger())
1115 // If operation type is 'undesirable', e.g. i16 on x86, consider
1117 unsigned Opc = Op.getOpcode();
1118 if (TLI.isTypeDesirableForOp(Opc, VT))
1122 // Consult target whether it is a good idea to promote this operation and
1123 // what's the right type to promote it to.
1124 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1125 assert(PVT != VT && "Don't know what type to promote to!");
1128 SDNode *N = Op.getNode();
1129 LoadSDNode *LD = cast<LoadSDNode>(N);
1130 EVT MemVT = LD->getMemoryVT();
1131 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1132 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1134 : LD->getExtensionType();
1135 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1136 LD->getChain(), LD->getBasePtr(),
1137 MemVT, LD->getMemOperand());
1138 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1140 DEBUG(dbgs() << "\nPromoting ";
1143 Result.getNode()->dump(&DAG);
1145 WorklistRemover DeadNodes(*this);
1146 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1147 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1148 deleteAndRecombine(N);
1149 AddToWorklist(Result.getNode());
1155 /// \brief Recursively delete a node which has no uses and any operands for
1156 /// which it is the only use.
1158 /// Note that this both deletes the nodes and removes them from the worklist.
1159 /// It also adds any nodes who have had a user deleted to the worklist as they
1160 /// may now have only one use and subject to other combines.
1161 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1162 if (!N->use_empty())
1165 SmallSetVector<SDNode *, 16> Nodes;
1168 N = Nodes.pop_back_val();
1172 if (N->use_empty()) {
1173 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1174 Nodes.insert(N->getOperand(i).getNode());
1176 removeFromWorklist(N);
1181 } while (!Nodes.empty());
1185 //===----------------------------------------------------------------------===//
1186 // Main DAG Combiner implementation
1187 //===----------------------------------------------------------------------===//
1189 void DAGCombiner::Run(CombineLevel AtLevel) {
1190 // set the instance variables, so that the various visit routines may use it.
1192 LegalOperations = Level >= AfterLegalizeVectorOps;
1193 LegalTypes = Level >= AfterLegalizeTypes;
1195 // Add all the dag nodes to the worklist.
1196 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1197 E = DAG.allnodes_end(); I != E; ++I)
1200 // Create a dummy node (which is not added to allnodes), that adds a reference
1201 // to the root node, preventing it from being deleted, and tracking any
1202 // changes of the root.
1203 HandleSDNode Dummy(DAG.getRoot());
1205 // while the worklist isn't empty, find a node and
1206 // try and combine it.
1207 while (!WorklistMap.empty()) {
1209 // The Worklist holds the SDNodes in order, but it may contain null entries.
1211 N = Worklist.pop_back_val();
1214 bool GoodWorklistEntry = WorklistMap.erase(N);
1215 (void)GoodWorklistEntry;
1216 assert(GoodWorklistEntry &&
1217 "Found a worklist entry without a corresponding map entry!");
1219 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1220 // N is deleted from the DAG, since they too may now be dead or may have a
1221 // reduced number of uses, allowing other xforms.
1222 if (recursivelyDeleteUnusedNodes(N))
1225 WorklistRemover DeadNodes(*this);
1227 // If this combine is running after legalizing the DAG, re-legalize any
1228 // nodes pulled off the worklist.
1229 if (Level == AfterLegalizeDAG) {
1230 SmallSetVector<SDNode *, 16> UpdatedNodes;
1231 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1233 for (SDNode *LN : UpdatedNodes) {
1235 AddUsersToWorklist(LN);
1241 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1243 // Add any operands of the new node which have not yet been combined to the
1244 // worklist as well. Because the worklist uniques things already, this
1245 // won't repeatedly process the same operand.
1246 CombinedNodes.insert(N);
1247 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1248 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1249 AddToWorklist(N->getOperand(i).getNode());
1251 SDValue RV = combine(N);
1258 // If we get back the same node we passed in, rather than a new node or
1259 // zero, we know that the node must have defined multiple values and
1260 // CombineTo was used. Since CombineTo takes care of the worklist
1261 // mechanics for us, we have no work to do in this case.
1262 if (RV.getNode() == N)
1265 assert(N->getOpcode() != ISD::DELETED_NODE &&
1266 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1267 "Node was deleted but visit returned new node!");
1269 DEBUG(dbgs() << " ... into: ";
1270 RV.getNode()->dump(&DAG));
1272 // Transfer debug value.
1273 DAG.TransferDbgValues(SDValue(N, 0), RV);
1274 if (N->getNumValues() == RV.getNode()->getNumValues())
1275 DAG.ReplaceAllUsesWith(N, RV.getNode());
1277 assert(N->getValueType(0) == RV.getValueType() &&
1278 N->getNumValues() == 1 && "Type mismatch");
1280 DAG.ReplaceAllUsesWith(N, &OpV);
1283 // Push the new node and any users onto the worklist
1284 AddToWorklist(RV.getNode());
1285 AddUsersToWorklist(RV.getNode());
1287 // Finally, if the node is now dead, remove it from the graph. The node
1288 // may not be dead if the replacement process recursively simplified to
1289 // something else needing this node. This will also take care of adding any
1290 // operands which have lost a user to the worklist.
1291 recursivelyDeleteUnusedNodes(N);
1294 // If the root changed (e.g. it was a dead load, update the root).
1295 DAG.setRoot(Dummy.getValue());
1296 DAG.RemoveDeadNodes();
1299 SDValue DAGCombiner::visit(SDNode *N) {
1300 switch (N->getOpcode()) {
1302 case ISD::TokenFactor: return visitTokenFactor(N);
1303 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1304 case ISD::ADD: return visitADD(N);
1305 case ISD::SUB: return visitSUB(N);
1306 case ISD::ADDC: return visitADDC(N);
1307 case ISD::SUBC: return visitSUBC(N);
1308 case ISD::ADDE: return visitADDE(N);
1309 case ISD::SUBE: return visitSUBE(N);
1310 case ISD::MUL: return visitMUL(N);
1311 case ISD::SDIV: return visitSDIV(N);
1312 case ISD::UDIV: return visitUDIV(N);
1313 case ISD::SREM: return visitSREM(N);
1314 case ISD::UREM: return visitUREM(N);
1315 case ISD::MULHU: return visitMULHU(N);
1316 case ISD::MULHS: return visitMULHS(N);
1317 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1318 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1319 case ISD::SMULO: return visitSMULO(N);
1320 case ISD::UMULO: return visitUMULO(N);
1321 case ISD::SDIVREM: return visitSDIVREM(N);
1322 case ISD::UDIVREM: return visitUDIVREM(N);
1323 case ISD::AND: return visitAND(N);
1324 case ISD::OR: return visitOR(N);
1325 case ISD::XOR: return visitXOR(N);
1326 case ISD::SHL: return visitSHL(N);
1327 case ISD::SRA: return visitSRA(N);
1328 case ISD::SRL: return visitSRL(N);
1330 case ISD::ROTL: return visitRotate(N);
1331 case ISD::CTLZ: return visitCTLZ(N);
1332 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1333 case ISD::CTTZ: return visitCTTZ(N);
1334 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1335 case ISD::CTPOP: return visitCTPOP(N);
1336 case ISD::SELECT: return visitSELECT(N);
1337 case ISD::VSELECT: return visitVSELECT(N);
1338 case ISD::SELECT_CC: return visitSELECT_CC(N);
1339 case ISD::SETCC: return visitSETCC(N);
1340 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1341 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1342 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1343 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1344 case ISD::TRUNCATE: return visitTRUNCATE(N);
1345 case ISD::BITCAST: return visitBITCAST(N);
1346 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1347 case ISD::FADD: return visitFADD(N);
1348 case ISD::FSUB: return visitFSUB(N);
1349 case ISD::FMUL: return visitFMUL(N);
1350 case ISD::FMA: return visitFMA(N);
1351 case ISD::FDIV: return visitFDIV(N);
1352 case ISD::FREM: return visitFREM(N);
1353 case ISD::FSQRT: return visitFSQRT(N);
1354 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1355 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1356 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1357 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1358 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1359 case ISD::FP_ROUND: return visitFP_ROUND(N);
1360 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1361 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1362 case ISD::FNEG: return visitFNEG(N);
1363 case ISD::FABS: return visitFABS(N);
1364 case ISD::FFLOOR: return visitFFLOOR(N);
1365 case ISD::FMINNUM: return visitFMINNUM(N);
1366 case ISD::FMAXNUM: return visitFMAXNUM(N);
1367 case ISD::FCEIL: return visitFCEIL(N);
1368 case ISD::FTRUNC: return visitFTRUNC(N);
1369 case ISD::BRCOND: return visitBRCOND(N);
1370 case ISD::BR_CC: return visitBR_CC(N);
1371 case ISD::LOAD: return visitLOAD(N);
1372 case ISD::STORE: return visitSTORE(N);
1373 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1374 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1375 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1376 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1377 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1378 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1379 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1380 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1381 case ISD::MLOAD: return visitMLOAD(N);
1382 case ISD::MSTORE: return visitMSTORE(N);
1387 SDValue DAGCombiner::combine(SDNode *N) {
1388 SDValue RV = visit(N);
1390 // If nothing happened, try a target-specific DAG combine.
1391 if (!RV.getNode()) {
1392 assert(N->getOpcode() != ISD::DELETED_NODE &&
1393 "Node was deleted but visit returned NULL!");
1395 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1396 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1398 // Expose the DAG combiner to the target combiner impls.
1399 TargetLowering::DAGCombinerInfo
1400 DagCombineInfo(DAG, Level, false, this);
1402 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1406 // If nothing happened still, try promoting the operation.
1407 if (!RV.getNode()) {
1408 switch (N->getOpcode()) {
1416 RV = PromoteIntBinOp(SDValue(N, 0));
1421 RV = PromoteIntShiftOp(SDValue(N, 0));
1423 case ISD::SIGN_EXTEND:
1424 case ISD::ZERO_EXTEND:
1425 case ISD::ANY_EXTEND:
1426 RV = PromoteExtend(SDValue(N, 0));
1429 if (PromoteLoad(SDValue(N, 0)))
1435 // If N is a commutative binary node, try commuting it to enable more
1437 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1438 N->getNumValues() == 1) {
1439 SDValue N0 = N->getOperand(0);
1440 SDValue N1 = N->getOperand(1);
1442 // Constant operands are canonicalized to RHS.
1443 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1444 SDValue Ops[] = {N1, N0};
1446 if (const BinaryWithFlagsSDNode *BinNode =
1447 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1448 CSENode = DAG.getNodeIfExists(
1449 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1450 BinNode->hasNoSignedWrap(), BinNode->isExact());
1452 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1455 return SDValue(CSENode, 0);
1462 /// Given a node, return its input chain if it has one, otherwise return a null
1464 static SDValue getInputChainForNode(SDNode *N) {
1465 if (unsigned NumOps = N->getNumOperands()) {
1466 if (N->getOperand(0).getValueType() == MVT::Other)
1467 return N->getOperand(0);
1468 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1469 return N->getOperand(NumOps-1);
1470 for (unsigned i = 1; i < NumOps-1; ++i)
1471 if (N->getOperand(i).getValueType() == MVT::Other)
1472 return N->getOperand(i);
1477 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1478 // If N has two operands, where one has an input chain equal to the other,
1479 // the 'other' chain is redundant.
1480 if (N->getNumOperands() == 2) {
1481 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1482 return N->getOperand(0);
1483 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1484 return N->getOperand(1);
1487 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1488 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1489 SmallPtrSet<SDNode*, 16> SeenOps;
1490 bool Changed = false; // If we should replace this token factor.
1492 // Start out with this token factor.
1495 // Iterate through token factors. The TFs grows when new token factors are
1497 for (unsigned i = 0; i < TFs.size(); ++i) {
1498 SDNode *TF = TFs[i];
1500 // Check each of the operands.
1501 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1502 SDValue Op = TF->getOperand(i);
1504 switch (Op.getOpcode()) {
1505 case ISD::EntryToken:
1506 // Entry tokens don't need to be added to the list. They are
1511 case ISD::TokenFactor:
1512 if (Op.hasOneUse() &&
1513 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1514 // Queue up for processing.
1515 TFs.push_back(Op.getNode());
1516 // Clean up in case the token factor is removed.
1517 AddToWorklist(Op.getNode());
1524 // Only add if it isn't already in the list.
1525 if (SeenOps.insert(Op.getNode()).second)
1536 // If we've changed things around then replace token factor.
1539 // The entry token is the only possible outcome.
1540 Result = DAG.getEntryNode();
1542 // New and improved token factor.
1543 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1546 // Add users to worklist if AA is enabled, since it may introduce
1547 // a lot of new chained token factors while removing memory deps.
1548 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1549 : DAG.getSubtarget().useAA();
1550 return CombineTo(N, Result, UseAA /*add to worklist*/);
1556 /// MERGE_VALUES can always be eliminated.
1557 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1558 WorklistRemover DeadNodes(*this);
1559 // Replacing results may cause a different MERGE_VALUES to suddenly
1560 // be CSE'd with N, and carry its uses with it. Iterate until no
1561 // uses remain, to ensure that the node can be safely deleted.
1562 // First add the users of this node to the work list so that they
1563 // can be tried again once they have new operands.
1564 AddUsersToWorklist(N);
1566 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1567 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1568 } while (!N->use_empty());
1569 deleteAndRecombine(N);
1570 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1573 SDValue DAGCombiner::visitADD(SDNode *N) {
1574 SDValue N0 = N->getOperand(0);
1575 SDValue N1 = N->getOperand(1);
1576 EVT VT = N0.getValueType();
1579 if (VT.isVector()) {
1580 SDValue FoldedVOp = SimplifyVBinOp(N);
1581 if (FoldedVOp.getNode()) return FoldedVOp;
1583 // fold (add x, 0) -> x, vector edition
1584 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1586 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1590 // fold (add x, undef) -> undef
1591 if (N0.getOpcode() == ISD::UNDEF)
1593 if (N1.getOpcode() == ISD::UNDEF)
1595 // fold (add c1, c2) -> c1+c2
1596 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1597 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1599 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1600 // canonicalize constant to RHS
1602 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1603 // fold (add x, 0) -> x
1604 if (N1C && N1C->isNullValue())
1606 // fold (add Sym, c) -> Sym+c
1607 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1608 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1609 GA->getOpcode() == ISD::GlobalAddress)
1610 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1612 (uint64_t)N1C->getSExtValue());
1613 // fold ((c1-A)+c2) -> (c1+c2)-A
1614 if (N1C && N0.getOpcode() == ISD::SUB)
1615 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1616 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1617 DAG.getConstant(N1C->getAPIntValue()+
1618 N0C->getAPIntValue(), VT),
1621 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1623 // fold ((0-A) + B) -> B-A
1624 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1625 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1626 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1627 // fold (A + (0-B)) -> A-B
1628 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1629 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1630 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1631 // fold (A+(B-A)) -> B
1632 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1633 return N1.getOperand(0);
1634 // fold ((B-A)+A) -> B
1635 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1636 return N0.getOperand(0);
1637 // fold (A+(B-(A+C))) to (B-C)
1638 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1639 N0 == N1.getOperand(1).getOperand(0))
1640 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1641 N1.getOperand(1).getOperand(1));
1642 // fold (A+(B-(C+A))) to (B-C)
1643 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1644 N0 == N1.getOperand(1).getOperand(1))
1645 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1646 N1.getOperand(1).getOperand(0));
1647 // fold (A+((B-A)+or-C)) to (B+or-C)
1648 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1649 N1.getOperand(0).getOpcode() == ISD::SUB &&
1650 N0 == N1.getOperand(0).getOperand(1))
1651 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1652 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1654 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1655 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1656 SDValue N00 = N0.getOperand(0);
1657 SDValue N01 = N0.getOperand(1);
1658 SDValue N10 = N1.getOperand(0);
1659 SDValue N11 = N1.getOperand(1);
1661 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1662 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1663 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1664 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1667 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1668 return SDValue(N, 0);
1670 // fold (a+b) -> (a|b) iff a and b share no bits.
1671 if (VT.isInteger() && !VT.isVector()) {
1672 APInt LHSZero, LHSOne;
1673 APInt RHSZero, RHSOne;
1674 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1676 if (LHSZero.getBoolValue()) {
1677 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1679 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1680 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1681 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1682 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1683 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1688 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1689 if (N1.getOpcode() == ISD::SHL &&
1690 N1.getOperand(0).getOpcode() == ISD::SUB)
1691 if (ConstantSDNode *C =
1692 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1693 if (C->getAPIntValue() == 0)
1694 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1695 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1696 N1.getOperand(0).getOperand(1),
1698 if (N0.getOpcode() == ISD::SHL &&
1699 N0.getOperand(0).getOpcode() == ISD::SUB)
1700 if (ConstantSDNode *C =
1701 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1702 if (C->getAPIntValue() == 0)
1703 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1704 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1705 N0.getOperand(0).getOperand(1),
1708 if (N1.getOpcode() == ISD::AND) {
1709 SDValue AndOp0 = N1.getOperand(0);
1710 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1711 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1712 unsigned DestBits = VT.getScalarType().getSizeInBits();
1714 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1715 // and similar xforms where the inner op is either ~0 or 0.
1716 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1718 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1722 // add (sext i1), X -> sub X, (zext i1)
1723 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1724 N0.getOperand(0).getValueType() == MVT::i1 &&
1725 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1727 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1728 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1731 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1732 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1733 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1734 if (TN->getVT() == MVT::i1) {
1736 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1737 DAG.getConstant(1, VT));
1738 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1745 SDValue DAGCombiner::visitADDC(SDNode *N) {
1746 SDValue N0 = N->getOperand(0);
1747 SDValue N1 = N->getOperand(1);
1748 EVT VT = N0.getValueType();
1750 // If the flag result is dead, turn this into an ADD.
1751 if (!N->hasAnyUseOfValue(1))
1752 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1753 DAG.getNode(ISD::CARRY_FALSE,
1754 SDLoc(N), MVT::Glue));
1756 // canonicalize constant to RHS.
1757 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1758 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1760 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1762 // fold (addc x, 0) -> x + no carry out
1763 if (N1C && N1C->isNullValue())
1764 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1765 SDLoc(N), MVT::Glue));
1767 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1768 APInt LHSZero, LHSOne;
1769 APInt RHSZero, RHSOne;
1770 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1772 if (LHSZero.getBoolValue()) {
1773 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1775 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1776 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1777 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1778 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1779 DAG.getNode(ISD::CARRY_FALSE,
1780 SDLoc(N), MVT::Glue));
1786 SDValue DAGCombiner::visitADDE(SDNode *N) {
1787 SDValue N0 = N->getOperand(0);
1788 SDValue N1 = N->getOperand(1);
1789 SDValue CarryIn = N->getOperand(2);
1791 // canonicalize constant to RHS
1792 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1793 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1795 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1798 // fold (adde x, y, false) -> (addc x, y)
1799 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1800 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1805 // Since it may not be valid to emit a fold to zero for vector initializers
1806 // check if we can before folding.
1807 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1809 bool LegalOperations, bool LegalTypes) {
1811 return DAG.getConstant(0, VT);
1812 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1813 return DAG.getConstant(0, VT);
1817 SDValue DAGCombiner::visitSUB(SDNode *N) {
1818 SDValue N0 = N->getOperand(0);
1819 SDValue N1 = N->getOperand(1);
1820 EVT VT = N0.getValueType();
1823 if (VT.isVector()) {
1824 SDValue FoldedVOp = SimplifyVBinOp(N);
1825 if (FoldedVOp.getNode()) return FoldedVOp;
1827 // fold (sub x, 0) -> x, vector edition
1828 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1832 // fold (sub x, x) -> 0
1833 // FIXME: Refactor this and xor and other similar operations together.
1835 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1836 // fold (sub c1, c2) -> c1-c2
1837 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1838 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1840 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1841 // fold (sub x, c) -> (add x, -c)
1843 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1844 DAG.getConstant(-N1C->getAPIntValue(), VT));
1845 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1846 if (N0C && N0C->isAllOnesValue())
1847 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1848 // fold A-(A-B) -> B
1849 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1850 return N1.getOperand(1);
1851 // fold (A+B)-A -> B
1852 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1853 return N0.getOperand(1);
1854 // fold (A+B)-B -> A
1855 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1856 return N0.getOperand(0);
1857 // fold C2-(A+C1) -> (C2-C1)-A
1858 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1859 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1860 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1861 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1863 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1866 // fold ((A+(B+or-C))-B) -> A+or-C
1867 if (N0.getOpcode() == ISD::ADD &&
1868 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1869 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1870 N0.getOperand(1).getOperand(0) == N1)
1871 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1872 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1873 // fold ((A+(C+B))-B) -> A+C
1874 if (N0.getOpcode() == ISD::ADD &&
1875 N0.getOperand(1).getOpcode() == ISD::ADD &&
1876 N0.getOperand(1).getOperand(1) == N1)
1877 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1878 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1879 // fold ((A-(B-C))-C) -> A-B
1880 if (N0.getOpcode() == ISD::SUB &&
1881 N0.getOperand(1).getOpcode() == ISD::SUB &&
1882 N0.getOperand(1).getOperand(1) == N1)
1883 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1884 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1886 // If either operand of a sub is undef, the result is undef
1887 if (N0.getOpcode() == ISD::UNDEF)
1889 if (N1.getOpcode() == ISD::UNDEF)
1892 // If the relocation model supports it, consider symbol offsets.
1893 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1894 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1895 // fold (sub Sym, c) -> Sym-c
1896 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1897 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1899 (uint64_t)N1C->getSExtValue());
1900 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1901 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1902 if (GA->getGlobal() == GB->getGlobal())
1903 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1907 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1908 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1909 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1910 if (TN->getVT() == MVT::i1) {
1912 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1913 DAG.getConstant(1, VT));
1914 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1921 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1922 SDValue N0 = N->getOperand(0);
1923 SDValue N1 = N->getOperand(1);
1924 EVT VT = N0.getValueType();
1926 // If the flag result is dead, turn this into an SUB.
1927 if (!N->hasAnyUseOfValue(1))
1928 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1929 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1932 // fold (subc x, x) -> 0 + no borrow
1934 return CombineTo(N, DAG.getConstant(0, VT),
1935 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1938 // fold (subc x, 0) -> x + no borrow
1939 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1940 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1941 if (N1C && N1C->isNullValue())
1942 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1945 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1946 if (N0C && N0C->isAllOnesValue())
1947 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1948 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1954 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1955 SDValue N0 = N->getOperand(0);
1956 SDValue N1 = N->getOperand(1);
1957 SDValue CarryIn = N->getOperand(2);
1959 // fold (sube x, y, false) -> (subc x, y)
1960 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1961 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1966 SDValue DAGCombiner::visitMUL(SDNode *N) {
1967 SDValue N0 = N->getOperand(0);
1968 SDValue N1 = N->getOperand(1);
1969 EVT VT = N0.getValueType();
1971 // fold (mul x, undef) -> 0
1972 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1973 return DAG.getConstant(0, VT);
1975 bool N0IsConst = false;
1976 bool N1IsConst = false;
1977 APInt ConstValue0, ConstValue1;
1979 if (VT.isVector()) {
1980 SDValue FoldedVOp = SimplifyVBinOp(N);
1981 if (FoldedVOp.getNode()) return FoldedVOp;
1983 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1984 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1986 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1987 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1989 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1990 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1994 // fold (mul c1, c2) -> c1*c2
1995 if (N0IsConst && N1IsConst)
1996 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1998 // canonicalize constant to RHS
1999 if (N0IsConst && !N1IsConst)
2000 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2001 // fold (mul x, 0) -> 0
2002 if (N1IsConst && ConstValue1 == 0)
2004 // We require a splat of the entire scalar bit width for non-contiguous
2007 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2008 // fold (mul x, 1) -> x
2009 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2011 // fold (mul x, -1) -> 0-x
2012 if (N1IsConst && ConstValue1.isAllOnesValue())
2013 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2014 DAG.getConstant(0, VT), N0);
2015 // fold (mul x, (1 << c)) -> x << c
2016 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2017 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2018 DAG.getConstant(ConstValue1.logBase2(),
2019 getShiftAmountTy(N0.getValueType())));
2020 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2021 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2022 unsigned Log2Val = (-ConstValue1).logBase2();
2023 // FIXME: If the input is something that is easily negated (e.g. a
2024 // single-use add), we should put the negate there.
2025 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2026 DAG.getConstant(0, VT),
2027 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2028 DAG.getConstant(Log2Val,
2029 getShiftAmountTy(N0.getValueType()))));
2033 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2034 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2035 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2036 isa<ConstantSDNode>(N0.getOperand(1)))) {
2037 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2038 N1, N0.getOperand(1));
2039 AddToWorklist(C3.getNode());
2040 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2041 N0.getOperand(0), C3);
2044 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2047 SDValue Sh(nullptr,0), Y(nullptr,0);
2048 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2049 if (N0.getOpcode() == ISD::SHL &&
2050 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2051 isa<ConstantSDNode>(N0.getOperand(1))) &&
2052 N0.getNode()->hasOneUse()) {
2054 } else if (N1.getOpcode() == ISD::SHL &&
2055 isa<ConstantSDNode>(N1.getOperand(1)) &&
2056 N1.getNode()->hasOneUse()) {
2061 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2062 Sh.getOperand(0), Y);
2063 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2064 Mul, Sh.getOperand(1));
2068 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2069 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2070 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2071 isa<ConstantSDNode>(N0.getOperand(1))))
2072 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2073 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2074 N0.getOperand(0), N1),
2075 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2076 N0.getOperand(1), N1));
2079 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2085 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2086 SDValue N0 = N->getOperand(0);
2087 SDValue N1 = N->getOperand(1);
2088 EVT VT = N->getValueType(0);
2091 if (VT.isVector()) {
2092 SDValue FoldedVOp = SimplifyVBinOp(N);
2093 if (FoldedVOp.getNode()) return FoldedVOp;
2096 // fold (sdiv c1, c2) -> c1/c2
2097 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2098 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2099 if (N0C && N1C && !N1C->isNullValue())
2100 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2101 // fold (sdiv X, 1) -> X
2102 if (N1C && N1C->getAPIntValue() == 1LL)
2104 // fold (sdiv X, -1) -> 0-X
2105 if (N1C && N1C->isAllOnesValue())
2106 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2107 DAG.getConstant(0, VT), N0);
2108 // If we know the sign bits of both operands are zero, strength reduce to a
2109 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2110 if (!VT.isVector()) {
2111 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2112 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2116 // fold (sdiv X, pow2) -> simple ops after legalize
2117 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2118 (-N1C->getAPIntValue()).isPowerOf2())) {
2119 // If dividing by powers of two is cheap, then don't perform the following
2121 if (TLI.isPow2SDivCheap())
2124 // Target-specific implementation of sdiv x, pow2.
2125 SDValue Res = BuildSDIVPow2(N);
2129 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2131 // Splat the sign bit into the register
2133 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2134 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2135 getShiftAmountTy(N0.getValueType())));
2136 AddToWorklist(SGN.getNode());
2138 // Add (N0 < 0) ? abs2 - 1 : 0;
2140 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2141 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2142 getShiftAmountTy(SGN.getValueType())));
2143 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2144 AddToWorklist(SRL.getNode());
2145 AddToWorklist(ADD.getNode()); // Divide by pow2
2146 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2147 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2149 // If we're dividing by a positive value, we're done. Otherwise, we must
2150 // negate the result.
2151 if (N1C->getAPIntValue().isNonNegative())
2154 AddToWorklist(SRA.getNode());
2155 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2158 // if integer divide is expensive and we satisfy the requirements, emit an
2159 // alternate sequence.
2160 if (N1C && !TLI.isIntDivCheap()) {
2161 SDValue Op = BuildSDIV(N);
2162 if (Op.getNode()) return Op;
2166 if (N0.getOpcode() == ISD::UNDEF)
2167 return DAG.getConstant(0, VT);
2168 // X / undef -> undef
2169 if (N1.getOpcode() == ISD::UNDEF)
2175 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2176 SDValue N0 = N->getOperand(0);
2177 SDValue N1 = N->getOperand(1);
2178 EVT VT = N->getValueType(0);
2181 if (VT.isVector()) {
2182 SDValue FoldedVOp = SimplifyVBinOp(N);
2183 if (FoldedVOp.getNode()) return FoldedVOp;
2186 // fold (udiv c1, c2) -> c1/c2
2187 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2188 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2189 if (N0C && N1C && !N1C->isNullValue())
2190 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2191 // fold (udiv x, (1 << c)) -> x >>u c
2192 if (N1C && N1C->getAPIntValue().isPowerOf2())
2193 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2194 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2195 getShiftAmountTy(N0.getValueType())));
2196 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2197 if (N1.getOpcode() == ISD::SHL) {
2198 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2199 if (SHC->getAPIntValue().isPowerOf2()) {
2200 EVT ADDVT = N1.getOperand(1).getValueType();
2201 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2203 DAG.getConstant(SHC->getAPIntValue()
2206 AddToWorklist(Add.getNode());
2207 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2211 // fold (udiv x, c) -> alternate
2212 if (N1C && !TLI.isIntDivCheap()) {
2213 SDValue Op = BuildUDIV(N);
2214 if (Op.getNode()) return Op;
2218 if (N0.getOpcode() == ISD::UNDEF)
2219 return DAG.getConstant(0, VT);
2220 // X / undef -> undef
2221 if (N1.getOpcode() == ISD::UNDEF)
2227 SDValue DAGCombiner::visitSREM(SDNode *N) {
2228 SDValue N0 = N->getOperand(0);
2229 SDValue N1 = N->getOperand(1);
2230 EVT VT = N->getValueType(0);
2232 // fold (srem c1, c2) -> c1%c2
2233 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2234 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2235 if (N0C && N1C && !N1C->isNullValue())
2236 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2237 // If we know the sign bits of both operands are zero, strength reduce to a
2238 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2239 if (!VT.isVector()) {
2240 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2241 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2244 // If X/C can be simplified by the division-by-constant logic, lower
2245 // X%C to the equivalent of X-X/C*C.
2246 if (N1C && !N1C->isNullValue()) {
2247 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2248 AddToWorklist(Div.getNode());
2249 SDValue OptimizedDiv = combine(Div.getNode());
2250 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2251 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2253 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2254 AddToWorklist(Mul.getNode());
2260 if (N0.getOpcode() == ISD::UNDEF)
2261 return DAG.getConstant(0, VT);
2262 // X % undef -> undef
2263 if (N1.getOpcode() == ISD::UNDEF)
2269 SDValue DAGCombiner::visitUREM(SDNode *N) {
2270 SDValue N0 = N->getOperand(0);
2271 SDValue N1 = N->getOperand(1);
2272 EVT VT = N->getValueType(0);
2274 // fold (urem c1, c2) -> c1%c2
2275 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2276 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2277 if (N0C && N1C && !N1C->isNullValue())
2278 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2279 // fold (urem x, pow2) -> (and x, pow2-1)
2280 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2281 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2282 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2283 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2284 if (N1.getOpcode() == ISD::SHL) {
2285 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2286 if (SHC->getAPIntValue().isPowerOf2()) {
2288 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2289 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2291 AddToWorklist(Add.getNode());
2292 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2297 // If X/C can be simplified by the division-by-constant logic, lower
2298 // X%C to the equivalent of X-X/C*C.
2299 if (N1C && !N1C->isNullValue()) {
2300 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2301 AddToWorklist(Div.getNode());
2302 SDValue OptimizedDiv = combine(Div.getNode());
2303 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2304 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2306 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2307 AddToWorklist(Mul.getNode());
2313 if (N0.getOpcode() == ISD::UNDEF)
2314 return DAG.getConstant(0, VT);
2315 // X % undef -> undef
2316 if (N1.getOpcode() == ISD::UNDEF)
2322 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2323 SDValue N0 = N->getOperand(0);
2324 SDValue N1 = N->getOperand(1);
2325 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2326 EVT VT = N->getValueType(0);
2329 // fold (mulhs x, 0) -> 0
2330 if (N1C && N1C->isNullValue())
2332 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2333 if (N1C && N1C->getAPIntValue() == 1)
2334 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2335 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2336 getShiftAmountTy(N0.getValueType())));
2337 // fold (mulhs x, undef) -> 0
2338 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2339 return DAG.getConstant(0, VT);
2341 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2343 if (VT.isSimple() && !VT.isVector()) {
2344 MVT Simple = VT.getSimpleVT();
2345 unsigned SimpleSize = Simple.getSizeInBits();
2346 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2347 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2348 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2349 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2350 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2351 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2352 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2353 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2360 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2361 SDValue N0 = N->getOperand(0);
2362 SDValue N1 = N->getOperand(1);
2363 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2364 EVT VT = N->getValueType(0);
2367 // fold (mulhu x, 0) -> 0
2368 if (N1C && N1C->isNullValue())
2370 // fold (mulhu x, 1) -> 0
2371 if (N1C && N1C->getAPIntValue() == 1)
2372 return DAG.getConstant(0, N0.getValueType());
2373 // fold (mulhu x, undef) -> 0
2374 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2375 return DAG.getConstant(0, VT);
2377 // If the type twice as wide is legal, transform the mulhu 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::ZERO_EXTEND, DL, NewVT, N0);
2385 N1 = DAG.getNode(ISD::ZERO_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, getShiftAmountTy(N1.getValueType())));
2389 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2396 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2397 /// give the opcodes for the two computations that are being performed. Return
2398 /// true if a simplification was made.
2399 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2401 // If the high half is not needed, just compute the low half.
2402 bool HiExists = N->hasAnyUseOfValue(1);
2404 (!LegalOperations ||
2405 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2406 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2407 return CombineTo(N, Res, Res);
2410 // If the low half is not needed, just compute the high half.
2411 bool LoExists = N->hasAnyUseOfValue(0);
2413 (!LegalOperations ||
2414 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2415 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2416 return CombineTo(N, Res, Res);
2419 // If both halves are used, return as it is.
2420 if (LoExists && HiExists)
2423 // If the two computed results can be simplified separately, separate them.
2425 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2426 AddToWorklist(Lo.getNode());
2427 SDValue LoOpt = combine(Lo.getNode());
2428 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2429 (!LegalOperations ||
2430 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2431 return CombineTo(N, LoOpt, LoOpt);
2435 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2436 AddToWorklist(Hi.getNode());
2437 SDValue HiOpt = combine(Hi.getNode());
2438 if (HiOpt.getNode() && HiOpt != Hi &&
2439 (!LegalOperations ||
2440 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2441 return CombineTo(N, HiOpt, HiOpt);
2447 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2448 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2449 if (Res.getNode()) return Res;
2451 EVT VT = N->getValueType(0);
2454 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2456 if (VT.isSimple() && !VT.isVector()) {
2457 MVT Simple = VT.getSimpleVT();
2458 unsigned SimpleSize = Simple.getSizeInBits();
2459 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2460 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2461 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2462 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2463 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2464 // Compute the high part as N1.
2465 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2466 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2467 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2468 // Compute the low part as N0.
2469 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2470 return CombineTo(N, Lo, Hi);
2477 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2478 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2479 if (Res.getNode()) return Res;
2481 EVT VT = N->getValueType(0);
2484 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2486 if (VT.isSimple() && !VT.isVector()) {
2487 MVT Simple = VT.getSimpleVT();
2488 unsigned SimpleSize = Simple.getSizeInBits();
2489 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2490 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2491 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2492 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2493 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2494 // Compute the high part as N1.
2495 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2496 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2497 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2498 // Compute the low part as N0.
2499 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2500 return CombineTo(N, Lo, Hi);
2507 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2508 // (smulo x, 2) -> (saddo x, x)
2509 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2510 if (C2->getAPIntValue() == 2)
2511 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2512 N->getOperand(0), N->getOperand(0));
2517 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2518 // (umulo x, 2) -> (uaddo x, x)
2519 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2520 if (C2->getAPIntValue() == 2)
2521 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2522 N->getOperand(0), N->getOperand(0));
2527 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2528 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2529 if (Res.getNode()) return Res;
2534 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2535 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2536 if (Res.getNode()) return Res;
2541 /// If this is a binary operator with two operands of the same opcode, try to
2543 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2544 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2545 EVT VT = N0.getValueType();
2546 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2548 // Bail early if none of these transforms apply.
2549 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2551 // For each of OP in AND/OR/XOR:
2552 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2553 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2554 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2555 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2556 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2558 // do not sink logical op inside of a vector extend, since it may combine
2560 EVT Op0VT = N0.getOperand(0).getValueType();
2561 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2562 N0.getOpcode() == ISD::SIGN_EXTEND ||
2563 N0.getOpcode() == ISD::BSWAP ||
2564 // Avoid infinite looping with PromoteIntBinOp.
2565 (N0.getOpcode() == ISD::ANY_EXTEND &&
2566 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2567 (N0.getOpcode() == ISD::TRUNCATE &&
2568 (!TLI.isZExtFree(VT, Op0VT) ||
2569 !TLI.isTruncateFree(Op0VT, VT)) &&
2570 TLI.isTypeLegal(Op0VT))) &&
2572 Op0VT == N1.getOperand(0).getValueType() &&
2573 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2574 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2575 N0.getOperand(0).getValueType(),
2576 N0.getOperand(0), N1.getOperand(0));
2577 AddToWorklist(ORNode.getNode());
2578 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2581 // For each of OP in SHL/SRL/SRA/AND...
2582 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2583 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2584 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2585 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2586 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2587 N0.getOperand(1) == N1.getOperand(1)) {
2588 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2589 N0.getOperand(0).getValueType(),
2590 N0.getOperand(0), N1.getOperand(0));
2591 AddToWorklist(ORNode.getNode());
2592 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2593 ORNode, N0.getOperand(1));
2596 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2597 // Only perform this optimization after type legalization and before
2598 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2599 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2600 // we don't want to undo this promotion.
2601 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2603 if ((N0.getOpcode() == ISD::BITCAST ||
2604 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2605 Level == AfterLegalizeTypes) {
2606 SDValue In0 = N0.getOperand(0);
2607 SDValue In1 = N1.getOperand(0);
2608 EVT In0Ty = In0.getValueType();
2609 EVT In1Ty = In1.getValueType();
2611 // If both incoming values are integers, and the original types are the
2613 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2614 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2615 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2616 AddToWorklist(Op.getNode());
2621 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2622 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2623 // If both shuffles use the same mask, and both shuffle within a single
2624 // vector, then it is worthwhile to move the swizzle after the operation.
2625 // The type-legalizer generates this pattern when loading illegal
2626 // vector types from memory. In many cases this allows additional shuffle
2628 // There are other cases where moving the shuffle after the xor/and/or
2629 // is profitable even if shuffles don't perform a swizzle.
2630 // If both shuffles use the same mask, and both shuffles have the same first
2631 // or second operand, then it might still be profitable to move the shuffle
2632 // after the xor/and/or operation.
2633 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2634 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2635 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2637 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2638 "Inputs to shuffles are not the same type");
2640 // Check that both shuffles use the same mask. The masks are known to be of
2641 // the same length because the result vector type is the same.
2642 // Check also that shuffles have only one use to avoid introducing extra
2644 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2645 SVN0->getMask().equals(SVN1->getMask())) {
2646 SDValue ShOp = N0->getOperand(1);
2648 // Don't try to fold this node if it requires introducing a
2649 // build vector of all zeros that might be illegal at this stage.
2650 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2652 ShOp = DAG.getConstant(0, VT);
2657 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2658 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2659 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2660 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2661 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2662 N0->getOperand(0), N1->getOperand(0));
2663 AddToWorklist(NewNode.getNode());
2664 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2665 &SVN0->getMask()[0]);
2668 // Don't try to fold this node if it requires introducing a
2669 // build vector of all zeros that might be illegal at this stage.
2670 ShOp = N0->getOperand(0);
2671 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2673 ShOp = DAG.getConstant(0, VT);
2678 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2679 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2680 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2681 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2682 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2683 N0->getOperand(1), N1->getOperand(1));
2684 AddToWorklist(NewNode.getNode());
2685 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2686 &SVN0->getMask()[0]);
2694 /// This contains all DAGCombine rules which reduce two values combined by
2695 /// an And operation to a single value. This makes them reusable in the context
2696 /// of visitSELECT(). Rules involving constants are not included as
2697 /// visitSELECT() already handles those cases.
2698 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2699 SDNode *LocReference) {
2700 EVT VT = N1.getValueType();
2702 // fold (and x, undef) -> 0
2703 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2704 return DAG.getConstant(0, VT);
2705 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2706 SDValue LL, LR, RL, RR, CC0, CC1;
2707 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2708 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2709 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2711 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2712 LL.getValueType().isInteger()) {
2713 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2714 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2715 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2716 LR.getValueType(), LL, RL);
2717 AddToWorklist(ORNode.getNode());
2718 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2720 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2721 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2722 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2723 LR.getValueType(), LL, RL);
2724 AddToWorklist(ANDNode.getNode());
2725 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2727 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2728 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2729 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2730 LR.getValueType(), LL, RL);
2731 AddToWorklist(ORNode.getNode());
2732 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2735 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2736 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2737 Op0 == Op1 && LL.getValueType().isInteger() &&
2738 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2739 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2740 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2741 cast<ConstantSDNode>(RR)->isNullValue()))) {
2742 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2743 LL, DAG.getConstant(1, LL.getValueType()));
2744 AddToWorklist(ADDNode.getNode());
2745 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2746 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2748 // canonicalize equivalent to ll == rl
2749 if (LL == RR && LR == RL) {
2750 Op1 = ISD::getSetCCSwappedOperands(Op1);
2753 if (LL == RL && LR == RR) {
2754 bool isInteger = LL.getValueType().isInteger();
2755 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2756 if (Result != ISD::SETCC_INVALID &&
2757 (!LegalOperations ||
2758 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2759 TLI.isOperationLegal(ISD::SETCC,
2760 getSetCCResultType(N0.getSimpleValueType())))))
2761 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2766 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2767 VT.getSizeInBits() <= 64) {
2768 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2769 APInt ADDC = ADDI->getAPIntValue();
2770 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2771 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2772 // immediate for an add, but it is legal if its top c2 bits are set,
2773 // transform the ADD so the immediate doesn't need to be materialized
2775 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2776 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2777 SRLI->getZExtValue());
2778 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2780 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2782 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2783 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2784 CombineTo(N0.getNode(), NewAdd);
2785 // Return N so it doesn't get rechecked!
2786 return SDValue(LocReference, 0);
2797 SDValue DAGCombiner::visitAND(SDNode *N) {
2798 SDValue N0 = N->getOperand(0);
2799 SDValue N1 = N->getOperand(1);
2800 EVT VT = N1.getValueType();
2803 if (VT.isVector()) {
2804 SDValue FoldedVOp = SimplifyVBinOp(N);
2805 if (FoldedVOp.getNode()) return FoldedVOp;
2807 // fold (and x, 0) -> 0, vector edition
2808 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2809 // do not return N0, because undef node may exist in N0
2810 return DAG.getConstant(
2811 APInt::getNullValue(
2812 N0.getValueType().getScalarType().getSizeInBits()),
2814 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2815 // do not return N1, because undef node may exist in N1
2816 return DAG.getConstant(
2817 APInt::getNullValue(
2818 N1.getValueType().getScalarType().getSizeInBits()),
2821 // fold (and x, -1) -> x, vector edition
2822 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2824 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2828 // fold (and c1, c2) -> c1&c2
2829 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2830 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2832 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2833 // canonicalize constant to RHS
2835 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2836 // fold (and x, -1) -> x
2837 if (N1C && N1C->isAllOnesValue())
2839 // if (and x, c) is known to be zero, return 0
2840 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2841 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2842 APInt::getAllOnesValue(BitWidth)))
2843 return DAG.getConstant(0, VT);
2845 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2847 // fold (and (or x, C), D) -> D if (C & D) == D
2848 if (N1C && N0.getOpcode() == ISD::OR)
2849 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2850 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2852 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2853 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2854 SDValue N0Op0 = N0.getOperand(0);
2855 APInt Mask = ~N1C->getAPIntValue();
2856 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2857 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2858 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2859 N0.getValueType(), N0Op0);
2861 // Replace uses of the AND with uses of the Zero extend node.
2864 // We actually want to replace all uses of the any_extend with the
2865 // zero_extend, to avoid duplicating things. This will later cause this
2866 // AND to be folded.
2867 CombineTo(N0.getNode(), Zext);
2868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2871 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2872 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2873 // already be zero by virtue of the width of the base type of the load.
2875 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2877 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2878 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2879 N0.getOpcode() == ISD::LOAD) {
2880 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2881 N0 : N0.getOperand(0) );
2883 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2884 // This can be a pure constant or a vector splat, in which case we treat the
2885 // vector as a scalar and use the splat value.
2886 APInt Constant = APInt::getNullValue(1);
2887 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2888 Constant = C->getAPIntValue();
2889 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2890 APInt SplatValue, SplatUndef;
2891 unsigned SplatBitSize;
2893 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2894 SplatBitSize, HasAnyUndefs);
2896 // Undef bits can contribute to a possible optimisation if set, so
2898 SplatValue |= SplatUndef;
2900 // The splat value may be something like "0x00FFFFFF", which means 0 for
2901 // the first vector value and FF for the rest, repeating. We need a mask
2902 // that will apply equally to all members of the vector, so AND all the
2903 // lanes of the constant together.
2904 EVT VT = Vector->getValueType(0);
2905 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2907 // If the splat value has been compressed to a bitlength lower
2908 // than the size of the vector lane, we need to re-expand it to
2910 if (BitWidth > SplatBitSize)
2911 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2912 SplatBitSize < BitWidth;
2913 SplatBitSize = SplatBitSize * 2)
2914 SplatValue |= SplatValue.shl(SplatBitSize);
2916 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2917 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2918 if (SplatBitSize % BitWidth == 0) {
2919 Constant = APInt::getAllOnesValue(BitWidth);
2920 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2921 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2926 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2927 // actually legal and isn't going to get expanded, else this is a false
2929 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2930 Load->getValueType(0),
2931 Load->getMemoryVT());
2933 // Resize the constant to the same size as the original memory access before
2934 // extension. If it is still the AllOnesValue then this AND is completely
2937 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2940 switch (Load->getExtensionType()) {
2941 default: B = false; break;
2942 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2944 case ISD::NON_EXTLOAD: B = true; break;
2947 if (B && Constant.isAllOnesValue()) {
2948 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2949 // preserve semantics once we get rid of the AND.
2950 SDValue NewLoad(Load, 0);
2951 if (Load->getExtensionType() == ISD::EXTLOAD) {
2952 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2953 Load->getValueType(0), SDLoc(Load),
2954 Load->getChain(), Load->getBasePtr(),
2955 Load->getOffset(), Load->getMemoryVT(),
2956 Load->getMemOperand());
2957 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2958 if (Load->getNumValues() == 3) {
2959 // PRE/POST_INC loads have 3 values.
2960 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2961 NewLoad.getValue(2) };
2962 CombineTo(Load, To, 3, true);
2964 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2968 // Fold the AND away, taking care not to fold to the old load node if we
2970 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2972 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2976 // fold (and (load x), 255) -> (zextload x, i8)
2977 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2978 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2979 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2980 (N0.getOpcode() == ISD::ANY_EXTEND &&
2981 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2982 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2983 LoadSDNode *LN0 = HasAnyExt
2984 ? cast<LoadSDNode>(N0.getOperand(0))
2985 : cast<LoadSDNode>(N0);
2986 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2987 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2988 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2989 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2990 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2991 EVT LoadedVT = LN0->getMemoryVT();
2992 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2994 if (ExtVT == LoadedVT &&
2995 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2999 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3000 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3001 LN0->getMemOperand());
3003 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3004 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3007 // Do not change the width of a volatile load.
3008 // Do not generate loads of non-round integer types since these can
3009 // be expensive (and would be wrong if the type is not byte sized).
3010 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3011 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3013 EVT PtrType = LN0->getOperand(1).getValueType();
3015 unsigned Alignment = LN0->getAlignment();
3016 SDValue NewPtr = LN0->getBasePtr();
3018 // For big endian targets, we need to add an offset to the pointer
3019 // to load the correct bytes. For little endian systems, we merely
3020 // need to read fewer bytes from the same pointer.
3021 if (TLI.isBigEndian()) {
3022 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3023 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3024 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3025 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3026 NewPtr, DAG.getConstant(PtrOff, PtrType));
3027 Alignment = MinAlign(Alignment, PtrOff);
3030 AddToWorklist(NewPtr.getNode());
3033 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3034 LN0->getChain(), NewPtr,
3035 LN0->getPointerInfo(),
3036 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3037 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3039 CombineTo(LN0, Load, Load.getValue(1));
3040 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3046 if (SDValue Combined = visitANDLike(N0, N1, N))
3049 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3050 if (N0.getOpcode() == N1.getOpcode()) {
3051 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3052 if (Tmp.getNode()) return Tmp;
3055 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3056 // fold (and (sra)) -> (and (srl)) when possible.
3057 if (!VT.isVector() &&
3058 SimplifyDemandedBits(SDValue(N, 0)))
3059 return SDValue(N, 0);
3061 // fold (zext_inreg (extload x)) -> (zextload x)
3062 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3063 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3064 EVT MemVT = LN0->getMemoryVT();
3065 // If we zero all the possible extended bits, then we can turn this into
3066 // a zextload if we are running before legalize or the operation is legal.
3067 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3068 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3069 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3070 ((!LegalOperations && !LN0->isVolatile()) ||
3071 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3072 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3073 LN0->getChain(), LN0->getBasePtr(),
3074 MemVT, LN0->getMemOperand());
3076 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3077 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3080 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3081 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3083 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3084 EVT MemVT = LN0->getMemoryVT();
3085 // If we zero all the possible extended bits, then we can turn this into
3086 // a zextload if we are running before legalize or the operation is legal.
3087 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3088 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3089 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3090 ((!LegalOperations && !LN0->isVolatile()) ||
3091 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3092 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3093 LN0->getChain(), LN0->getBasePtr(),
3094 MemVT, LN0->getMemOperand());
3096 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3097 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3100 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3101 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3102 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3103 N0.getOperand(1), false);
3104 if (BSwap.getNode())
3111 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3112 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3113 bool DemandHighBits) {
3114 if (!LegalOperations)
3117 EVT VT = N->getValueType(0);
3118 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3120 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3123 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3124 bool LookPassAnd0 = false;
3125 bool LookPassAnd1 = false;
3126 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3128 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3130 if (N0.getOpcode() == ISD::AND) {
3131 if (!N0.getNode()->hasOneUse())
3133 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3134 if (!N01C || N01C->getZExtValue() != 0xFF00)
3136 N0 = N0.getOperand(0);
3137 LookPassAnd0 = true;
3140 if (N1.getOpcode() == ISD::AND) {
3141 if (!N1.getNode()->hasOneUse())
3143 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3144 if (!N11C || N11C->getZExtValue() != 0xFF)
3146 N1 = N1.getOperand(0);
3147 LookPassAnd1 = true;
3150 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3152 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3154 if (!N0.getNode()->hasOneUse() ||
3155 !N1.getNode()->hasOneUse())
3158 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3159 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3162 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3165 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3166 SDValue N00 = N0->getOperand(0);
3167 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3168 if (!N00.getNode()->hasOneUse())
3170 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3171 if (!N001C || N001C->getZExtValue() != 0xFF)
3173 N00 = N00.getOperand(0);
3174 LookPassAnd0 = true;
3177 SDValue N10 = N1->getOperand(0);
3178 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3179 if (!N10.getNode()->hasOneUse())
3181 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3182 if (!N101C || N101C->getZExtValue() != 0xFF00)
3184 N10 = N10.getOperand(0);
3185 LookPassAnd1 = true;
3191 // Make sure everything beyond the low halfword gets set to zero since the SRL
3192 // 16 will clear the top bits.
3193 unsigned OpSizeInBits = VT.getSizeInBits();
3194 if (DemandHighBits && OpSizeInBits > 16) {
3195 // If the left-shift isn't masked out then the only way this is a bswap is
3196 // if all bits beyond the low 8 are 0. In that case the entire pattern
3197 // reduces to a left shift anyway: leave it for other parts of the combiner.
3201 // However, if the right shift isn't masked out then it might be because
3202 // it's not needed. See if we can spot that too.
3203 if (!LookPassAnd1 &&
3204 !DAG.MaskedValueIsZero(
3205 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3209 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3210 if (OpSizeInBits > 16)
3211 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3212 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3216 /// Return true if the specified node is an element that makes up a 32-bit
3217 /// packed halfword byteswap.
3218 /// ((x & 0x000000ff) << 8) |
3219 /// ((x & 0x0000ff00) >> 8) |
3220 /// ((x & 0x00ff0000) << 8) |
3221 /// ((x & 0xff000000) >> 8)
3222 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3223 if (!N.getNode()->hasOneUse())
3226 unsigned Opc = N.getOpcode();
3227 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3230 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3235 switch (N1C->getZExtValue()) {
3238 case 0xFF: Num = 0; break;
3239 case 0xFF00: Num = 1; break;
3240 case 0xFF0000: Num = 2; break;
3241 case 0xFF000000: Num = 3; break;
3244 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3245 SDValue N0 = N.getOperand(0);
3246 if (Opc == ISD::AND) {
3247 if (Num == 0 || Num == 2) {
3249 // (x >> 8) & 0xff0000
3250 if (N0.getOpcode() != ISD::SRL)
3252 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3253 if (!C || C->getZExtValue() != 8)
3256 // (x << 8) & 0xff00
3257 // (x << 8) & 0xff000000
3258 if (N0.getOpcode() != ISD::SHL)
3260 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3261 if (!C || C->getZExtValue() != 8)
3264 } else if (Opc == ISD::SHL) {
3266 // (x & 0xff0000) << 8
3267 if (Num != 0 && Num != 2)
3269 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3270 if (!C || C->getZExtValue() != 8)
3272 } else { // Opc == ISD::SRL
3273 // (x & 0xff00) >> 8
3274 // (x & 0xff000000) >> 8
3275 if (Num != 1 && Num != 3)
3277 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3278 if (!C || C->getZExtValue() != 8)
3285 Parts[Num] = N0.getOperand(0).getNode();
3289 /// Match a 32-bit packed halfword bswap. That is
3290 /// ((x & 0x000000ff) << 8) |
3291 /// ((x & 0x0000ff00) >> 8) |
3292 /// ((x & 0x00ff0000) << 8) |
3293 /// ((x & 0xff000000) >> 8)
3294 /// => (rotl (bswap x), 16)
3295 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3296 if (!LegalOperations)
3299 EVT VT = N->getValueType(0);
3302 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3306 // (or (or (and), (and)), (or (and), (and)))
3307 // (or (or (or (and), (and)), (and)), (and))
3308 if (N0.getOpcode() != ISD::OR)
3310 SDValue N00 = N0.getOperand(0);
3311 SDValue N01 = N0.getOperand(1);
3312 SDNode *Parts[4] = {};
3314 if (N1.getOpcode() == ISD::OR &&
3315 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3316 // (or (or (and), (and)), (or (and), (and)))
3317 SDValue N000 = N00.getOperand(0);
3318 if (!isBSwapHWordElement(N000, Parts))
3321 SDValue N001 = N00.getOperand(1);
3322 if (!isBSwapHWordElement(N001, Parts))
3324 SDValue N010 = N01.getOperand(0);
3325 if (!isBSwapHWordElement(N010, Parts))
3327 SDValue N011 = N01.getOperand(1);
3328 if (!isBSwapHWordElement(N011, Parts))
3331 // (or (or (or (and), (and)), (and)), (and))
3332 if (!isBSwapHWordElement(N1, Parts))
3334 if (!isBSwapHWordElement(N01, Parts))
3336 if (N00.getOpcode() != ISD::OR)
3338 SDValue N000 = N00.getOperand(0);
3339 if (!isBSwapHWordElement(N000, Parts))
3341 SDValue N001 = N00.getOperand(1);
3342 if (!isBSwapHWordElement(N001, Parts))
3346 // Make sure the parts are all coming from the same node.
3347 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3350 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3351 SDValue(Parts[0],0));
3353 // Result of the bswap should be rotated by 16. If it's not legal, then
3354 // do (x << 16) | (x >> 16).
3355 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3356 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3357 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3358 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3359 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3360 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3361 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3362 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3365 /// This contains all DAGCombine rules which reduce two values combined by
3366 /// an Or operation to a single value \see visitANDLike().
3367 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3368 EVT VT = N1.getValueType();
3369 // fold (or x, undef) -> -1
3370 if (!LegalOperations &&
3371 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3372 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3373 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3375 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3376 SDValue LL, LR, RL, RR, CC0, CC1;
3377 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3378 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3379 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3381 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3382 LL.getValueType().isInteger()) {
3383 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3384 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3385 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3386 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3387 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3388 LR.getValueType(), LL, RL);
3389 AddToWorklist(ORNode.getNode());
3390 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3392 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3393 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3394 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3395 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3396 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3397 LR.getValueType(), LL, RL);
3398 AddToWorklist(ANDNode.getNode());
3399 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3402 // canonicalize equivalent to ll == rl
3403 if (LL == RR && LR == RL) {
3404 Op1 = ISD::getSetCCSwappedOperands(Op1);
3407 if (LL == RL && LR == RR) {
3408 bool isInteger = LL.getValueType().isInteger();
3409 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3410 if (Result != ISD::SETCC_INVALID &&
3411 (!LegalOperations ||
3412 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3413 TLI.isOperationLegal(ISD::SETCC,
3414 getSetCCResultType(N0.getValueType())))))
3415 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3420 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3421 if (N0.getOpcode() == ISD::AND &&
3422 N1.getOpcode() == ISD::AND &&
3423 N0.getOperand(1).getOpcode() == ISD::Constant &&
3424 N1.getOperand(1).getOpcode() == ISD::Constant &&
3425 // Don't increase # computations.
3426 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3427 // We can only do this xform if we know that bits from X that are set in C2
3428 // but not in C1 are already zero. Likewise for Y.
3429 const APInt &LHSMask =
3430 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3431 const APInt &RHSMask =
3432 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3434 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3435 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3436 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3437 N0.getOperand(0), N1.getOperand(0));
3438 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3439 DAG.getConstant(LHSMask | RHSMask, VT));
3443 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3444 if (N0.getOpcode() == ISD::AND &&
3445 N1.getOpcode() == ISD::AND &&
3446 N0.getOperand(0) == N1.getOperand(0) &&
3447 // Don't increase # computations.
3448 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3449 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3450 N0.getOperand(1), N1.getOperand(1));
3451 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3457 SDValue DAGCombiner::visitOR(SDNode *N) {
3458 SDValue N0 = N->getOperand(0);
3459 SDValue N1 = N->getOperand(1);
3460 EVT VT = N1.getValueType();
3463 if (VT.isVector()) {
3464 SDValue FoldedVOp = SimplifyVBinOp(N);
3465 if (FoldedVOp.getNode()) return FoldedVOp;
3467 // fold (or x, 0) -> x, vector edition
3468 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3470 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3473 // fold (or x, -1) -> -1, vector edition
3474 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3475 // do not return N0, because undef node may exist in N0
3476 return DAG.getConstant(
3477 APInt::getAllOnesValue(
3478 N0.getValueType().getScalarType().getSizeInBits()),
3480 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3481 // do not return N1, because undef node may exist in N1
3482 return DAG.getConstant(
3483 APInt::getAllOnesValue(
3484 N1.getValueType().getScalarType().getSizeInBits()),
3487 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3488 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3489 // Do this only if the resulting shuffle is legal.
3490 if (isa<ShuffleVectorSDNode>(N0) &&
3491 isa<ShuffleVectorSDNode>(N1) &&
3492 // Avoid folding a node with illegal type.
3493 TLI.isTypeLegal(VT) &&
3494 N0->getOperand(1) == N1->getOperand(1) &&
3495 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3496 bool CanFold = true;
3497 unsigned NumElts = VT.getVectorNumElements();
3498 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3499 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3500 // We construct two shuffle masks:
3501 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3502 // and N1 as the second operand.
3503 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3504 // and N0 as the second operand.
3505 // We do this because OR is commutable and therefore there might be
3506 // two ways to fold this node into a shuffle.
3507 SmallVector<int,4> Mask1;
3508 SmallVector<int,4> Mask2;
3510 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3511 int M0 = SV0->getMaskElt(i);
3512 int M1 = SV1->getMaskElt(i);
3514 // Both shuffle indexes are undef. Propagate Undef.
3515 if (M0 < 0 && M1 < 0) {
3516 Mask1.push_back(M0);
3517 Mask2.push_back(M0);
3521 if (M0 < 0 || M1 < 0 ||
3522 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3523 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3528 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3529 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3533 // Fold this sequence only if the resulting shuffle is 'legal'.
3534 if (TLI.isShuffleMaskLegal(Mask1, VT))
3535 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3536 N1->getOperand(0), &Mask1[0]);
3537 if (TLI.isShuffleMaskLegal(Mask2, VT))
3538 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3539 N0->getOperand(0), &Mask2[0]);
3544 // fold (or c1, c2) -> c1|c2
3545 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3546 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3548 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3549 // canonicalize constant to RHS
3551 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3552 // fold (or x, 0) -> x
3553 if (N1C && N1C->isNullValue())
3555 // fold (or x, -1) -> -1
3556 if (N1C && N1C->isAllOnesValue())
3558 // fold (or x, c) -> c iff (x & ~c) == 0
3559 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3562 if (SDValue Combined = visitORLike(N0, N1, N))
3565 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3566 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3567 if (BSwap.getNode())
3569 BSwap = MatchBSwapHWordLow(N, N0, N1);
3570 if (BSwap.getNode())
3574 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3576 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3577 // iff (c1 & c2) == 0.
3578 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3579 isa<ConstantSDNode>(N0.getOperand(1))) {
3580 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3581 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3582 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3584 ISD::AND, SDLoc(N), VT,
3585 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3589 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3590 if (N0.getOpcode() == N1.getOpcode()) {
3591 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3592 if (Tmp.getNode()) return Tmp;
3595 // See if this is some rotate idiom.
3596 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3597 return SDValue(Rot, 0);
3599 // Simplify the operands using demanded-bits information.
3600 if (!VT.isVector() &&
3601 SimplifyDemandedBits(SDValue(N, 0)))
3602 return SDValue(N, 0);
3607 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3608 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3609 if (Op.getOpcode() == ISD::AND) {
3610 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3611 Mask = Op.getOperand(1);
3612 Op = Op.getOperand(0);
3618 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3626 // Return true if we can prove that, whenever Neg and Pos are both in the
3627 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3628 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3630 // (or (shift1 X, Neg), (shift2 X, Pos))
3632 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3633 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3634 // to consider shift amounts with defined behavior.
3635 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3636 // If OpSize is a power of 2 then:
3638 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3639 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3641 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3642 // for the stronger condition:
3644 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3646 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3647 // we can just replace Neg with Neg' for the rest of the function.
3649 // In other cases we check for the even stronger condition:
3651 // Neg == OpSize - Pos [B]
3653 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3654 // behavior if Pos == 0 (and consequently Neg == OpSize).
3656 // We could actually use [A] whenever OpSize is a power of 2, but the
3657 // only extra cases that it would match are those uninteresting ones
3658 // where Neg and Pos are never in range at the same time. E.g. for
3659 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3660 // as well as (sub 32, Pos), but:
3662 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3664 // always invokes undefined behavior for 32-bit X.
3666 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3667 unsigned MaskLoBits = 0;
3668 if (Neg.getOpcode() == ISD::AND &&
3669 isPowerOf2_64(OpSize) &&
3670 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3671 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3672 Neg = Neg.getOperand(0);
3673 MaskLoBits = Log2_64(OpSize);
3676 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3677 if (Neg.getOpcode() != ISD::SUB)
3679 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3682 SDValue NegOp1 = Neg.getOperand(1);
3684 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3685 // Pos'. The truncation is redundant for the purpose of the equality.
3687 Pos.getOpcode() == ISD::AND &&
3688 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3689 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3690 Pos = Pos.getOperand(0);
3692 // The condition we need is now:
3694 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3696 // If NegOp1 == Pos then we need:
3698 // OpSize & Mask == NegC & Mask
3700 // (because "x & Mask" is a truncation and distributes through subtraction).
3703 Width = NegC->getAPIntValue();
3704 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3705 // Then the condition we want to prove becomes:
3707 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3709 // which, again because "x & Mask" is a truncation, becomes:
3711 // NegC & Mask == (OpSize - PosC) & Mask
3712 // OpSize & Mask == (NegC + PosC) & Mask
3713 else if (Pos.getOpcode() == ISD::ADD &&
3714 Pos.getOperand(0) == NegOp1 &&
3715 Pos.getOperand(1).getOpcode() == ISD::Constant)
3716 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3717 NegC->getAPIntValue());
3721 // Now we just need to check that OpSize & Mask == Width & Mask.
3723 // Opsize & Mask is 0 since Mask is Opsize - 1.
3724 return Width.getLoBits(MaskLoBits) == 0;
3725 return Width == OpSize;
3728 // A subroutine of MatchRotate used once we have found an OR of two opposite
3729 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3730 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3731 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3732 // Neg with outer conversions stripped away.
3733 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3734 SDValue Neg, SDValue InnerPos,
3735 SDValue InnerNeg, unsigned PosOpcode,
3736 unsigned NegOpcode, SDLoc DL) {
3737 // fold (or (shl x, (*ext y)),
3738 // (srl x, (*ext (sub 32, y)))) ->
3739 // (rotl x, y) or (rotr x, (sub 32, y))
3741 // fold (or (shl x, (*ext (sub 32, y))),
3742 // (srl x, (*ext y))) ->
3743 // (rotr x, y) or (rotl x, (sub 32, y))
3744 EVT VT = Shifted.getValueType();
3745 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3746 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3747 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3748 HasPos ? Pos : Neg).getNode();
3754 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3755 // idioms for rotate, and if the target supports rotation instructions, generate
3757 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3758 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3759 EVT VT = LHS.getValueType();
3760 if (!TLI.isTypeLegal(VT)) return nullptr;
3762 // The target must have at least one rotate flavor.
3763 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3764 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3765 if (!HasROTL && !HasROTR) return nullptr;
3767 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3768 SDValue LHSShift; // The shift.
3769 SDValue LHSMask; // AND value if any.
3770 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3771 return nullptr; // Not part of a rotate.
3773 SDValue RHSShift; // The shift.
3774 SDValue RHSMask; // AND value if any.
3775 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3776 return nullptr; // Not part of a rotate.
3778 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3779 return nullptr; // Not shifting the same value.
3781 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3782 return nullptr; // Shifts must disagree.
3784 // Canonicalize shl to left side in a shl/srl pair.
3785 if (RHSShift.getOpcode() == ISD::SHL) {
3786 std::swap(LHS, RHS);
3787 std::swap(LHSShift, RHSShift);
3788 std::swap(LHSMask , RHSMask );
3791 unsigned OpSizeInBits = VT.getSizeInBits();
3792 SDValue LHSShiftArg = LHSShift.getOperand(0);
3793 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3794 SDValue RHSShiftArg = RHSShift.getOperand(0);
3795 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3797 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3798 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3799 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3800 RHSShiftAmt.getOpcode() == ISD::Constant) {
3801 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3802 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3803 if ((LShVal + RShVal) != OpSizeInBits)
3806 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3807 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3809 // If there is an AND of either shifted operand, apply it to the result.
3810 if (LHSMask.getNode() || RHSMask.getNode()) {
3811 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3813 if (LHSMask.getNode()) {
3814 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3815 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3817 if (RHSMask.getNode()) {
3818 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3819 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3822 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3825 return Rot.getNode();
3828 // If there is a mask here, and we have a variable shift, we can't be sure
3829 // that we're masking out the right stuff.
3830 if (LHSMask.getNode() || RHSMask.getNode())
3833 // If the shift amount is sign/zext/any-extended just peel it off.
3834 SDValue LExtOp0 = LHSShiftAmt;
3835 SDValue RExtOp0 = RHSShiftAmt;
3836 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3837 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3838 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3839 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3840 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3841 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3842 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3843 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3844 LExtOp0 = LHSShiftAmt.getOperand(0);
3845 RExtOp0 = RHSShiftAmt.getOperand(0);
3848 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3849 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3853 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3854 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3861 SDValue DAGCombiner::visitXOR(SDNode *N) {
3862 SDValue N0 = N->getOperand(0);
3863 SDValue N1 = N->getOperand(1);
3864 EVT VT = N0.getValueType();
3867 if (VT.isVector()) {
3868 SDValue FoldedVOp = SimplifyVBinOp(N);
3869 if (FoldedVOp.getNode()) return FoldedVOp;
3871 // fold (xor x, 0) -> x, vector edition
3872 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3874 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3878 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3879 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3880 return DAG.getConstant(0, VT);
3881 // fold (xor x, undef) -> undef
3882 if (N0.getOpcode() == ISD::UNDEF)
3884 if (N1.getOpcode() == ISD::UNDEF)
3886 // fold (xor c1, c2) -> c1^c2
3887 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3888 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3890 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3891 // canonicalize constant to RHS
3893 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3894 // fold (xor x, 0) -> x
3895 if (N1C && N1C->isNullValue())
3898 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3901 // fold !(x cc y) -> (x !cc y)
3902 SDValue LHS, RHS, CC;
3903 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3904 bool isInt = LHS.getValueType().isInteger();
3905 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3908 if (!LegalOperations ||
3909 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3910 switch (N0.getOpcode()) {
3912 llvm_unreachable("Unhandled SetCC Equivalent!");
3914 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3915 case ISD::SELECT_CC:
3916 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3917 N0.getOperand(3), NotCC);
3922 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3923 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3924 N0.getNode()->hasOneUse() &&
3925 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3926 SDValue V = N0.getOperand(0);
3927 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3928 DAG.getConstant(1, V.getValueType()));
3929 AddToWorklist(V.getNode());
3930 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3933 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3934 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3935 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3936 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3937 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3938 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3939 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3940 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3941 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3942 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3945 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3946 if (N1C && N1C->isAllOnesValue() &&
3947 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3948 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3949 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3950 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3951 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3952 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3953 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3954 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3957 // fold (xor (and x, y), y) -> (and (not x), y)
3958 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3959 N0->getOperand(1) == N1) {
3960 SDValue X = N0->getOperand(0);
3961 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3962 AddToWorklist(NotX.getNode());
3963 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3965 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3966 if (N1C && N0.getOpcode() == ISD::XOR) {
3967 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3968 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3970 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3971 DAG.getConstant(N1C->getAPIntValue() ^
3972 N00C->getAPIntValue(), VT));
3974 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3975 DAG.getConstant(N1C->getAPIntValue() ^
3976 N01C->getAPIntValue(), VT));
3978 // fold (xor x, x) -> 0
3980 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3982 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
3983 // Here is a concrete example of this equivalence:
3985 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
3986 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
3990 // i16 ~1 == 0b1111111111111110
3991 // i16 rol(~1, 14) == 0b1011111111111111
3993 // Some additional tips to help conceptualize this transform:
3994 // - Try to see the operation as placing a single zero in a value of all ones.
3995 // - There exists no value for x which would allow the result to contain zero.
3996 // - Values of x larger than the bitwidth are undefined and do not require a
3997 // consistent result.
3998 // - Pushing the zero left requires shifting one bits in from the right.
3999 // A rotate left of ~1 is a nice way of achieving the desired result.
4000 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4001 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4002 if (N0.getOpcode() == ISD::SHL)
4003 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4004 if (N1C->isAllOnesValue() && ShlLHS->isOne())
4005 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT),
4008 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4009 if (N0.getOpcode() == N1.getOpcode()) {
4010 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4011 if (Tmp.getNode()) return Tmp;
4014 // Simplify the expression using non-local knowledge.
4015 if (!VT.isVector() &&
4016 SimplifyDemandedBits(SDValue(N, 0)))
4017 return SDValue(N, 0);
4022 /// Handle transforms common to the three shifts, when the shift amount is a
4024 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4025 // We can't and shouldn't fold opaque constants.
4026 if (Amt->isOpaque())
4029 SDNode *LHS = N->getOperand(0).getNode();
4030 if (!LHS->hasOneUse()) return SDValue();
4032 // We want to pull some binops through shifts, so that we have (and (shift))
4033 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4034 // thing happens with address calculations, so it's important to canonicalize
4036 bool HighBitSet = false; // Can we transform this if the high bit is set?
4038 switch (LHS->getOpcode()) {
4039 default: return SDValue();
4042 HighBitSet = false; // We can only transform sra if the high bit is clear.
4045 HighBitSet = true; // We can only transform sra if the high bit is set.
4048 if (N->getOpcode() != ISD::SHL)
4049 return SDValue(); // only shl(add) not sr[al](add).
4050 HighBitSet = false; // We can only transform sra if the high bit is clear.
4054 // We require the RHS of the binop to be a constant and not opaque as well.
4055 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4056 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4058 // FIXME: disable this unless the input to the binop is a shift by a constant.
4059 // If it is not a shift, it pessimizes some common cases like:
4061 // void foo(int *X, int i) { X[i & 1235] = 1; }
4062 // int bar(int *X, int i) { return X[i & 255]; }
4063 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4064 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4065 BinOpLHSVal->getOpcode() != ISD::SRA &&
4066 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4067 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4070 EVT VT = N->getValueType(0);
4072 // If this is a signed shift right, and the high bit is modified by the
4073 // logical operation, do not perform the transformation. The highBitSet
4074 // boolean indicates the value of the high bit of the constant which would
4075 // cause it to be modified for this operation.
4076 if (N->getOpcode() == ISD::SRA) {
4077 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4078 if (BinOpRHSSignSet != HighBitSet)
4082 if (!TLI.isDesirableToCommuteWithShift(LHS))
4085 // Fold the constants, shifting the binop RHS by the shift amount.
4086 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4088 LHS->getOperand(1), N->getOperand(1));
4089 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4091 // Create the new shift.
4092 SDValue NewShift = DAG.getNode(N->getOpcode(),
4093 SDLoc(LHS->getOperand(0)),
4094 VT, LHS->getOperand(0), N->getOperand(1));
4096 // Create the new binop.
4097 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4100 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4101 assert(N->getOpcode() == ISD::TRUNCATE);
4102 assert(N->getOperand(0).getOpcode() == ISD::AND);
4104 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4105 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4106 SDValue N01 = N->getOperand(0).getOperand(1);
4108 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4109 EVT TruncVT = N->getValueType(0);
4110 SDValue N00 = N->getOperand(0).getOperand(0);
4111 APInt TruncC = N01C->getAPIntValue();
4112 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4114 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4115 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4116 DAG.getConstant(TruncC, TruncVT));
4123 SDValue DAGCombiner::visitRotate(SDNode *N) {
4124 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4125 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4126 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4127 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4128 if (NewOp1.getNode())
4129 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4130 N->getOperand(0), NewOp1);
4135 SDValue DAGCombiner::visitSHL(SDNode *N) {
4136 SDValue N0 = N->getOperand(0);
4137 SDValue N1 = N->getOperand(1);
4138 EVT VT = N0.getValueType();
4139 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4142 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4143 if (VT.isVector()) {
4144 SDValue FoldedVOp = SimplifyVBinOp(N);
4145 if (FoldedVOp.getNode()) return FoldedVOp;
4147 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4148 // If setcc produces all-one true value then:
4149 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4150 if (N1CV && N1CV->isConstant()) {
4151 if (N0.getOpcode() == ISD::AND) {
4152 SDValue N00 = N0->getOperand(0);
4153 SDValue N01 = N0->getOperand(1);
4154 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4156 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4157 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4158 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4159 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4160 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4163 N1C = isConstOrConstSplat(N1);
4168 // fold (shl c1, c2) -> c1<<c2
4169 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4171 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4172 // fold (shl 0, x) -> 0
4173 if (N0C && N0C->isNullValue())
4175 // fold (shl x, c >= size(x)) -> undef
4176 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4177 return DAG.getUNDEF(VT);
4178 // fold (shl x, 0) -> x
4179 if (N1C && N1C->isNullValue())
4181 // fold (shl undef, x) -> 0
4182 if (N0.getOpcode() == ISD::UNDEF)
4183 return DAG.getConstant(0, VT);
4184 // if (shl x, c) is known to be zero, return 0
4185 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4186 APInt::getAllOnesValue(OpSizeInBits)))
4187 return DAG.getConstant(0, VT);
4188 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4189 if (N1.getOpcode() == ISD::TRUNCATE &&
4190 N1.getOperand(0).getOpcode() == ISD::AND) {
4191 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4192 if (NewOp1.getNode())
4193 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4196 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4197 return SDValue(N, 0);
4199 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4200 if (N1C && N0.getOpcode() == ISD::SHL) {
4201 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4202 uint64_t c1 = N0C1->getZExtValue();
4203 uint64_t c2 = N1C->getZExtValue();
4204 if (c1 + c2 >= OpSizeInBits)
4205 return DAG.getConstant(0, VT);
4206 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4207 DAG.getConstant(c1 + c2, N1.getValueType()));
4211 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4212 // For this to be valid, the second form must not preserve any of the bits
4213 // that are shifted out by the inner shift in the first form. This means
4214 // the outer shift size must be >= the number of bits added by the ext.
4215 // As a corollary, we don't care what kind of ext it is.
4216 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4217 N0.getOpcode() == ISD::ANY_EXTEND ||
4218 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4219 N0.getOperand(0).getOpcode() == ISD::SHL) {
4220 SDValue N0Op0 = N0.getOperand(0);
4221 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4222 uint64_t c1 = N0Op0C1->getZExtValue();
4223 uint64_t c2 = N1C->getZExtValue();
4224 EVT InnerShiftVT = N0Op0.getValueType();
4225 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4226 if (c2 >= OpSizeInBits - InnerShiftSize) {
4227 if (c1 + c2 >= OpSizeInBits)
4228 return DAG.getConstant(0, VT);
4229 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4230 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4231 N0Op0->getOperand(0)),
4232 DAG.getConstant(c1 + c2, N1.getValueType()));
4237 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4238 // Only fold this if the inner zext has no other uses to avoid increasing
4239 // the total number of instructions.
4240 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4241 N0.getOperand(0).getOpcode() == ISD::SRL) {
4242 SDValue N0Op0 = N0.getOperand(0);
4243 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4244 uint64_t c1 = N0Op0C1->getZExtValue();
4245 if (c1 < VT.getScalarSizeInBits()) {
4246 uint64_t c2 = N1C->getZExtValue();
4248 SDValue NewOp0 = N0.getOperand(0);
4249 EVT CountVT = NewOp0.getOperand(1).getValueType();
4250 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4251 NewOp0, DAG.getConstant(c2, CountVT));
4252 AddToWorklist(NewSHL.getNode());
4253 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4259 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4260 // (and (srl x, (sub c1, c2), MASK)
4261 // Only fold this if the inner shift has no other uses -- if it does, folding
4262 // this will increase the total number of instructions.
4263 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4264 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4265 uint64_t c1 = N0C1->getZExtValue();
4266 if (c1 < OpSizeInBits) {
4267 uint64_t c2 = N1C->getZExtValue();
4268 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4271 Mask = Mask.shl(c2 - c1);
4272 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4273 DAG.getConstant(c2 - c1, N1.getValueType()));
4275 Mask = Mask.lshr(c1 - c2);
4276 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4277 DAG.getConstant(c1 - c2, N1.getValueType()));
4279 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4280 DAG.getConstant(Mask, VT));
4284 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4285 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4286 unsigned BitSize = VT.getScalarSizeInBits();
4287 SDValue HiBitsMask =
4288 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4289 BitSize - N1C->getZExtValue()), VT);
4290 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4294 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4295 // Variant of version done on multiply, except mul by a power of 2 is turned
4298 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4299 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4300 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4301 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4302 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4303 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4307 SDValue NewSHL = visitShiftByConstant(N, N1C);
4308 if (NewSHL.getNode())
4315 SDValue DAGCombiner::visitSRA(SDNode *N) {
4316 SDValue N0 = N->getOperand(0);
4317 SDValue N1 = N->getOperand(1);
4318 EVT VT = N0.getValueType();
4319 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4322 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4323 if (VT.isVector()) {
4324 SDValue FoldedVOp = SimplifyVBinOp(N);
4325 if (FoldedVOp.getNode()) return FoldedVOp;
4327 N1C = isConstOrConstSplat(N1);
4330 // fold (sra c1, c2) -> (sra c1, c2)
4331 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4333 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4334 // fold (sra 0, x) -> 0
4335 if (N0C && N0C->isNullValue())
4337 // fold (sra -1, x) -> -1
4338 if (N0C && N0C->isAllOnesValue())
4340 // fold (sra x, (setge c, size(x))) -> undef
4341 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4342 return DAG.getUNDEF(VT);
4343 // fold (sra x, 0) -> x
4344 if (N1C && N1C->isNullValue())
4346 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4348 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4349 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4350 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4352 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4353 ExtVT, VT.getVectorNumElements());
4354 if ((!LegalOperations ||
4355 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4356 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4357 N0.getOperand(0), DAG.getValueType(ExtVT));
4360 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4361 if (N1C && N0.getOpcode() == ISD::SRA) {
4362 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4363 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4364 if (Sum >= OpSizeInBits)
4365 Sum = OpSizeInBits - 1;
4366 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4367 DAG.getConstant(Sum, N1.getValueType()));
4371 // fold (sra (shl X, m), (sub result_size, n))
4372 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4373 // result_size - n != m.
4374 // If truncate is free for the target sext(shl) is likely to result in better
4376 if (N0.getOpcode() == ISD::SHL && N1C) {
4377 // Get the two constanst of the shifts, CN0 = m, CN = n.
4378 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4380 LLVMContext &Ctx = *DAG.getContext();
4381 // Determine what the truncate's result bitsize and type would be.
4382 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4385 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4387 // Determine the residual right-shift amount.
4388 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4390 // If the shift is not a no-op (in which case this should be just a sign
4391 // extend already), the truncated to type is legal, sign_extend is legal
4392 // on that type, and the truncate to that type is both legal and free,
4393 // perform the transform.
4394 if ((ShiftAmt > 0) &&
4395 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4396 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4397 TLI.isTruncateFree(VT, TruncVT)) {
4399 SDValue Amt = DAG.getConstant(ShiftAmt,
4400 getShiftAmountTy(N0.getOperand(0).getValueType()));
4401 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4402 N0.getOperand(0), Amt);
4403 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4405 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4406 N->getValueType(0), Trunc);
4411 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4412 if (N1.getOpcode() == ISD::TRUNCATE &&
4413 N1.getOperand(0).getOpcode() == ISD::AND) {
4414 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4415 if (NewOp1.getNode())
4416 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4419 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4420 // if c1 is equal to the number of bits the trunc removes
4421 if (N0.getOpcode() == ISD::TRUNCATE &&
4422 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4423 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4424 N0.getOperand(0).hasOneUse() &&
4425 N0.getOperand(0).getOperand(1).hasOneUse() &&
4427 SDValue N0Op0 = N0.getOperand(0);
4428 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4429 unsigned LargeShiftVal = LargeShift->getZExtValue();
4430 EVT LargeVT = N0Op0.getValueType();
4432 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4434 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4435 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4436 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4437 N0Op0.getOperand(0), Amt);
4438 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4443 // Simplify, based on bits shifted out of the LHS.
4444 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4445 return SDValue(N, 0);
4448 // If the sign bit is known to be zero, switch this to a SRL.
4449 if (DAG.SignBitIsZero(N0))
4450 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4453 SDValue NewSRA = visitShiftByConstant(N, N1C);
4454 if (NewSRA.getNode())
4461 SDValue DAGCombiner::visitSRL(SDNode *N) {
4462 SDValue N0 = N->getOperand(0);
4463 SDValue N1 = N->getOperand(1);
4464 EVT VT = N0.getValueType();
4465 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4468 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4469 if (VT.isVector()) {
4470 SDValue FoldedVOp = SimplifyVBinOp(N);
4471 if (FoldedVOp.getNode()) return FoldedVOp;
4473 N1C = isConstOrConstSplat(N1);
4476 // fold (srl c1, c2) -> c1 >>u c2
4477 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4479 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4480 // fold (srl 0, x) -> 0
4481 if (N0C && N0C->isNullValue())
4483 // fold (srl x, c >= size(x)) -> undef
4484 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4485 return DAG.getUNDEF(VT);
4486 // fold (srl x, 0) -> x
4487 if (N1C && N1C->isNullValue())
4489 // if (srl x, c) is known to be zero, return 0
4490 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4491 APInt::getAllOnesValue(OpSizeInBits)))
4492 return DAG.getConstant(0, VT);
4494 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4495 if (N1C && N0.getOpcode() == ISD::SRL) {
4496 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4497 uint64_t c1 = N01C->getZExtValue();
4498 uint64_t c2 = N1C->getZExtValue();
4499 if (c1 + c2 >= OpSizeInBits)
4500 return DAG.getConstant(0, VT);
4501 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4502 DAG.getConstant(c1 + c2, N1.getValueType()));
4506 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4507 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4508 N0.getOperand(0).getOpcode() == ISD::SRL &&
4509 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4511 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4512 uint64_t c2 = N1C->getZExtValue();
4513 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4514 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4515 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4516 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4517 if (c1 + OpSizeInBits == InnerShiftSize) {
4518 if (c1 + c2 >= InnerShiftSize)
4519 return DAG.getConstant(0, VT);
4520 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4521 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4522 N0.getOperand(0)->getOperand(0),
4523 DAG.getConstant(c1 + c2, ShiftCountVT)));
4527 // fold (srl (shl x, c), c) -> (and x, cst2)
4528 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4529 unsigned BitSize = N0.getScalarValueSizeInBits();
4530 if (BitSize <= 64) {
4531 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4532 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4533 DAG.getConstant(~0ULL >> ShAmt, VT));
4537 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4538 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4539 // Shifting in all undef bits?
4540 EVT SmallVT = N0.getOperand(0).getValueType();
4541 unsigned BitSize = SmallVT.getScalarSizeInBits();
4542 if (N1C->getZExtValue() >= BitSize)
4543 return DAG.getUNDEF(VT);
4545 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4546 uint64_t ShiftAmt = N1C->getZExtValue();
4547 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4549 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4550 AddToWorklist(SmallShift.getNode());
4551 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4552 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4553 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4554 DAG.getConstant(Mask, VT));
4558 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4559 // bit, which is unmodified by sra.
4560 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4561 if (N0.getOpcode() == ISD::SRA)
4562 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4565 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4566 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4567 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4568 APInt KnownZero, KnownOne;
4569 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4571 // If any of the input bits are KnownOne, then the input couldn't be all
4572 // zeros, thus the result of the srl will always be zero.
4573 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4575 // If all of the bits input the to ctlz node are known to be zero, then
4576 // the result of the ctlz is "32" and the result of the shift is one.
4577 APInt UnknownBits = ~KnownZero;
4578 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4580 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4581 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4582 // Okay, we know that only that the single bit specified by UnknownBits
4583 // could be set on input to the CTLZ node. If this bit is set, the SRL
4584 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4585 // to an SRL/XOR pair, which is likely to simplify more.
4586 unsigned ShAmt = UnknownBits.countTrailingZeros();
4587 SDValue Op = N0.getOperand(0);
4590 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4591 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4592 AddToWorklist(Op.getNode());
4595 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4596 Op, DAG.getConstant(1, VT));
4600 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4601 if (N1.getOpcode() == ISD::TRUNCATE &&
4602 N1.getOperand(0).getOpcode() == ISD::AND) {
4603 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4604 if (NewOp1.getNode())
4605 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4608 // fold operands of srl based on knowledge that the low bits are not
4610 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4611 return SDValue(N, 0);
4614 SDValue NewSRL = visitShiftByConstant(N, N1C);
4615 if (NewSRL.getNode())
4619 // Attempt to convert a srl of a load into a narrower zero-extending load.
4620 SDValue NarrowLoad = ReduceLoadWidth(N);
4621 if (NarrowLoad.getNode())
4624 // Here is a common situation. We want to optimize:
4627 // %b = and i32 %a, 2
4628 // %c = srl i32 %b, 1
4629 // brcond i32 %c ...
4635 // %c = setcc eq %b, 0
4638 // However when after the source operand of SRL is optimized into AND, the SRL
4639 // itself may not be optimized further. Look for it and add the BRCOND into
4641 if (N->hasOneUse()) {
4642 SDNode *Use = *N->use_begin();
4643 if (Use->getOpcode() == ISD::BRCOND)
4645 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4646 // Also look pass the truncate.
4647 Use = *Use->use_begin();
4648 if (Use->getOpcode() == ISD::BRCOND)
4656 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4657 SDValue N0 = N->getOperand(0);
4658 EVT VT = N->getValueType(0);
4660 // fold (ctlz c1) -> c2
4661 if (isa<ConstantSDNode>(N0))
4662 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4666 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4667 SDValue N0 = N->getOperand(0);
4668 EVT VT = N->getValueType(0);
4670 // fold (ctlz_zero_undef c1) -> c2
4671 if (isa<ConstantSDNode>(N0))
4672 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4676 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4677 SDValue N0 = N->getOperand(0);
4678 EVT VT = N->getValueType(0);
4680 // fold (cttz c1) -> c2
4681 if (isa<ConstantSDNode>(N0))
4682 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4686 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4687 SDValue N0 = N->getOperand(0);
4688 EVT VT = N->getValueType(0);
4690 // fold (cttz_zero_undef c1) -> c2
4691 if (isa<ConstantSDNode>(N0))
4692 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4696 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4697 SDValue N0 = N->getOperand(0);
4698 EVT VT = N->getValueType(0);
4700 // fold (ctpop c1) -> c2
4701 if (isa<ConstantSDNode>(N0))
4702 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4707 /// \brief Generate Min/Max node
4708 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4709 SDValue True, SDValue False,
4710 ISD::CondCode CC, const TargetLowering &TLI,
4711 SelectionDAG &DAG) {
4712 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4722 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4723 if (TLI.isOperationLegal(Opcode, VT))
4724 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4733 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4734 if (TLI.isOperationLegal(Opcode, VT))
4735 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4743 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4744 SDValue N0 = N->getOperand(0);
4745 SDValue N1 = N->getOperand(1);
4746 SDValue N2 = N->getOperand(2);
4747 EVT VT = N->getValueType(0);
4748 EVT VT0 = N0.getValueType();
4750 // fold (select C, X, X) -> X
4753 // fold (select true, X, Y) -> X
4754 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4755 if (N0C && !N0C->isNullValue())
4757 // fold (select false, X, Y) -> Y
4758 if (N0C && N0C->isNullValue())
4760 // fold (select C, 1, X) -> (or C, X)
4761 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4762 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4763 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4764 // fold (select C, 0, 1) -> (xor C, 1)
4765 // We can't do this reliably if integer based booleans have different contents
4766 // to floating point based booleans. This is because we can't tell whether we
4767 // have an integer-based boolean or a floating-point-based boolean unless we
4768 // can find the SETCC that produced it and inspect its operands. This is
4769 // fairly easy if C is the SETCC node, but it can potentially be
4770 // undiscoverable (or not reasonably discoverable). For example, it could be
4771 // in another basic block or it could require searching a complicated
4773 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4774 if (VT.isInteger() &&
4775 (VT0 == MVT::i1 || (VT0.isInteger() &&
4776 TLI.getBooleanContents(false, false) ==
4777 TLI.getBooleanContents(false, true) &&
4778 TLI.getBooleanContents(false, false) ==
4779 TargetLowering::ZeroOrOneBooleanContent)) &&
4780 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4783 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4784 N0, DAG.getConstant(1, VT0));
4785 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4786 N0, DAG.getConstant(1, VT0));
4787 AddToWorklist(XORNode.getNode());
4789 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4790 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4792 // fold (select C, 0, X) -> (and (not C), X)
4793 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4794 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4795 AddToWorklist(NOTNode.getNode());
4796 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4798 // fold (select C, X, 1) -> (or (not C), X)
4799 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4800 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4801 AddToWorklist(NOTNode.getNode());
4802 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4804 // fold (select C, X, 0) -> (and C, X)
4805 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4806 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4807 // fold (select X, X, Y) -> (or X, Y)
4808 // fold (select X, 1, Y) -> (or X, Y)
4809 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4810 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4811 // fold (select X, Y, X) -> (and X, Y)
4812 // fold (select X, Y, 0) -> (and X, Y)
4813 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4814 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4816 // If we can fold this based on the true/false value, do so.
4817 if (SimplifySelectOps(N, N1, N2))
4818 return SDValue(N, 0); // Don't revisit N.
4820 // fold selects based on a setcc into other things, such as min/max/abs
4821 if (N0.getOpcode() == ISD::SETCC) {
4822 // select x, y (fcmp lt x, y) -> fminnum x, y
4823 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4825 // This is OK if we don't care about what happens if either operand is a
4829 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4830 // no signed zeros as well as no nans.
4831 const TargetOptions &Options = DAG.getTarget().Options;
4832 if (Options.UnsafeFPMath &&
4833 VT.isFloatingPoint() && N0.hasOneUse() &&
4834 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4835 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4838 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4839 N1, N2, CC, TLI, DAG);
4844 if ((!LegalOperations &&
4845 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4846 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4847 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4848 N0.getOperand(0), N0.getOperand(1),
4849 N1, N2, N0.getOperand(2));
4850 return SimplifySelect(SDLoc(N), N0, N1, N2);
4853 if (VT0 == MVT::i1) {
4854 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4855 // select (and Cond0, Cond1), X, Y
4856 // -> select Cond0, (select Cond1, X, Y), Y
4857 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4858 SDValue Cond0 = N0->getOperand(0);
4859 SDValue Cond1 = N0->getOperand(1);
4860 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4861 N1.getValueType(), Cond1, N1, N2);
4862 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4865 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4866 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4867 SDValue Cond0 = N0->getOperand(0);
4868 SDValue Cond1 = N0->getOperand(1);
4869 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4870 N1.getValueType(), Cond1, N1, N2);
4871 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4876 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4877 if (N1->getOpcode() == ISD::SELECT) {
4878 SDValue N1_0 = N1->getOperand(0);
4879 SDValue N1_1 = N1->getOperand(1);
4880 SDValue N1_2 = N1->getOperand(2);
4882 // Create the actual and node if we can generate good code for it.
4883 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4884 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4886 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4889 // Otherwise see if we can optimize the "and" to a better pattern.
4890 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4891 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4895 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4896 if (N2->getOpcode() == ISD::SELECT) {
4897 SDValue N2_0 = N2->getOperand(0);
4898 SDValue N2_1 = N2->getOperand(1);
4899 SDValue N2_2 = N2->getOperand(2);
4901 // Create the actual or node if we can generate good code for it.
4902 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4903 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4905 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4908 // Otherwise see if we can optimize to a better pattern.
4909 if (SDValue Combined = visitORLike(N0, N2_0, N))
4910 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4920 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4923 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4925 // Split the inputs.
4926 SDValue Lo, Hi, LL, LH, RL, RH;
4927 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4928 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4930 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4931 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4933 return std::make_pair(Lo, Hi);
4936 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4937 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4938 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4940 SDValue Cond = N->getOperand(0);
4941 SDValue LHS = N->getOperand(1);
4942 SDValue RHS = N->getOperand(2);
4943 EVT VT = N->getValueType(0);
4944 int NumElems = VT.getVectorNumElements();
4945 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4946 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4947 Cond.getOpcode() == ISD::BUILD_VECTOR);
4949 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4950 // binary ones here.
4951 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4954 // We're sure we have an even number of elements due to the
4955 // concat_vectors we have as arguments to vselect.
4956 // Skip BV elements until we find one that's not an UNDEF
4957 // After we find an UNDEF element, keep looping until we get to half the
4958 // length of the BV and see if all the non-undef nodes are the same.
4959 ConstantSDNode *BottomHalf = nullptr;
4960 for (int i = 0; i < NumElems / 2; ++i) {
4961 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4964 if (BottomHalf == nullptr)
4965 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4966 else if (Cond->getOperand(i).getNode() != BottomHalf)
4970 // Do the same for the second half of the BuildVector
4971 ConstantSDNode *TopHalf = nullptr;
4972 for (int i = NumElems / 2; i < NumElems; ++i) {
4973 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4976 if (TopHalf == nullptr)
4977 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4978 else if (Cond->getOperand(i).getNode() != TopHalf)
4982 assert(TopHalf && BottomHalf &&
4983 "One half of the selector was all UNDEFs and the other was all the "
4984 "same value. This should have been addressed before this function.");
4986 ISD::CONCAT_VECTORS, dl, VT,
4987 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4988 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4991 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4993 if (Level >= AfterLegalizeTypes)
4996 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4997 SDValue Mask = MST->getMask();
4998 SDValue Data = MST->getValue();
5001 // If the MSTORE data type requires splitting and the mask is provided by a
5002 // SETCC, then split both nodes and its operands before legalization. This
5003 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5004 // and enables future optimizations (e.g. min/max pattern matching on X86).
5005 if (Mask.getOpcode() == ISD::SETCC) {
5007 // Check if any splitting is required.
5008 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5009 TargetLowering::TypeSplitVector)
5012 SDValue MaskLo, MaskHi, Lo, Hi;
5013 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5016 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5018 SDValue Chain = MST->getChain();
5019 SDValue Ptr = MST->getBasePtr();
5021 EVT MemoryVT = MST->getMemoryVT();
5022 unsigned Alignment = MST->getOriginalAlignment();
5024 // if Alignment is equal to the vector size,
5025 // take the half of it for the second part
5026 unsigned SecondHalfAlignment =
5027 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5028 Alignment/2 : Alignment;
5030 EVT LoMemVT, HiMemVT;
5031 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5033 SDValue DataLo, DataHi;
5034 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5036 MachineMemOperand *MMO = DAG.getMachineFunction().
5037 getMachineMemOperand(MST->getPointerInfo(),
5038 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5039 Alignment, MST->getAAInfo(), MST->getRanges());
5041 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5042 MST->isTruncatingStore());
5044 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5045 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5046 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5048 MMO = DAG.getMachineFunction().
5049 getMachineMemOperand(MST->getPointerInfo(),
5050 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5051 SecondHalfAlignment, MST->getAAInfo(),
5054 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5055 MST->isTruncatingStore());
5057 AddToWorklist(Lo.getNode());
5058 AddToWorklist(Hi.getNode());
5060 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5065 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5067 if (Level >= AfterLegalizeTypes)
5070 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5071 SDValue Mask = MLD->getMask();
5074 // If the MLOAD result requires splitting and the mask is provided by a
5075 // SETCC, then split both nodes and its operands before legalization. This
5076 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5077 // and enables future optimizations (e.g. min/max pattern matching on X86).
5079 if (Mask.getOpcode() == ISD::SETCC) {
5080 EVT VT = N->getValueType(0);
5082 // Check if any splitting is required.
5083 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5084 TargetLowering::TypeSplitVector)
5087 SDValue MaskLo, MaskHi, Lo, Hi;
5088 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5090 SDValue Src0 = MLD->getSrc0();
5091 SDValue Src0Lo, Src0Hi;
5092 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5095 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5097 SDValue Chain = MLD->getChain();
5098 SDValue Ptr = MLD->getBasePtr();
5099 EVT MemoryVT = MLD->getMemoryVT();
5100 unsigned Alignment = MLD->getOriginalAlignment();
5102 // if Alignment is equal to the vector size,
5103 // take the half of it for the second part
5104 unsigned SecondHalfAlignment =
5105 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5106 Alignment/2 : Alignment;
5108 EVT LoMemVT, HiMemVT;
5109 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5111 MachineMemOperand *MMO = DAG.getMachineFunction().
5112 getMachineMemOperand(MLD->getPointerInfo(),
5113 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5114 Alignment, MLD->getAAInfo(), MLD->getRanges());
5116 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5119 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5120 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5121 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5123 MMO = DAG.getMachineFunction().
5124 getMachineMemOperand(MLD->getPointerInfo(),
5125 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5126 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5128 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5131 AddToWorklist(Lo.getNode());
5132 AddToWorklist(Hi.getNode());
5134 // Build a factor node to remember that this load is independent of the
5136 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5139 // Legalized the chain result - switch anything that used the old chain to
5141 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5143 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5145 SDValue RetOps[] = { LoadRes, Chain };
5146 return DAG.getMergeValues(RetOps, DL);
5151 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5152 SDValue N0 = N->getOperand(0);
5153 SDValue N1 = N->getOperand(1);
5154 SDValue N2 = N->getOperand(2);
5157 // Canonicalize integer abs.
5158 // vselect (setg[te] X, 0), X, -X ->
5159 // vselect (setgt X, -1), X, -X ->
5160 // vselect (setl[te] X, 0), -X, X ->
5161 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5162 if (N0.getOpcode() == ISD::SETCC) {
5163 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5164 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5166 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5168 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5169 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5170 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5171 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5172 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5173 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5174 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5177 EVT VT = LHS.getValueType();
5178 SDValue Shift = DAG.getNode(
5179 ISD::SRA, DL, VT, LHS,
5180 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5181 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5182 AddToWorklist(Shift.getNode());
5183 AddToWorklist(Add.getNode());
5184 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5188 // If the VSELECT result requires splitting and the mask is provided by a
5189 // SETCC, then split both nodes and its operands before legalization. This
5190 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5191 // and enables future optimizations (e.g. min/max pattern matching on X86).
5192 if (N0.getOpcode() == ISD::SETCC) {
5193 EVT VT = N->getValueType(0);
5195 // Check if any splitting is required.
5196 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5197 TargetLowering::TypeSplitVector)
5200 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5201 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5202 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5203 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5205 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5206 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5208 // Add the new VSELECT nodes to the work list in case they need to be split
5210 AddToWorklist(Lo.getNode());
5211 AddToWorklist(Hi.getNode());
5213 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5216 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5217 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5219 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5220 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5223 // The ConvertSelectToConcatVector function is assuming both the above
5224 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5226 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5227 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5228 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5229 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5237 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5238 SDValue N0 = N->getOperand(0);
5239 SDValue N1 = N->getOperand(1);
5240 SDValue N2 = N->getOperand(2);
5241 SDValue N3 = N->getOperand(3);
5242 SDValue N4 = N->getOperand(4);
5243 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5245 // fold select_cc lhs, rhs, x, x, cc -> x
5249 // Determine if the condition we're dealing with is constant
5250 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5251 N0, N1, CC, SDLoc(N), false);
5252 if (SCC.getNode()) {
5253 AddToWorklist(SCC.getNode());
5255 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5256 if (!SCCC->isNullValue())
5257 return N2; // cond always true -> true val
5259 return N3; // cond always false -> false val
5260 } else if (SCC->getOpcode() == ISD::UNDEF) {
5261 // When the condition is UNDEF, just return the first operand. This is
5262 // coherent the DAG creation, no setcc node is created in this case
5264 } else if (SCC.getOpcode() == ISD::SETCC) {
5265 // Fold to a simpler select_cc
5266 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5267 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5272 // If we can fold this based on the true/false value, do so.
5273 if (SimplifySelectOps(N, N2, N3))
5274 return SDValue(N, 0); // Don't revisit N.
5276 // fold select_cc into other things, such as min/max/abs
5277 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5280 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5281 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5282 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5286 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5287 // dag node into a ConstantSDNode or a build_vector of constants.
5288 // This function is called by the DAGCombiner when visiting sext/zext/aext
5289 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5290 // Vector extends are not folded if operations are legal; this is to
5291 // avoid introducing illegal build_vector dag nodes.
5292 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5293 SelectionDAG &DAG, bool LegalTypes,
5294 bool LegalOperations) {
5295 unsigned Opcode = N->getOpcode();
5296 SDValue N0 = N->getOperand(0);
5297 EVT VT = N->getValueType(0);
5299 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5300 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5302 // fold (sext c1) -> c1
5303 // fold (zext c1) -> c1
5304 // fold (aext c1) -> c1
5305 if (isa<ConstantSDNode>(N0))
5306 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5308 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5309 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5310 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5311 EVT SVT = VT.getScalarType();
5312 if (!(VT.isVector() &&
5313 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5314 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5317 // We can fold this node into a build_vector.
5318 unsigned VTBits = SVT.getSizeInBits();
5319 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5320 unsigned ShAmt = VTBits - EVTBits;
5321 SmallVector<SDValue, 8> Elts;
5322 unsigned NumElts = N0->getNumOperands();
5325 for (unsigned i=0; i != NumElts; ++i) {
5326 SDValue Op = N0->getOperand(i);
5327 if (Op->getOpcode() == ISD::UNDEF) {
5328 Elts.push_back(DAG.getUNDEF(SVT));
5332 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5333 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5334 if (Opcode == ISD::SIGN_EXTEND)
5335 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5338 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5342 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5345 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5346 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5347 // transformation. Returns true if extension are possible and the above
5348 // mentioned transformation is profitable.
5349 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5351 SmallVectorImpl<SDNode *> &ExtendNodes,
5352 const TargetLowering &TLI) {
5353 bool HasCopyToRegUses = false;
5354 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5355 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5356 UE = N0.getNode()->use_end();
5361 if (UI.getUse().getResNo() != N0.getResNo())
5363 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5364 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5365 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5366 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5367 // Sign bits will be lost after a zext.
5370 for (unsigned i = 0; i != 2; ++i) {
5371 SDValue UseOp = User->getOperand(i);
5374 if (!isa<ConstantSDNode>(UseOp))
5379 ExtendNodes.push_back(User);
5382 // If truncates aren't free and there are users we can't
5383 // extend, it isn't worthwhile.
5386 // Remember if this value is live-out.
5387 if (User->getOpcode() == ISD::CopyToReg)
5388 HasCopyToRegUses = true;
5391 if (HasCopyToRegUses) {
5392 bool BothLiveOut = false;
5393 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5395 SDUse &Use = UI.getUse();
5396 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5402 // Both unextended and extended values are live out. There had better be
5403 // a good reason for the transformation.
5404 return ExtendNodes.size();
5409 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5410 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5411 ISD::NodeType ExtType) {
5412 // Extend SetCC uses if necessary.
5413 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5414 SDNode *SetCC = SetCCs[i];
5415 SmallVector<SDValue, 4> Ops;
5417 for (unsigned j = 0; j != 2; ++j) {
5418 SDValue SOp = SetCC->getOperand(j);
5420 Ops.push_back(ExtLoad);
5422 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5425 Ops.push_back(SetCC->getOperand(2));
5426 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5430 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5431 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5432 SDValue N0 = N->getOperand(0);
5433 EVT DstVT = N->getValueType(0);
5434 EVT SrcVT = N0.getValueType();
5436 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5437 N->getOpcode() == ISD::ZERO_EXTEND) &&
5438 "Unexpected node type (not an extend)!");
5440 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5441 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5442 // (v8i32 (sext (v8i16 (load x))))
5444 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5445 // (v4i32 (sextload (x + 16)))))
5446 // Where uses of the original load, i.e.:
5448 // are replaced with:
5450 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5451 // (v4i32 (sextload (x + 16)))))))
5453 // This combine is only applicable to illegal, but splittable, vectors.
5454 // All legal types, and illegal non-vector types, are handled elsewhere.
5455 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5457 if (N0->getOpcode() != ISD::LOAD)
5460 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5462 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5463 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5464 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5467 SmallVector<SDNode *, 4> SetCCs;
5468 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5471 ISD::LoadExtType ExtType =
5472 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5474 // Try to split the vector types to get down to legal types.
5475 EVT SplitSrcVT = SrcVT;
5476 EVT SplitDstVT = DstVT;
5477 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5478 SplitSrcVT.getVectorNumElements() > 1) {
5479 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5480 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5483 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5487 const unsigned NumSplits =
5488 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5489 const unsigned Stride = SplitSrcVT.getStoreSize();
5490 SmallVector<SDValue, 4> Loads;
5491 SmallVector<SDValue, 4> Chains;
5493 SDValue BasePtr = LN0->getBasePtr();
5494 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5495 const unsigned Offset = Idx * Stride;
5496 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5498 SDValue SplitLoad = DAG.getExtLoad(
5499 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5500 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5501 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5502 Align, LN0->getAAInfo());
5504 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5505 DAG.getConstant(Stride, BasePtr.getValueType()));
5507 Loads.push_back(SplitLoad.getValue(0));
5508 Chains.push_back(SplitLoad.getValue(1));
5511 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5512 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5514 CombineTo(N, NewValue);
5516 // Replace uses of the original load (before extension)
5517 // with a truncate of the concatenated sextloaded vectors.
5519 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5520 CombineTo(N0.getNode(), Trunc, NewChain);
5521 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5522 (ISD::NodeType)N->getOpcode());
5523 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5526 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5527 SDValue N0 = N->getOperand(0);
5528 EVT VT = N->getValueType(0);
5530 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5532 return SDValue(Res, 0);
5534 // fold (sext (sext x)) -> (sext x)
5535 // fold (sext (aext x)) -> (sext x)
5536 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5537 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5540 if (N0.getOpcode() == ISD::TRUNCATE) {
5541 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5542 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5543 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5544 if (NarrowLoad.getNode()) {
5545 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5546 if (NarrowLoad.getNode() != N0.getNode()) {
5547 CombineTo(N0.getNode(), NarrowLoad);
5548 // CombineTo deleted the truncate, if needed, but not what's under it.
5551 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5554 // See if the value being truncated is already sign extended. If so, just
5555 // eliminate the trunc/sext pair.
5556 SDValue Op = N0.getOperand(0);
5557 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5558 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5559 unsigned DestBits = VT.getScalarType().getSizeInBits();
5560 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5562 if (OpBits == DestBits) {
5563 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5564 // bits, it is already ready.
5565 if (NumSignBits > DestBits-MidBits)
5567 } else if (OpBits < DestBits) {
5568 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5569 // bits, just sext from i32.
5570 if (NumSignBits > OpBits-MidBits)
5571 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5573 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5574 // bits, just truncate to i32.
5575 if (NumSignBits > OpBits-MidBits)
5576 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5579 // fold (sext (truncate x)) -> (sextinreg x).
5580 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5581 N0.getValueType())) {
5582 if (OpBits < DestBits)
5583 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5584 else if (OpBits > DestBits)
5585 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5586 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5587 DAG.getValueType(N0.getValueType()));
5591 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5592 // Only generate vector extloads when 1) they're legal, and 2) they are
5593 // deemed desirable by the target.
5594 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5595 ((!LegalOperations && !VT.isVector() &&
5596 !cast<LoadSDNode>(N0)->isVolatile()) ||
5597 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5598 bool DoXform = true;
5599 SmallVector<SDNode*, 4> SetCCs;
5600 if (!N0.hasOneUse())
5601 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5603 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5605 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5606 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5608 LN0->getBasePtr(), N0.getValueType(),
5609 LN0->getMemOperand());
5610 CombineTo(N, ExtLoad);
5611 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5612 N0.getValueType(), ExtLoad);
5613 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5614 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5616 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5620 // fold (sext (load x)) to multiple smaller sextloads.
5621 // Only on illegal but splittable vectors.
5622 if (SDValue ExtLoad = CombineExtLoad(N))
5625 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5626 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5627 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5628 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5629 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5630 EVT MemVT = LN0->getMemoryVT();
5631 if ((!LegalOperations && !LN0->isVolatile()) ||
5632 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5633 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5635 LN0->getBasePtr(), MemVT,
5636 LN0->getMemOperand());
5637 CombineTo(N, ExtLoad);
5638 CombineTo(N0.getNode(),
5639 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5640 N0.getValueType(), ExtLoad),
5641 ExtLoad.getValue(1));
5642 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5646 // fold (sext (and/or/xor (load x), cst)) ->
5647 // (and/or/xor (sextload x), (sext cst))
5648 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5649 N0.getOpcode() == ISD::XOR) &&
5650 isa<LoadSDNode>(N0.getOperand(0)) &&
5651 N0.getOperand(1).getOpcode() == ISD::Constant &&
5652 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5653 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5654 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5655 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5656 bool DoXform = true;
5657 SmallVector<SDNode*, 4> SetCCs;
5658 if (!N0.hasOneUse())
5659 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5662 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5663 LN0->getChain(), LN0->getBasePtr(),
5665 LN0->getMemOperand());
5666 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5667 Mask = Mask.sext(VT.getSizeInBits());
5668 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5669 ExtLoad, DAG.getConstant(Mask, VT));
5670 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5671 SDLoc(N0.getOperand(0)),
5672 N0.getOperand(0).getValueType(), ExtLoad);
5674 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5675 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5677 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5682 if (N0.getOpcode() == ISD::SETCC) {
5683 EVT N0VT = N0.getOperand(0).getValueType();
5684 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5685 // Only do this before legalize for now.
5686 if (VT.isVector() && !LegalOperations &&
5687 TLI.getBooleanContents(N0VT) ==
5688 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5689 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5690 // of the same size as the compared operands. Only optimize sext(setcc())
5691 // if this is the case.
5692 EVT SVT = getSetCCResultType(N0VT);
5694 // We know that the # elements of the results is the same as the
5695 // # elements of the compare (and the # elements of the compare result
5696 // for that matter). Check to see that they are the same size. If so,
5697 // we know that the element size of the sext'd result matches the
5698 // element size of the compare operands.
5699 if (VT.getSizeInBits() == SVT.getSizeInBits())
5700 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5702 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5704 // If the desired elements are smaller or larger than the source
5705 // elements we can use a matching integer vector type and then
5706 // truncate/sign extend
5707 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5708 if (SVT == MatchingVectorType) {
5709 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5710 N0.getOperand(0), N0.getOperand(1),
5711 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5712 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5716 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5717 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5719 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5721 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5722 NegOne, DAG.getConstant(0, VT),
5723 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5724 if (SCC.getNode()) return SCC;
5726 if (!VT.isVector()) {
5727 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5728 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5730 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5731 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5732 N0.getOperand(0), N0.getOperand(1), CC);
5733 return DAG.getSelect(DL, VT, SetCC,
5734 NegOne, DAG.getConstant(0, VT));
5739 // fold (sext x) -> (zext x) if the sign bit is known zero.
5740 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5741 DAG.SignBitIsZero(N0))
5742 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5747 // isTruncateOf - If N is a truncate of some other value, return true, record
5748 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5749 // This function computes KnownZero to avoid a duplicated call to
5750 // computeKnownBits in the caller.
5751 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5754 if (N->getOpcode() == ISD::TRUNCATE) {
5755 Op = N->getOperand(0);
5756 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5760 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5761 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5764 SDValue Op0 = N->getOperand(0);
5765 SDValue Op1 = N->getOperand(1);
5766 assert(Op0.getValueType() == Op1.getValueType());
5768 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5769 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5770 if (COp0 && COp0->isNullValue())
5772 else if (COp1 && COp1->isNullValue())
5777 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5779 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5785 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5786 SDValue N0 = N->getOperand(0);
5787 EVT VT = N->getValueType(0);
5789 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5791 return SDValue(Res, 0);
5793 // fold (zext (zext x)) -> (zext x)
5794 // fold (zext (aext x)) -> (zext x)
5795 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5796 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5799 // fold (zext (truncate x)) -> (zext x) or
5800 // (zext (truncate x)) -> (truncate x)
5801 // This is valid when the truncated bits of x are already zero.
5802 // FIXME: We should extend this to work for vectors too.
5805 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5806 APInt TruncatedBits =
5807 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5808 APInt(Op.getValueSizeInBits(), 0) :
5809 APInt::getBitsSet(Op.getValueSizeInBits(),
5810 N0.getValueSizeInBits(),
5811 std::min(Op.getValueSizeInBits(),
5812 VT.getSizeInBits()));
5813 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5814 if (VT.bitsGT(Op.getValueType()))
5815 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5816 if (VT.bitsLT(Op.getValueType()))
5817 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5823 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5824 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5825 if (N0.getOpcode() == ISD::TRUNCATE) {
5826 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5827 if (NarrowLoad.getNode()) {
5828 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5829 if (NarrowLoad.getNode() != N0.getNode()) {
5830 CombineTo(N0.getNode(), NarrowLoad);
5831 // CombineTo deleted the truncate, if needed, but not what's under it.
5834 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5838 // fold (zext (truncate x)) -> (and x, mask)
5839 if (N0.getOpcode() == ISD::TRUNCATE &&
5840 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5842 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5843 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5844 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5845 if (NarrowLoad.getNode()) {
5846 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5847 if (NarrowLoad.getNode() != N0.getNode()) {
5848 CombineTo(N0.getNode(), NarrowLoad);
5849 // CombineTo deleted the truncate, if needed, but not what's under it.
5852 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5855 SDValue Op = N0.getOperand(0);
5856 if (Op.getValueType().bitsLT(VT)) {
5857 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5858 AddToWorklist(Op.getNode());
5859 } else if (Op.getValueType().bitsGT(VT)) {
5860 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5861 AddToWorklist(Op.getNode());
5863 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5864 N0.getValueType().getScalarType());
5867 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5868 // if either of the casts is not free.
5869 if (N0.getOpcode() == ISD::AND &&
5870 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5871 N0.getOperand(1).getOpcode() == ISD::Constant &&
5872 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5873 N0.getValueType()) ||
5874 !TLI.isZExtFree(N0.getValueType(), VT))) {
5875 SDValue X = N0.getOperand(0).getOperand(0);
5876 if (X.getValueType().bitsLT(VT)) {
5877 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5878 } else if (X.getValueType().bitsGT(VT)) {
5879 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5881 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5882 Mask = Mask.zext(VT.getSizeInBits());
5883 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5884 X, DAG.getConstant(Mask, VT));
5887 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5888 // Only generate vector extloads when 1) they're legal, and 2) they are
5889 // deemed desirable by the target.
5890 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5891 ((!LegalOperations && !VT.isVector() &&
5892 !cast<LoadSDNode>(N0)->isVolatile()) ||
5893 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5894 bool DoXform = true;
5895 SmallVector<SDNode*, 4> SetCCs;
5896 if (!N0.hasOneUse())
5897 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5899 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5901 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5902 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5904 LN0->getBasePtr(), N0.getValueType(),
5905 LN0->getMemOperand());
5906 CombineTo(N, ExtLoad);
5907 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5908 N0.getValueType(), ExtLoad);
5909 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5911 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5913 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5917 // fold (zext (load x)) to multiple smaller zextloads.
5918 // Only on illegal but splittable vectors.
5919 if (SDValue ExtLoad = CombineExtLoad(N))
5922 // fold (zext (and/or/xor (load x), cst)) ->
5923 // (and/or/xor (zextload x), (zext cst))
5924 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5925 N0.getOpcode() == ISD::XOR) &&
5926 isa<LoadSDNode>(N0.getOperand(0)) &&
5927 N0.getOperand(1).getOpcode() == ISD::Constant &&
5928 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5929 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5930 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5931 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5932 bool DoXform = true;
5933 SmallVector<SDNode*, 4> SetCCs;
5934 if (!N0.hasOneUse())
5935 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5938 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5939 LN0->getChain(), LN0->getBasePtr(),
5941 LN0->getMemOperand());
5942 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5943 Mask = Mask.zext(VT.getSizeInBits());
5944 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5945 ExtLoad, DAG.getConstant(Mask, VT));
5946 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5947 SDLoc(N0.getOperand(0)),
5948 N0.getOperand(0).getValueType(), ExtLoad);
5950 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5951 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5953 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5958 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5959 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5960 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5961 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5962 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5963 EVT MemVT = LN0->getMemoryVT();
5964 if ((!LegalOperations && !LN0->isVolatile()) ||
5965 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5966 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5968 LN0->getBasePtr(), MemVT,
5969 LN0->getMemOperand());
5970 CombineTo(N, ExtLoad);
5971 CombineTo(N0.getNode(),
5972 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5974 ExtLoad.getValue(1));
5975 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5979 if (N0.getOpcode() == ISD::SETCC) {
5980 if (!LegalOperations && VT.isVector() &&
5981 N0.getValueType().getVectorElementType() == MVT::i1) {
5982 EVT N0VT = N0.getOperand(0).getValueType();
5983 if (getSetCCResultType(N0VT) == N0.getValueType())
5986 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5987 // Only do this before legalize for now.
5988 EVT EltVT = VT.getVectorElementType();
5989 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5990 DAG.getConstant(1, EltVT));
5991 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5992 // We know that the # elements of the results is the same as the
5993 // # elements of the compare (and the # elements of the compare result
5994 // for that matter). Check to see that they are the same size. If so,
5995 // we know that the element size of the sext'd result matches the
5996 // element size of the compare operands.
5997 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5998 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6000 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6001 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
6004 // If the desired elements are smaller or larger than the source
6005 // elements we can use a matching integer vector type and then
6006 // truncate/sign extend
6007 EVT MatchingElementType =
6008 EVT::getIntegerVT(*DAG.getContext(),
6009 N0VT.getScalarType().getSizeInBits());
6010 EVT MatchingVectorType =
6011 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6012 N0VT.getVectorNumElements());
6014 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6016 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6017 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6018 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
6019 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
6022 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6024 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6025 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6026 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6027 if (SCC.getNode()) return SCC;
6030 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6031 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6032 isa<ConstantSDNode>(N0.getOperand(1)) &&
6033 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6035 SDValue ShAmt = N0.getOperand(1);
6036 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6037 if (N0.getOpcode() == ISD::SHL) {
6038 SDValue InnerZExt = N0.getOperand(0);
6039 // If the original shl may be shifting out bits, do not perform this
6041 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6042 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6043 if (ShAmtVal > KnownZeroBits)
6049 // Ensure that the shift amount is wide enough for the shifted value.
6050 if (VT.getSizeInBits() >= 256)
6051 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6053 return DAG.getNode(N0.getOpcode(), DL, VT,
6054 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6061 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6062 SDValue N0 = N->getOperand(0);
6063 EVT VT = N->getValueType(0);
6065 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6067 return SDValue(Res, 0);
6069 // fold (aext (aext x)) -> (aext x)
6070 // fold (aext (zext x)) -> (zext x)
6071 // fold (aext (sext x)) -> (sext x)
6072 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6073 N0.getOpcode() == ISD::ZERO_EXTEND ||
6074 N0.getOpcode() == ISD::SIGN_EXTEND)
6075 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6077 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6078 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6079 if (N0.getOpcode() == ISD::TRUNCATE) {
6080 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6081 if (NarrowLoad.getNode()) {
6082 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6083 if (NarrowLoad.getNode() != N0.getNode()) {
6084 CombineTo(N0.getNode(), NarrowLoad);
6085 // CombineTo deleted the truncate, if needed, but not what's under it.
6088 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6092 // fold (aext (truncate x))
6093 if (N0.getOpcode() == ISD::TRUNCATE) {
6094 SDValue TruncOp = N0.getOperand(0);
6095 if (TruncOp.getValueType() == VT)
6096 return TruncOp; // x iff x size == zext size.
6097 if (TruncOp.getValueType().bitsGT(VT))
6098 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6099 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6102 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6103 // if the trunc is not free.
6104 if (N0.getOpcode() == ISD::AND &&
6105 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6106 N0.getOperand(1).getOpcode() == ISD::Constant &&
6107 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6108 N0.getValueType())) {
6109 SDValue X = N0.getOperand(0).getOperand(0);
6110 if (X.getValueType().bitsLT(VT)) {
6111 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6112 } else if (X.getValueType().bitsGT(VT)) {
6113 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6115 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6116 Mask = Mask.zext(VT.getSizeInBits());
6117 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6118 X, DAG.getConstant(Mask, VT));
6121 // fold (aext (load x)) -> (aext (truncate (extload x)))
6122 // None of the supported targets knows how to perform load and any_ext
6123 // on vectors in one instruction. We only perform this transformation on
6125 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6126 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6127 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6128 bool DoXform = true;
6129 SmallVector<SDNode*, 4> SetCCs;
6130 if (!N0.hasOneUse())
6131 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6133 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6134 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6136 LN0->getBasePtr(), N0.getValueType(),
6137 LN0->getMemOperand());
6138 CombineTo(N, ExtLoad);
6139 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6140 N0.getValueType(), ExtLoad);
6141 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6142 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6144 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6148 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6149 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6150 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6151 if (N0.getOpcode() == ISD::LOAD &&
6152 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6154 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6155 ISD::LoadExtType ExtType = LN0->getExtensionType();
6156 EVT MemVT = LN0->getMemoryVT();
6157 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6158 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6159 VT, LN0->getChain(), LN0->getBasePtr(),
6160 MemVT, LN0->getMemOperand());
6161 CombineTo(N, ExtLoad);
6162 CombineTo(N0.getNode(),
6163 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6164 N0.getValueType(), ExtLoad),
6165 ExtLoad.getValue(1));
6166 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6170 if (N0.getOpcode() == ISD::SETCC) {
6172 // aext(setcc) -> vsetcc
6173 // aext(setcc) -> truncate(vsetcc)
6174 // aext(setcc) -> aext(vsetcc)
6175 // Only do this before legalize for now.
6176 if (VT.isVector() && !LegalOperations) {
6177 EVT N0VT = N0.getOperand(0).getValueType();
6178 // We know that the # elements of the results is the same as the
6179 // # elements of the compare (and the # elements of the compare result
6180 // for that matter). Check to see that they are the same size. If so,
6181 // we know that the element size of the sext'd result matches the
6182 // element size of the compare operands.
6183 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6184 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6186 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6187 // If the desired elements are smaller or larger than the source
6188 // elements we can use a matching integer vector type and then
6189 // truncate/any extend
6191 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6193 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6195 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6196 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6200 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6202 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6203 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6204 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6212 /// See if the specified operand can be simplified with the knowledge that only
6213 /// the bits specified by Mask are used. If so, return the simpler operand,
6214 /// otherwise return a null SDValue.
6215 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6216 switch (V.getOpcode()) {
6218 case ISD::Constant: {
6219 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6220 assert(CV && "Const value should be ConstSDNode.");
6221 const APInt &CVal = CV->getAPIntValue();
6222 APInt NewVal = CVal & Mask;
6224 return DAG.getConstant(NewVal, V.getValueType());
6229 // If the LHS or RHS don't contribute bits to the or, drop them.
6230 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6231 return V.getOperand(1);
6232 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6233 return V.getOperand(0);
6236 // Only look at single-use SRLs.
6237 if (!V.getNode()->hasOneUse())
6239 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6240 // See if we can recursively simplify the LHS.
6241 unsigned Amt = RHSC->getZExtValue();
6243 // Watch out for shift count overflow though.
6244 if (Amt >= Mask.getBitWidth()) break;
6245 APInt NewMask = Mask << Amt;
6246 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6247 if (SimplifyLHS.getNode())
6248 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6249 SimplifyLHS, V.getOperand(1));
6255 /// If the result of a wider load is shifted to right of N bits and then
6256 /// truncated to a narrower type and where N is a multiple of number of bits of
6257 /// the narrower type, transform it to a narrower load from address + N / num of
6258 /// bits of new type. If the result is to be extended, also fold the extension
6259 /// to form a extending load.
6260 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6261 unsigned Opc = N->getOpcode();
6263 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6264 SDValue N0 = N->getOperand(0);
6265 EVT VT = N->getValueType(0);
6268 // This transformation isn't valid for vector loads.
6272 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6274 if (Opc == ISD::SIGN_EXTEND_INREG) {
6275 ExtType = ISD::SEXTLOAD;
6276 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6277 } else if (Opc == ISD::SRL) {
6278 // Another special-case: SRL is basically zero-extending a narrower value.
6279 ExtType = ISD::ZEXTLOAD;
6281 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6282 if (!N01) return SDValue();
6283 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6284 VT.getSizeInBits() - N01->getZExtValue());
6286 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6289 unsigned EVTBits = ExtVT.getSizeInBits();
6291 // Do not generate loads of non-round integer types since these can
6292 // be expensive (and would be wrong if the type is not byte sized).
6293 if (!ExtVT.isRound())
6297 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6298 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6299 ShAmt = N01->getZExtValue();
6300 // Is the shift amount a multiple of size of VT?
6301 if ((ShAmt & (EVTBits-1)) == 0) {
6302 N0 = N0.getOperand(0);
6303 // Is the load width a multiple of size of VT?
6304 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6308 // At this point, we must have a load or else we can't do the transform.
6309 if (!isa<LoadSDNode>(N0)) return SDValue();
6311 // Because a SRL must be assumed to *need* to zero-extend the high bits
6312 // (as opposed to anyext the high bits), we can't combine the zextload
6313 // lowering of SRL and an sextload.
6314 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6317 // If the shift amount is larger than the input type then we're not
6318 // accessing any of the loaded bytes. If the load was a zextload/extload
6319 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6320 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6325 // If the load is shifted left (and the result isn't shifted back right),
6326 // we can fold the truncate through the shift.
6327 unsigned ShLeftAmt = 0;
6328 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6329 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6330 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6331 ShLeftAmt = N01->getZExtValue();
6332 N0 = N0.getOperand(0);
6336 // If we haven't found a load, we can't narrow it. Don't transform one with
6337 // multiple uses, this would require adding a new load.
6338 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6341 // Don't change the width of a volatile load.
6342 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6343 if (LN0->isVolatile())
6346 // Verify that we are actually reducing a load width here.
6347 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6350 // For the transform to be legal, the load must produce only two values
6351 // (the value loaded and the chain). Don't transform a pre-increment
6352 // load, for example, which produces an extra value. Otherwise the
6353 // transformation is not equivalent, and the downstream logic to replace
6354 // uses gets things wrong.
6355 if (LN0->getNumValues() > 2)
6358 // If the load that we're shrinking is an extload and we're not just
6359 // discarding the extension we can't simply shrink the load. Bail.
6360 // TODO: It would be possible to merge the extensions in some cases.
6361 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6362 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6365 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6368 EVT PtrType = N0.getOperand(1).getValueType();
6370 if (PtrType == MVT::Untyped || PtrType.isExtended())
6371 // It's not possible to generate a constant of extended or untyped type.
6374 // For big endian targets, we need to adjust the offset to the pointer to
6375 // load the correct bytes.
6376 if (TLI.isBigEndian()) {
6377 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6378 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6379 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6382 uint64_t PtrOff = ShAmt / 8;
6383 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6384 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6385 PtrType, LN0->getBasePtr(),
6386 DAG.getConstant(PtrOff, PtrType));
6387 AddToWorklist(NewPtr.getNode());
6390 if (ExtType == ISD::NON_EXTLOAD)
6391 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6392 LN0->getPointerInfo().getWithOffset(PtrOff),
6393 LN0->isVolatile(), LN0->isNonTemporal(),
6394 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6396 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6397 LN0->getPointerInfo().getWithOffset(PtrOff),
6398 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6399 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6401 // Replace the old load's chain with the new load's chain.
6402 WorklistRemover DeadNodes(*this);
6403 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6405 // Shift the result left, if we've swallowed a left shift.
6406 SDValue Result = Load;
6407 if (ShLeftAmt != 0) {
6408 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6409 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6411 // If the shift amount is as large as the result size (but, presumably,
6412 // no larger than the source) then the useful bits of the result are
6413 // zero; we can't simply return the shortened shift, because the result
6414 // of that operation is undefined.
6415 if (ShLeftAmt >= VT.getSizeInBits())
6416 Result = DAG.getConstant(0, VT);
6418 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6419 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6422 // Return the new loaded value.
6426 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6427 SDValue N0 = N->getOperand(0);
6428 SDValue N1 = N->getOperand(1);
6429 EVT VT = N->getValueType(0);
6430 EVT EVT = cast<VTSDNode>(N1)->getVT();
6431 unsigned VTBits = VT.getScalarType().getSizeInBits();
6432 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6434 // fold (sext_in_reg c1) -> c1
6435 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6436 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6438 // If the input is already sign extended, just drop the extension.
6439 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6442 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6443 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6444 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6445 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6446 N0.getOperand(0), N1);
6448 // fold (sext_in_reg (sext x)) -> (sext x)
6449 // fold (sext_in_reg (aext x)) -> (sext x)
6450 // if x is small enough.
6451 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6452 SDValue N00 = N0.getOperand(0);
6453 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6454 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6455 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6458 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6459 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6460 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6462 // fold operands of sext_in_reg based on knowledge that the top bits are not
6464 if (SimplifyDemandedBits(SDValue(N, 0)))
6465 return SDValue(N, 0);
6467 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6468 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6469 SDValue NarrowLoad = ReduceLoadWidth(N);
6470 if (NarrowLoad.getNode())
6473 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6474 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6475 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6476 if (N0.getOpcode() == ISD::SRL) {
6477 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6478 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6479 // We can turn this into an SRA iff the input to the SRL is already sign
6481 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6482 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6483 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6484 N0.getOperand(0), N0.getOperand(1));
6488 // fold (sext_inreg (extload x)) -> (sextload x)
6489 if (ISD::isEXTLoad(N0.getNode()) &&
6490 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6491 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6492 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6493 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6494 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6495 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6497 LN0->getBasePtr(), EVT,
6498 LN0->getMemOperand());
6499 CombineTo(N, ExtLoad);
6500 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6501 AddToWorklist(ExtLoad.getNode());
6502 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6504 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6505 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6507 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6508 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6509 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6510 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6511 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6513 LN0->getBasePtr(), EVT,
6514 LN0->getMemOperand());
6515 CombineTo(N, ExtLoad);
6516 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6517 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6520 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6521 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6522 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6523 N0.getOperand(1), false);
6524 if (BSwap.getNode())
6525 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6529 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6530 // into a build_vector.
6531 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6532 SmallVector<SDValue, 8> Elts;
6533 unsigned NumElts = N0->getNumOperands();
6534 unsigned ShAmt = VTBits - EVTBits;
6536 for (unsigned i = 0; i != NumElts; ++i) {
6537 SDValue Op = N0->getOperand(i);
6538 if (Op->getOpcode() == ISD::UNDEF) {
6543 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6544 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6545 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6546 Op.getValueType()));
6549 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6555 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6556 SDValue N0 = N->getOperand(0);
6557 EVT VT = N->getValueType(0);
6558 bool isLE = TLI.isLittleEndian();
6561 if (N0.getValueType() == N->getValueType(0))
6563 // fold (truncate c1) -> c1
6564 if (isConstantIntBuildVectorOrConstantInt(N0))
6565 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6566 // fold (truncate (truncate x)) -> (truncate x)
6567 if (N0.getOpcode() == ISD::TRUNCATE)
6568 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6569 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6570 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6571 N0.getOpcode() == ISD::SIGN_EXTEND ||
6572 N0.getOpcode() == ISD::ANY_EXTEND) {
6573 if (N0.getOperand(0).getValueType().bitsLT(VT))
6574 // if the source is smaller than the dest, we still need an extend
6575 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6577 if (N0.getOperand(0).getValueType().bitsGT(VT))
6578 // if the source is larger than the dest, than we just need the truncate
6579 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6580 // if the source and dest are the same type, we can drop both the extend
6581 // and the truncate.
6582 return N0.getOperand(0);
6585 // Fold extract-and-trunc into a narrow extract. For example:
6586 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6587 // i32 y = TRUNCATE(i64 x)
6589 // v16i8 b = BITCAST (v2i64 val)
6590 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6592 // Note: We only run this optimization after type legalization (which often
6593 // creates this pattern) and before operation legalization after which
6594 // we need to be more careful about the vector instructions that we generate.
6595 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6596 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6598 EVT VecTy = N0.getOperand(0).getValueType();
6599 EVT ExTy = N0.getValueType();
6600 EVT TrTy = N->getValueType(0);
6602 unsigned NumElem = VecTy.getVectorNumElements();
6603 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6605 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6606 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6608 SDValue EltNo = N0->getOperand(1);
6609 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6610 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6611 EVT IndexTy = TLI.getVectorIdxTy();
6612 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6614 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6615 NVT, N0.getOperand(0));
6617 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6619 DAG.getConstant(Index, IndexTy));
6623 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6624 if (N0.getOpcode() == ISD::SELECT) {
6625 EVT SrcVT = N0.getValueType();
6626 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6627 TLI.isTruncateFree(SrcVT, VT)) {
6629 SDValue Cond = N0.getOperand(0);
6630 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6631 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6632 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6636 // Fold a series of buildvector, bitcast, and truncate if possible.
6638 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6639 // (2xi32 (buildvector x, y)).
6640 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6641 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6642 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6643 N0.getOperand(0).hasOneUse()) {
6645 SDValue BuildVect = N0.getOperand(0);
6646 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6647 EVT TruncVecEltTy = VT.getVectorElementType();
6649 // Check that the element types match.
6650 if (BuildVectEltTy == TruncVecEltTy) {
6651 // Now we only need to compute the offset of the truncated elements.
6652 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6653 unsigned TruncVecNumElts = VT.getVectorNumElements();
6654 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6656 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6657 "Invalid number of elements");
6659 SmallVector<SDValue, 8> Opnds;
6660 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6661 Opnds.push_back(BuildVect.getOperand(i));
6663 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6667 // See if we can simplify the input to this truncate through knowledge that
6668 // only the low bits are being used.
6669 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6670 // Currently we only perform this optimization on scalars because vectors
6671 // may have different active low bits.
6672 if (!VT.isVector()) {
6674 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6675 VT.getSizeInBits()));
6676 if (Shorter.getNode())
6677 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6679 // fold (truncate (load x)) -> (smaller load x)
6680 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6681 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6682 SDValue Reduced = ReduceLoadWidth(N);
6683 if (Reduced.getNode())
6685 // Handle the case where the load remains an extending load even
6686 // after truncation.
6687 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6688 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6689 if (!LN0->isVolatile() &&
6690 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6691 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6692 VT, LN0->getChain(), LN0->getBasePtr(),
6694 LN0->getMemOperand());
6695 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6700 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6701 // where ... are all 'undef'.
6702 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6703 SmallVector<EVT, 8> VTs;
6706 unsigned NumDefs = 0;
6708 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6709 SDValue X = N0.getOperand(i);
6710 if (X.getOpcode() != ISD::UNDEF) {
6715 // Stop if more than one members are non-undef.
6718 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6719 VT.getVectorElementType(),
6720 X.getValueType().getVectorNumElements()));
6724 return DAG.getUNDEF(VT);
6727 assert(V.getNode() && "The single defined operand is empty!");
6728 SmallVector<SDValue, 8> Opnds;
6729 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6731 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6734 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6735 AddToWorklist(NV.getNode());
6736 Opnds.push_back(NV);
6738 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6742 // Simplify the operands using demanded-bits information.
6743 if (!VT.isVector() &&
6744 SimplifyDemandedBits(SDValue(N, 0)))
6745 return SDValue(N, 0);
6750 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6751 SDValue Elt = N->getOperand(i);
6752 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6753 return Elt.getNode();
6754 return Elt.getOperand(Elt.getResNo()).getNode();
6757 /// build_pair (load, load) -> load
6758 /// if load locations are consecutive.
6759 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6760 assert(N->getOpcode() == ISD::BUILD_PAIR);
6762 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6763 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6764 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6765 LD1->getAddressSpace() != LD2->getAddressSpace())
6767 EVT LD1VT = LD1->getValueType(0);
6769 if (ISD::isNON_EXTLoad(LD2) &&
6771 // If both are volatile this would reduce the number of volatile loads.
6772 // If one is volatile it might be ok, but play conservative and bail out.
6773 !LD1->isVolatile() &&
6774 !LD2->isVolatile() &&
6775 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6776 unsigned Align = LD1->getAlignment();
6777 unsigned NewAlign = TLI.getDataLayout()->
6778 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6780 if (NewAlign <= Align &&
6781 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6782 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6783 LD1->getBasePtr(), LD1->getPointerInfo(),
6784 false, false, false, Align);
6790 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6791 SDValue N0 = N->getOperand(0);
6792 EVT VT = N->getValueType(0);
6794 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6795 // Only do this before legalize, since afterward the target may be depending
6796 // on the bitconvert.
6797 // First check to see if this is all constant.
6799 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6801 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6803 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6804 assert(!DestEltVT.isVector() &&
6805 "Element type of vector ValueType must not be vector!");
6807 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6810 // If the input is a constant, let getNode fold it.
6811 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6812 // If we can't allow illegal operations, we need to check that this is just
6813 // a fp -> int or int -> conversion and that the resulting operation will
6815 if (!LegalOperations ||
6816 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6817 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6818 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6819 TLI.isOperationLegal(ISD::Constant, VT)))
6820 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6823 // (conv (conv x, t1), t2) -> (conv x, t2)
6824 if (N0.getOpcode() == ISD::BITCAST)
6825 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6828 // fold (conv (load x)) -> (load (conv*)x)
6829 // If the resultant load doesn't need a higher alignment than the original!
6830 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6831 // Do not change the width of a volatile load.
6832 !cast<LoadSDNode>(N0)->isVolatile() &&
6833 // Do not remove the cast if the types differ in endian layout.
6834 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6835 TLI.hasBigEndianPartOrdering(VT) &&
6836 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6837 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6838 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6839 unsigned Align = TLI.getDataLayout()->
6840 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6841 unsigned OrigAlign = LN0->getAlignment();
6843 if (Align <= OrigAlign) {
6844 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6845 LN0->getBasePtr(), LN0->getPointerInfo(),
6846 LN0->isVolatile(), LN0->isNonTemporal(),
6847 LN0->isInvariant(), OrigAlign,
6849 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6854 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6855 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6856 // This often reduces constant pool loads.
6857 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6858 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6859 N0.getNode()->hasOneUse() && VT.isInteger() &&
6860 !VT.isVector() && !N0.getValueType().isVector()) {
6861 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6863 AddToWorklist(NewConv.getNode());
6865 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6866 if (N0.getOpcode() == ISD::FNEG)
6867 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6868 NewConv, DAG.getConstant(SignBit, VT));
6869 assert(N0.getOpcode() == ISD::FABS);
6870 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6871 NewConv, DAG.getConstant(~SignBit, VT));
6874 // fold (bitconvert (fcopysign cst, x)) ->
6875 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6876 // Note that we don't handle (copysign x, cst) because this can always be
6877 // folded to an fneg or fabs.
6878 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6879 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6880 VT.isInteger() && !VT.isVector()) {
6881 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6882 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6883 if (isTypeLegal(IntXVT)) {
6884 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6885 IntXVT, N0.getOperand(1));
6886 AddToWorklist(X.getNode());
6888 // If X has a different width than the result/lhs, sext it or truncate it.
6889 unsigned VTWidth = VT.getSizeInBits();
6890 if (OrigXWidth < VTWidth) {
6891 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6892 AddToWorklist(X.getNode());
6893 } else if (OrigXWidth > VTWidth) {
6894 // To get the sign bit in the right place, we have to shift it right
6895 // before truncating.
6896 X = DAG.getNode(ISD::SRL, SDLoc(X),
6897 X.getValueType(), X,
6898 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6899 AddToWorklist(X.getNode());
6900 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6901 AddToWorklist(X.getNode());
6904 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6905 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6906 X, DAG.getConstant(SignBit, VT));
6907 AddToWorklist(X.getNode());
6909 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6910 VT, N0.getOperand(0));
6911 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6912 Cst, DAG.getConstant(~SignBit, VT));
6913 AddToWorklist(Cst.getNode());
6915 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6919 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6920 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6921 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6922 if (CombineLD.getNode())
6929 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6930 EVT VT = N->getValueType(0);
6931 return CombineConsecutiveLoads(N, VT);
6934 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6935 /// operands. DstEltVT indicates the destination element value type.
6936 SDValue DAGCombiner::
6937 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6938 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6940 // If this is already the right type, we're done.
6941 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6943 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6944 unsigned DstBitSize = DstEltVT.getSizeInBits();
6946 // If this is a conversion of N elements of one type to N elements of another
6947 // type, convert each element. This handles FP<->INT cases.
6948 if (SrcBitSize == DstBitSize) {
6949 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6950 BV->getValueType(0).getVectorNumElements());
6952 // Due to the FP element handling below calling this routine recursively,
6953 // we can end up with a scalar-to-vector node here.
6954 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6955 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6956 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6957 DstEltVT, BV->getOperand(0)));
6959 SmallVector<SDValue, 8> Ops;
6960 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6961 SDValue Op = BV->getOperand(i);
6962 // If the vector element type is not legal, the BUILD_VECTOR operands
6963 // are promoted and implicitly truncated. Make that explicit here.
6964 if (Op.getValueType() != SrcEltVT)
6965 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6966 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6968 AddToWorklist(Ops.back().getNode());
6970 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6973 // Otherwise, we're growing or shrinking the elements. To avoid having to
6974 // handle annoying details of growing/shrinking FP values, we convert them to
6976 if (SrcEltVT.isFloatingPoint()) {
6977 // Convert the input float vector to a int vector where the elements are the
6979 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6980 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6984 // Now we know the input is an integer vector. If the output is a FP type,
6985 // convert to integer first, then to FP of the right size.
6986 if (DstEltVT.isFloatingPoint()) {
6987 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6988 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6990 // Next, convert to FP elements of the same size.
6991 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6994 // Okay, we know the src/dst types are both integers of differing types.
6995 // Handling growing first.
6996 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6997 if (SrcBitSize < DstBitSize) {
6998 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7000 SmallVector<SDValue, 8> Ops;
7001 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7002 i += NumInputsPerOutput) {
7003 bool isLE = TLI.isLittleEndian();
7004 APInt NewBits = APInt(DstBitSize, 0);
7005 bool EltIsUndef = true;
7006 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7007 // Shift the previously computed bits over.
7008 NewBits <<= SrcBitSize;
7009 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7010 if (Op.getOpcode() == ISD::UNDEF) continue;
7013 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7014 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7018 Ops.push_back(DAG.getUNDEF(DstEltVT));
7020 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
7023 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7024 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7027 // Finally, this must be the case where we are shrinking elements: each input
7028 // turns into multiple outputs.
7029 bool isS2V = ISD::isScalarToVector(BV);
7030 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7031 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7032 NumOutputsPerInput*BV->getNumOperands());
7033 SmallVector<SDValue, 8> Ops;
7035 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7036 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7037 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7041 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7042 getAPIntValue().zextOrTrunc(SrcBitSize);
7044 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7045 APInt ThisVal = OpVal.trunc(DstBitSize);
7046 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
7047 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
7048 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
7049 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7051 OpVal = OpVal.lshr(DstBitSize);
7054 // For big endian targets, swap the order of the pieces of each element.
7055 if (TLI.isBigEndian())
7056 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7059 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7062 // Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad
7063 static SDValue performFaddFmulCombines(unsigned FusedOpcode,
7066 const TargetLowering &TLI,
7067 SelectionDAG &DAG) {
7068 SDValue N0 = N->getOperand(0);
7069 SDValue N1 = N->getOperand(1);
7070 EVT VT = N->getValueType(0);
7072 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7073 if (N0.getOpcode() == ISD::FMUL &&
7074 (Aggressive || N0->hasOneUse())) {
7075 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7076 N0.getOperand(0), N0.getOperand(1), N1);
7079 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7080 // Note: Commutes FADD operands.
7081 if (N1.getOpcode() == ISD::FMUL &&
7082 (Aggressive || N1->hasOneUse())) {
7083 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7084 N1.getOperand(0), N1.getOperand(1), N0);
7087 // More folding opportunities when target permits.
7089 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7090 if (N0.getOpcode() == ISD::FMA &&
7091 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7092 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7093 N0.getOperand(0), N0.getOperand(1),
7094 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7095 N0.getOperand(2).getOperand(0),
7096 N0.getOperand(2).getOperand(1),
7100 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7101 if (N1->getOpcode() == ISD::FMA &&
7102 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7103 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7104 N1.getOperand(0), N1.getOperand(1),
7105 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7106 N1.getOperand(2).getOperand(0),
7107 N1.getOperand(2).getOperand(1),
7115 static SDValue performFsubFmulCombines(unsigned FusedOpcode,
7118 const TargetLowering &TLI,
7119 SelectionDAG &DAG) {
7120 SDValue N0 = N->getOperand(0);
7121 SDValue N1 = N->getOperand(1);
7122 EVT VT = N->getValueType(0);
7126 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7127 if (N0.getOpcode() == ISD::FMUL &&
7128 (Aggressive || N0->hasOneUse())) {
7129 return DAG.getNode(FusedOpcode, SL, VT,
7130 N0.getOperand(0), N0.getOperand(1),
7131 DAG.getNode(ISD::FNEG, SL, VT, N1));
7134 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7135 // Note: Commutes FSUB operands.
7136 if (N1.getOpcode() == ISD::FMUL &&
7137 (Aggressive || N1->hasOneUse()))
7138 return DAG.getNode(FusedOpcode, SL, VT,
7139 DAG.getNode(ISD::FNEG, SL, VT,
7141 N1.getOperand(1), N0);
7143 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7144 if (N0.getOpcode() == ISD::FNEG &&
7145 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7146 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7147 SDValue N00 = N0.getOperand(0).getOperand(0);
7148 SDValue N01 = N0.getOperand(0).getOperand(1);
7149 return DAG.getNode(FusedOpcode, SL, VT,
7150 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7151 DAG.getNode(ISD::FNEG, SL, VT, N1));
7154 // More folding opportunities when target permits.
7156 // fold (fsub (fma x, y, (fmul u, v)), z)
7157 // -> (fma x, y (fma u, v, (fneg z)))
7158 if (N0.getOpcode() == FusedOpcode &&
7159 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7160 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7161 N0.getOperand(0), N0.getOperand(1),
7162 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7163 N0.getOperand(2).getOperand(0),
7164 N0.getOperand(2).getOperand(1),
7165 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7169 // fold (fsub x, (fma y, z, (fmul u, v)))
7170 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7171 if (N1.getOpcode() == FusedOpcode &&
7172 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7173 SDValue N20 = N1.getOperand(2).getOperand(0);
7174 SDValue N21 = N1.getOperand(2).getOperand(1);
7175 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7176 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7179 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7180 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7189 SDValue DAGCombiner::visitFADD(SDNode *N) {
7190 SDValue N0 = N->getOperand(0);
7191 SDValue N1 = N->getOperand(1);
7192 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7193 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7194 EVT VT = N->getValueType(0);
7195 const TargetOptions &Options = DAG.getTarget().Options;
7198 if (VT.isVector()) {
7199 SDValue FoldedVOp = SimplifyVBinOp(N);
7200 if (FoldedVOp.getNode()) return FoldedVOp;
7203 // fold (fadd c1, c2) -> c1 + c2
7205 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7207 // canonicalize constant to RHS
7208 if (N0CFP && !N1CFP)
7209 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7211 // fold (fadd A, (fneg B)) -> (fsub A, B)
7212 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7213 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7214 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7215 GetNegatedExpression(N1, DAG, LegalOperations));
7217 // fold (fadd (fneg A), B) -> (fsub B, A)
7218 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7219 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7220 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7221 GetNegatedExpression(N0, DAG, LegalOperations));
7223 // If 'unsafe math' is enabled, fold lots of things.
7224 if (Options.UnsafeFPMath) {
7225 // No FP constant should be created after legalization as Instruction
7226 // Selection pass has a hard time dealing with FP constants.
7227 bool AllowNewConst = (Level < AfterLegalizeDAG);
7229 // fold (fadd A, 0) -> A
7230 if (N1CFP && N1CFP->getValueAPF().isZero())
7233 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7234 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7235 isa<ConstantFPSDNode>(N0.getOperand(1)))
7236 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7237 DAG.getNode(ISD::FADD, SDLoc(N), VT,
7238 N0.getOperand(1), N1));
7240 // If allowed, fold (fadd (fneg x), x) -> 0.0
7241 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7242 return DAG.getConstantFP(0.0, VT);
7244 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7245 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7246 return DAG.getConstantFP(0.0, VT);
7248 // We can fold chains of FADD's of the same value into multiplications.
7249 // This transform is not safe in general because we are reducing the number
7250 // of rounding steps.
7251 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7252 if (N0.getOpcode() == ISD::FMUL) {
7253 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7254 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7256 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7257 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7258 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7260 DAG.getConstantFP(1.0, VT));
7261 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7264 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7265 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7266 N1.getOperand(0) == N1.getOperand(1) &&
7267 N0.getOperand(0) == N1.getOperand(0)) {
7268 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7270 DAG.getConstantFP(2.0, VT));
7271 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7272 N0.getOperand(0), NewCFP);
7276 if (N1.getOpcode() == ISD::FMUL) {
7277 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7278 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7280 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7281 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7282 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7284 DAG.getConstantFP(1.0, VT));
7285 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7288 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7289 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7290 N0.getOperand(0) == N0.getOperand(1) &&
7291 N1.getOperand(0) == N0.getOperand(0)) {
7292 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7294 DAG.getConstantFP(2.0, VT));
7295 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7299 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7300 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7301 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7302 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7303 (N0.getOperand(0) == N1))
7304 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7305 N1, DAG.getConstantFP(3.0, VT));
7308 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7309 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7310 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7311 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7312 N1.getOperand(0) == N0)
7313 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7314 N0, DAG.getConstantFP(3.0, VT));
7317 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7318 if (AllowNewConst &&
7319 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7320 N0.getOperand(0) == N0.getOperand(1) &&
7321 N1.getOperand(0) == N1.getOperand(1) &&
7322 N0.getOperand(0) == N1.getOperand(0))
7323 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7324 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7326 } // enable-unsafe-fp-math
7328 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7329 // Assume if there is an fmad instruction that it should be aggressively
7331 if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7335 // FADD -> FMA combines:
7336 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7337 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7338 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7340 if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7341 // Don't form FMA if we are preferring FMAD.
7343 = performFaddFmulCombines(ISD::FMA,
7344 TLI.enableAggressiveFMAFusion(VT),
7350 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7351 // to combine into FMA, arrange such nodes accordingly.
7352 if (TLI.isFPExtFree(VT)) {
7354 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7355 if (N0.getOpcode() == ISD::FP_EXTEND) {
7356 SDValue N00 = N0.getOperand(0);
7357 if (N00.getOpcode() == ISD::FMUL)
7358 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7359 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7361 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7362 N00.getOperand(1)), N1);
7365 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7366 // Note: Commutes FADD operands.
7367 if (N1.getOpcode() == ISD::FP_EXTEND) {
7368 SDValue N10 = N1.getOperand(0);
7369 if (N10.getOpcode() == ISD::FMUL)
7370 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7371 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7373 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7374 N10.getOperand(1)), N0);
7382 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7383 SDValue N0 = N->getOperand(0);
7384 SDValue N1 = N->getOperand(1);
7385 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7386 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7387 EVT VT = N->getValueType(0);
7389 const TargetOptions &Options = DAG.getTarget().Options;
7392 if (VT.isVector()) {
7393 SDValue FoldedVOp = SimplifyVBinOp(N);
7394 if (FoldedVOp.getNode()) return FoldedVOp;
7397 // fold (fsub c1, c2) -> c1-c2
7399 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7401 // fold (fsub A, (fneg B)) -> (fadd A, B)
7402 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7403 return DAG.getNode(ISD::FADD, dl, VT, N0,
7404 GetNegatedExpression(N1, DAG, LegalOperations));
7406 // If 'unsafe math' is enabled, fold lots of things.
7407 if (Options.UnsafeFPMath) {
7409 if (N1CFP && N1CFP->getValueAPF().isZero())
7412 // (fsub 0, B) -> -B
7413 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7414 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7415 return GetNegatedExpression(N1, DAG, LegalOperations);
7416 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7417 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7420 // (fsub x, x) -> 0.0
7422 return DAG.getConstantFP(0.0f, VT);
7424 // (fsub x, (fadd x, y)) -> (fneg y)
7425 // (fsub x, (fadd y, x)) -> (fneg y)
7426 if (N1.getOpcode() == ISD::FADD) {
7427 SDValue N10 = N1->getOperand(0);
7428 SDValue N11 = N1->getOperand(1);
7430 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7431 return GetNegatedExpression(N11, DAG, LegalOperations);
7433 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7434 return GetNegatedExpression(N10, DAG, LegalOperations);
7438 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7439 // Assume if there is an fmad instruction that it should be aggressively
7441 if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7445 // FSUB -> FMA combines:
7446 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7447 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7448 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7450 if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7451 // Don't form FMA if we are preferring FMAD.
7454 = performFsubFmulCombines(ISD::FMA,
7455 TLI.enableAggressiveFMAFusion(VT),
7461 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7462 // to combine into FMA, arrange such nodes accordingly.
7463 if (TLI.isFPExtFree(VT)) {
7464 // fold (fsub (fpext (fmul x, y)), z)
7465 // -> (fma (fpext x), (fpext y), (fneg z))
7466 if (N0.getOpcode() == ISD::FP_EXTEND) {
7467 SDValue N00 = N0.getOperand(0);
7468 if (N00.getOpcode() == ISD::FMUL)
7469 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7470 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7472 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7474 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7477 // fold (fsub x, (fpext (fmul y, z)))
7478 // -> (fma (fneg (fpext y)), (fpext z), x)
7479 // Note: Commutes FSUB operands.
7480 if (N1.getOpcode() == ISD::FP_EXTEND) {
7481 SDValue N10 = N1.getOperand(0);
7482 if (N10.getOpcode() == ISD::FMUL)
7483 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7484 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7485 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7486 VT, N10.getOperand(0))),
7487 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7492 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7493 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7494 if (N0.getOpcode() == ISD::FP_EXTEND) {
7495 SDValue N00 = N0.getOperand(0);
7496 if (N00.getOpcode() == ISD::FNEG) {
7497 SDValue N000 = N00.getOperand(0);
7498 if (N000.getOpcode() == ISD::FMUL) {
7499 return DAG.getNode(ISD::FMA, dl, VT,
7500 DAG.getNode(ISD::FNEG, dl, VT,
7501 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7502 VT, N000.getOperand(0))),
7503 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7504 N000.getOperand(1)),
7505 DAG.getNode(ISD::FNEG, dl, VT, N1));
7510 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7511 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7512 if (N0.getOpcode() == ISD::FNEG) {
7513 SDValue N00 = N0.getOperand(0);
7514 if (N00.getOpcode() == ISD::FP_EXTEND) {
7515 SDValue N000 = N00.getOperand(0);
7516 if (N000.getOpcode() == ISD::FMUL) {
7517 return DAG.getNode(ISD::FMA, dl, VT,
7518 DAG.getNode(ISD::FNEG, dl, VT,
7519 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7520 VT, N000.getOperand(0))),
7521 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7522 N000.getOperand(1)),
7523 DAG.getNode(ISD::FNEG, dl, VT, N1));
7533 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7534 SDValue N0 = N->getOperand(0);
7535 SDValue N1 = N->getOperand(1);
7536 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7537 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7538 EVT VT = N->getValueType(0);
7539 const TargetOptions &Options = DAG.getTarget().Options;
7542 if (VT.isVector()) {
7543 // This just handles C1 * C2 for vectors. Other vector folds are below.
7544 SDValue FoldedVOp = SimplifyVBinOp(N);
7545 if (FoldedVOp.getNode())
7547 // Canonicalize vector constant to RHS.
7548 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7549 N1.getOpcode() != ISD::BUILD_VECTOR)
7550 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7551 if (BV0->isConstant())
7552 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7555 // fold (fmul c1, c2) -> c1*c2
7557 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7559 // canonicalize constant to RHS
7560 if (N0CFP && !N1CFP)
7561 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7563 // fold (fmul A, 1.0) -> A
7564 if (N1CFP && N1CFP->isExactlyValue(1.0))
7567 if (Options.UnsafeFPMath) {
7568 // fold (fmul A, 0) -> 0
7569 if (N1CFP && N1CFP->getValueAPF().isZero())
7572 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7573 if (N0.getOpcode() == ISD::FMUL) {
7574 // Fold scalars or any vector constants (not just splats).
7575 // This fold is done in general by InstCombine, but extra fmul insts
7576 // may have been generated during lowering.
7577 SDValue N00 = N0.getOperand(0);
7578 SDValue N01 = N0.getOperand(1);
7579 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7580 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7581 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7583 // Check 1: Make sure that the first operand of the inner multiply is NOT
7584 // a constant. Otherwise, we may induce infinite looping.
7585 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7586 // Check 2: Make sure that the second operand of the inner multiply and
7587 // the second operand of the outer multiply are constants.
7588 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7589 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7591 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7592 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7597 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7598 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7599 // during an early run of DAGCombiner can prevent folding with fmuls
7600 // inserted during lowering.
7601 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7603 const SDValue Two = DAG.getConstantFP(2.0, VT);
7604 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7605 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7609 // fold (fmul X, 2.0) -> (fadd X, X)
7610 if (N1CFP && N1CFP->isExactlyValue(+2.0))
7611 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7613 // fold (fmul X, -1.0) -> (fneg X)
7614 if (N1CFP && N1CFP->isExactlyValue(-1.0))
7615 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7616 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7618 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7619 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7620 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7621 // Both can be negated for free, check to see if at least one is cheaper
7623 if (LHSNeg == 2 || RHSNeg == 2)
7624 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7625 GetNegatedExpression(N0, DAG, LegalOperations),
7626 GetNegatedExpression(N1, DAG, LegalOperations));
7633 SDValue DAGCombiner::visitFMA(SDNode *N) {
7634 SDValue N0 = N->getOperand(0);
7635 SDValue N1 = N->getOperand(1);
7636 SDValue N2 = N->getOperand(2);
7637 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7638 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7639 EVT VT = N->getValueType(0);
7641 const TargetOptions &Options = DAG.getTarget().Options;
7643 // Constant fold FMA.
7644 if (isa<ConstantFPSDNode>(N0) &&
7645 isa<ConstantFPSDNode>(N1) &&
7646 isa<ConstantFPSDNode>(N2)) {
7647 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7650 if (Options.UnsafeFPMath) {
7651 if (N0CFP && N0CFP->isZero())
7653 if (N1CFP && N1CFP->isZero())
7656 if (N0CFP && N0CFP->isExactlyValue(1.0))
7657 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7658 if (N1CFP && N1CFP->isExactlyValue(1.0))
7659 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7661 // Canonicalize (fma c, x, y) -> (fma x, c, y)
7662 if (N0CFP && !N1CFP)
7663 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7665 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7666 if (Options.UnsafeFPMath && N1CFP &&
7667 N2.getOpcode() == ISD::FMUL &&
7668 N0 == N2.getOperand(0) &&
7669 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7670 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7671 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7675 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7676 if (Options.UnsafeFPMath &&
7677 N0.getOpcode() == ISD::FMUL && N1CFP &&
7678 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7679 return DAG.getNode(ISD::FMA, dl, VT,
7681 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7685 // (fma x, 1, y) -> (fadd x, y)
7686 // (fma x, -1, y) -> (fadd (fneg x), y)
7688 if (N1CFP->isExactlyValue(1.0))
7689 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7691 if (N1CFP->isExactlyValue(-1.0) &&
7692 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7693 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7694 AddToWorklist(RHSNeg.getNode());
7695 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7699 // (fma x, c, x) -> (fmul x, (c+1))
7700 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7701 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7702 DAG.getNode(ISD::FADD, dl, VT,
7703 N1, DAG.getConstantFP(1.0, VT)));
7705 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7706 if (Options.UnsafeFPMath && N1CFP &&
7707 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7708 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7709 DAG.getNode(ISD::FADD, dl, VT,
7710 N1, DAG.getConstantFP(-1.0, VT)));
7716 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7717 SDValue N0 = N->getOperand(0);
7718 SDValue N1 = N->getOperand(1);
7719 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7720 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7721 EVT VT = N->getValueType(0);
7723 const TargetOptions &Options = DAG.getTarget().Options;
7726 if (VT.isVector()) {
7727 SDValue FoldedVOp = SimplifyVBinOp(N);
7728 if (FoldedVOp.getNode()) return FoldedVOp;
7731 // fold (fdiv c1, c2) -> c1/c2
7733 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7735 if (Options.UnsafeFPMath) {
7736 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7738 // Compute the reciprocal 1.0 / c2.
7739 APFloat N1APF = N1CFP->getValueAPF();
7740 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7741 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7742 // Only do the transform if the reciprocal is a legal fp immediate that
7743 // isn't too nasty (eg NaN, denormal, ...).
7744 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7745 (!LegalOperations ||
7746 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7747 // backend)... we should handle this gracefully after Legalize.
7748 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7749 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7750 TLI.isFPImmLegal(Recip, VT)))
7751 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7752 DAG.getConstantFP(Recip, VT));
7755 // If this FDIV is part of a reciprocal square root, it may be folded
7756 // into a target-specific square root estimate instruction.
7757 if (N1.getOpcode() == ISD::FSQRT) {
7758 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7759 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7761 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7762 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7763 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7764 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7765 AddToWorklist(RV.getNode());
7766 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7768 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7769 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7770 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7771 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7772 AddToWorklist(RV.getNode());
7773 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7775 } else if (N1.getOpcode() == ISD::FMUL) {
7776 // Look through an FMUL. Even though this won't remove the FDIV directly,
7777 // it's still worthwhile to get rid of the FSQRT if possible.
7780 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7781 SqrtOp = N1.getOperand(0);
7782 OtherOp = N1.getOperand(1);
7783 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7784 SqrtOp = N1.getOperand(1);
7785 OtherOp = N1.getOperand(0);
7787 if (SqrtOp.getNode()) {
7788 // We found a FSQRT, so try to make this fold:
7789 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7790 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7791 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7792 AddToWorklist(RV.getNode());
7793 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7798 // Fold into a reciprocal estimate and multiply instead of a real divide.
7799 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7800 AddToWorklist(RV.getNode());
7801 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7805 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7806 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7807 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7808 // Both can be negated for free, check to see if at least one is cheaper
7810 if (LHSNeg == 2 || RHSNeg == 2)
7811 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7812 GetNegatedExpression(N0, DAG, LegalOperations),
7813 GetNegatedExpression(N1, DAG, LegalOperations));
7817 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7819 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7820 // Notice that this is not always beneficial. One reason is different target
7821 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7822 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7823 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7824 if (Options.UnsafeFPMath) {
7825 // Skip if current node is a reciprocal.
7826 if (N0CFP && N0CFP->isExactlyValue(1.0))
7829 SmallVector<SDNode *, 4> Users;
7830 // Find all FDIV users of the same divisor.
7831 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7832 UE = N1.getNode()->use_end();
7834 SDNode *User = UI.getUse().getUser();
7835 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7836 Users.push_back(User);
7839 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7840 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7841 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7843 // Dividend / Divisor -> Dividend * Reciprocal
7844 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7845 if ((*I)->getOperand(0) != FPOne) {
7846 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7847 (*I)->getOperand(0), Reciprocal);
7848 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7858 SDValue DAGCombiner::visitFREM(SDNode *N) {
7859 SDValue N0 = N->getOperand(0);
7860 SDValue N1 = N->getOperand(1);
7861 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7862 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7863 EVT VT = N->getValueType(0);
7865 // fold (frem c1, c2) -> fmod(c1,c2)
7867 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7872 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7873 if (DAG.getTarget().Options.UnsafeFPMath &&
7874 !TLI.isFsqrtCheap()) {
7875 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7876 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7877 EVT VT = RV.getValueType();
7878 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7879 AddToWorklist(RV.getNode());
7881 // Unfortunately, RV is now NaN if the input was exactly 0.
7882 // Select out this case and force the answer to 0.
7883 SDValue Zero = DAG.getConstantFP(0.0, VT);
7885 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7886 N->getOperand(0), Zero, ISD::SETEQ);
7887 AddToWorklist(ZeroCmp.getNode());
7888 AddToWorklist(RV.getNode());
7890 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7891 SDLoc(N), VT, ZeroCmp, Zero, RV);
7898 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7899 SDValue N0 = N->getOperand(0);
7900 SDValue N1 = N->getOperand(1);
7901 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7902 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7903 EVT VT = N->getValueType(0);
7905 if (N0CFP && N1CFP) // Constant fold
7906 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7909 const APFloat& V = N1CFP->getValueAPF();
7910 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7911 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7912 if (!V.isNegative()) {
7913 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7914 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7916 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7917 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7918 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7922 // copysign(fabs(x), y) -> copysign(x, y)
7923 // copysign(fneg(x), y) -> copysign(x, y)
7924 // copysign(copysign(x,z), y) -> copysign(x, y)
7925 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7926 N0.getOpcode() == ISD::FCOPYSIGN)
7927 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7928 N0.getOperand(0), N1);
7930 // copysign(x, abs(y)) -> abs(x)
7931 if (N1.getOpcode() == ISD::FABS)
7932 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7934 // copysign(x, copysign(y,z)) -> copysign(x, z)
7935 if (N1.getOpcode() == ISD::FCOPYSIGN)
7936 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7937 N0, N1.getOperand(1));
7939 // copysign(x, fp_extend(y)) -> copysign(x, y)
7940 // copysign(x, fp_round(y)) -> copysign(x, y)
7941 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7942 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7943 N0, N1.getOperand(0));
7948 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7949 SDValue N0 = N->getOperand(0);
7950 EVT VT = N->getValueType(0);
7951 EVT OpVT = N0.getValueType();
7953 // fold (sint_to_fp c1) -> c1fp
7954 if (isConstantIntBuildVectorOrConstantInt(N0) &&
7955 // ...but only if the target supports immediate floating-point values
7956 (!LegalOperations ||
7957 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7958 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7960 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7961 // but UINT_TO_FP is legal on this target, try to convert.
7962 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7963 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7964 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7965 if (DAG.SignBitIsZero(N0))
7966 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7969 // The next optimizations are desirable only if SELECT_CC can be lowered.
7970 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7971 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7972 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7974 (!LegalOperations ||
7975 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7977 { N0.getOperand(0), N0.getOperand(1),
7978 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7980 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7983 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7984 // (select_cc x, y, 1.0, 0.0,, cc)
7985 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7986 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7987 (!LegalOperations ||
7988 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7990 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7991 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7992 N0.getOperand(0).getOperand(2) };
7993 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8000 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8001 SDValue N0 = N->getOperand(0);
8002 EVT VT = N->getValueType(0);
8003 EVT OpVT = N0.getValueType();
8005 // fold (uint_to_fp c1) -> c1fp
8006 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8007 // ...but only if the target supports immediate floating-point values
8008 (!LegalOperations ||
8009 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8010 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8012 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8013 // but SINT_TO_FP is legal on this target, try to convert.
8014 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8015 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8016 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8017 if (DAG.SignBitIsZero(N0))
8018 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8021 // The next optimizations are desirable only if SELECT_CC can be lowered.
8022 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8023 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8025 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8026 (!LegalOperations ||
8027 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8029 { N0.getOperand(0), N0.getOperand(1),
8030 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
8032 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8039 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8040 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8041 SDValue N0 = N->getOperand(0);
8042 EVT VT = N->getValueType(0);
8044 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8047 SDValue Src = N0.getOperand(0);
8048 EVT SrcVT = Src.getValueType();
8049 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8050 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8052 // We can safely assume the conversion won't overflow the output range,
8053 // because (for example) (uint8_t)18293.f is undefined behavior.
8055 // Since we can assume the conversion won't overflow, our decision as to
8056 // whether the input will fit in the float should depend on the minimum
8057 // of the input range and output range.
8059 // This means this is also safe for a signed input and unsigned output, since
8060 // a negative input would lead to undefined behavior.
8061 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8062 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8063 unsigned ActualSize = std::min(InputSize, OutputSize);
8064 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8066 // We can only fold away the float conversion if the input range can be
8067 // represented exactly in the float range.
8068 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8069 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8070 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8072 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8074 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8075 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8078 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8083 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8084 SDValue N0 = N->getOperand(0);
8085 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8086 EVT VT = N->getValueType(0);
8088 // fold (fp_to_sint c1fp) -> c1
8090 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8092 return FoldIntToFPToInt(N, DAG);
8095 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8096 SDValue N0 = N->getOperand(0);
8097 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8098 EVT VT = N->getValueType(0);
8100 // fold (fp_to_uint c1fp) -> c1
8102 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8104 return FoldIntToFPToInt(N, DAG);
8107 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8108 SDValue N0 = N->getOperand(0);
8109 SDValue N1 = N->getOperand(1);
8110 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8111 EVT VT = N->getValueType(0);
8113 // fold (fp_round c1fp) -> c1fp
8115 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8117 // fold (fp_round (fp_extend x)) -> x
8118 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8119 return N0.getOperand(0);
8121 // fold (fp_round (fp_round x)) -> (fp_round x)
8122 if (N0.getOpcode() == ISD::FP_ROUND) {
8123 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8124 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8125 // If the first fp_round isn't a value preserving truncation, it might
8126 // introduce a tie in the second fp_round, that wouldn't occur in the
8127 // single-step fp_round we want to fold to.
8128 // In other words, double rounding isn't the same as rounding.
8129 // Also, this is a value preserving truncation iff both fp_round's are.
8130 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8131 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8132 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
8135 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8136 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8137 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8138 N0.getOperand(0), N1);
8139 AddToWorklist(Tmp.getNode());
8140 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8141 Tmp, N0.getOperand(1));
8147 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8148 SDValue N0 = N->getOperand(0);
8149 EVT VT = N->getValueType(0);
8150 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8151 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8153 // fold (fp_round_inreg c1fp) -> c1fp
8154 if (N0CFP && isTypeLegal(EVT)) {
8155 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
8156 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
8162 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8163 SDValue N0 = N->getOperand(0);
8164 EVT VT = N->getValueType(0);
8166 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8167 if (N->hasOneUse() &&
8168 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8171 // fold (fp_extend c1fp) -> c1fp
8172 if (isConstantFPBuildVectorOrConstantFP(N0))
8173 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8175 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8177 if (N0.getOpcode() == ISD::FP_ROUND
8178 && N0.getNode()->getConstantOperandVal(1) == 1) {
8179 SDValue In = N0.getOperand(0);
8180 if (In.getValueType() == VT) return In;
8181 if (VT.bitsLT(In.getValueType()))
8182 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8183 In, N0.getOperand(1));
8184 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8187 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8188 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8189 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8190 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8191 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8193 LN0->getBasePtr(), N0.getValueType(),
8194 LN0->getMemOperand());
8195 CombineTo(N, ExtLoad);
8196 CombineTo(N0.getNode(),
8197 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8198 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8199 ExtLoad.getValue(1));
8200 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8206 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8207 SDValue N0 = N->getOperand(0);
8208 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8209 EVT VT = N->getValueType(0);
8211 // fold (fceil c1) -> fceil(c1)
8213 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8218 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8219 SDValue N0 = N->getOperand(0);
8220 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8221 EVT VT = N->getValueType(0);
8223 // fold (ftrunc c1) -> ftrunc(c1)
8225 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8230 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8231 SDValue N0 = N->getOperand(0);
8232 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8233 EVT VT = N->getValueType(0);
8235 // fold (ffloor c1) -> ffloor(c1)
8237 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8242 // FIXME: FNEG and FABS have a lot in common; refactor.
8243 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8244 SDValue N0 = N->getOperand(0);
8245 EVT VT = N->getValueType(0);
8247 // Constant fold FNEG.
8248 if (isConstantFPBuildVectorOrConstantFP(N0))
8249 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8251 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8252 &DAG.getTarget().Options))
8253 return GetNegatedExpression(N0, DAG, LegalOperations);
8255 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8256 // constant pool values.
8257 if (!TLI.isFNegFree(VT) &&
8258 N0.getOpcode() == ISD::BITCAST &&
8259 N0.getNode()->hasOneUse()) {
8260 SDValue Int = N0.getOperand(0);
8261 EVT IntVT = Int.getValueType();
8262 if (IntVT.isInteger() && !IntVT.isVector()) {
8264 if (N0.getValueType().isVector()) {
8265 // For a vector, get a mask such as 0x80... per scalar element
8267 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8268 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8270 // For a scalar, just generate 0x80...
8271 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8273 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8274 DAG.getConstant(SignMask, IntVT));
8275 AddToWorklist(Int.getNode());
8276 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8280 // (fneg (fmul c, x)) -> (fmul -c, x)
8281 if (N0.getOpcode() == ISD::FMUL) {
8282 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8284 APFloat CVal = CFP1->getValueAPF();
8286 if (Level >= AfterLegalizeDAG &&
8287 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8288 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8290 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8291 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8298 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8299 SDValue N0 = N->getOperand(0);
8300 SDValue N1 = N->getOperand(1);
8301 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8302 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8304 if (N0CFP && N1CFP) {
8305 const APFloat &C0 = N0CFP->getValueAPF();
8306 const APFloat &C1 = N1CFP->getValueAPF();
8307 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8311 EVT VT = N->getValueType(0);
8312 // Canonicalize to constant on RHS.
8313 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8319 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8320 SDValue N0 = N->getOperand(0);
8321 SDValue N1 = N->getOperand(1);
8322 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8323 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8325 if (N0CFP && N1CFP) {
8326 const APFloat &C0 = N0CFP->getValueAPF();
8327 const APFloat &C1 = N1CFP->getValueAPF();
8328 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8332 EVT VT = N->getValueType(0);
8333 // Canonicalize to constant on RHS.
8334 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8340 SDValue DAGCombiner::visitFABS(SDNode *N) {
8341 SDValue N0 = N->getOperand(0);
8342 EVT VT = N->getValueType(0);
8344 // fold (fabs c1) -> fabs(c1)
8345 if (isConstantFPBuildVectorOrConstantFP(N0))
8346 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8348 // fold (fabs (fabs x)) -> (fabs x)
8349 if (N0.getOpcode() == ISD::FABS)
8350 return N->getOperand(0);
8352 // fold (fabs (fneg x)) -> (fabs x)
8353 // fold (fabs (fcopysign x, y)) -> (fabs x)
8354 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8355 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8357 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8358 // constant pool values.
8359 if (!TLI.isFAbsFree(VT) &&
8360 N0.getOpcode() == ISD::BITCAST &&
8361 N0.getNode()->hasOneUse()) {
8362 SDValue Int = N0.getOperand(0);
8363 EVT IntVT = Int.getValueType();
8364 if (IntVT.isInteger() && !IntVT.isVector()) {
8366 if (N0.getValueType().isVector()) {
8367 // For a vector, get a mask such as 0x7f... per scalar element
8369 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8370 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8372 // For a scalar, just generate 0x7f...
8373 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8375 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8376 DAG.getConstant(SignMask, IntVT));
8377 AddToWorklist(Int.getNode());
8378 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8385 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8386 SDValue Chain = N->getOperand(0);
8387 SDValue N1 = N->getOperand(1);
8388 SDValue N2 = N->getOperand(2);
8390 // If N is a constant we could fold this into a fallthrough or unconditional
8391 // branch. However that doesn't happen very often in normal code, because
8392 // Instcombine/SimplifyCFG should have handled the available opportunities.
8393 // If we did this folding here, it would be necessary to update the
8394 // MachineBasicBlock CFG, which is awkward.
8396 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8398 if (N1.getOpcode() == ISD::SETCC &&
8399 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8400 N1.getOperand(0).getValueType())) {
8401 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8402 Chain, N1.getOperand(2),
8403 N1.getOperand(0), N1.getOperand(1), N2);
8406 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8407 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8408 (N1.getOperand(0).hasOneUse() &&
8409 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8410 SDNode *Trunc = nullptr;
8411 if (N1.getOpcode() == ISD::TRUNCATE) {
8412 // Look pass the truncate.
8413 Trunc = N1.getNode();
8414 N1 = N1.getOperand(0);
8417 // Match this pattern so that we can generate simpler code:
8420 // %b = and i32 %a, 2
8421 // %c = srl i32 %b, 1
8422 // brcond i32 %c ...
8427 // %b = and i32 %a, 2
8428 // %c = setcc eq %b, 0
8431 // This applies only when the AND constant value has one bit set and the
8432 // SRL constant is equal to the log2 of the AND constant. The back-end is
8433 // smart enough to convert the result into a TEST/JMP sequence.
8434 SDValue Op0 = N1.getOperand(0);
8435 SDValue Op1 = N1.getOperand(1);
8437 if (Op0.getOpcode() == ISD::AND &&
8438 Op1.getOpcode() == ISD::Constant) {
8439 SDValue AndOp1 = Op0.getOperand(1);
8441 if (AndOp1.getOpcode() == ISD::Constant) {
8442 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8444 if (AndConst.isPowerOf2() &&
8445 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8447 DAG.getSetCC(SDLoc(N),
8448 getSetCCResultType(Op0.getValueType()),
8449 Op0, DAG.getConstant(0, Op0.getValueType()),
8452 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8453 MVT::Other, Chain, SetCC, N2);
8454 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8455 // will convert it back to (X & C1) >> C2.
8456 CombineTo(N, NewBRCond, false);
8457 // Truncate is dead.
8459 deleteAndRecombine(Trunc);
8460 // Replace the uses of SRL with SETCC
8461 WorklistRemover DeadNodes(*this);
8462 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8463 deleteAndRecombine(N1.getNode());
8464 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8470 // Restore N1 if the above transformation doesn't match.
8471 N1 = N->getOperand(1);
8474 // Transform br(xor(x, y)) -> br(x != y)
8475 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8476 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8477 SDNode *TheXor = N1.getNode();
8478 SDValue Op0 = TheXor->getOperand(0);
8479 SDValue Op1 = TheXor->getOperand(1);
8480 if (Op0.getOpcode() == Op1.getOpcode()) {
8481 // Avoid missing important xor optimizations.
8482 SDValue Tmp = visitXOR(TheXor);
8483 if (Tmp.getNode()) {
8484 if (Tmp.getNode() != TheXor) {
8485 DEBUG(dbgs() << "\nReplacing.8 ";
8487 dbgs() << "\nWith: ";
8488 Tmp.getNode()->dump(&DAG);
8490 WorklistRemover DeadNodes(*this);
8491 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8492 deleteAndRecombine(TheXor);
8493 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8494 MVT::Other, Chain, Tmp, N2);
8497 // visitXOR has changed XOR's operands or replaced the XOR completely,
8499 return SDValue(N, 0);
8503 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8505 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8506 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8507 Op0.getOpcode() == ISD::XOR) {
8508 TheXor = Op0.getNode();
8512 EVT SetCCVT = N1.getValueType();
8514 SetCCVT = getSetCCResultType(SetCCVT);
8515 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8518 Equal ? ISD::SETEQ : ISD::SETNE);
8519 // Replace the uses of XOR with SETCC
8520 WorklistRemover DeadNodes(*this);
8521 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8522 deleteAndRecombine(N1.getNode());
8523 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8524 MVT::Other, Chain, SetCC, N2);
8531 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8533 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8534 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8535 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8537 // If N is a constant we could fold this into a fallthrough or unconditional
8538 // branch. However that doesn't happen very often in normal code, because
8539 // Instcombine/SimplifyCFG should have handled the available opportunities.
8540 // If we did this folding here, it would be necessary to update the
8541 // MachineBasicBlock CFG, which is awkward.
8543 // Use SimplifySetCC to simplify SETCC's.
8544 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8545 CondLHS, CondRHS, CC->get(), SDLoc(N),
8547 if (Simp.getNode()) AddToWorklist(Simp.getNode());
8549 // fold to a simpler setcc
8550 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8551 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8552 N->getOperand(0), Simp.getOperand(2),
8553 Simp.getOperand(0), Simp.getOperand(1),
8559 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8560 /// and that N may be folded in the load / store addressing mode.
8561 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8563 const TargetLowering &TLI) {
8565 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8566 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8568 VT = Use->getValueType(0);
8569 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8570 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8572 VT = ST->getValue().getValueType();
8576 TargetLowering::AddrMode AM;
8577 if (N->getOpcode() == ISD::ADD) {
8578 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8581 AM.BaseOffs = Offset->getSExtValue();
8585 } else if (N->getOpcode() == ISD::SUB) {
8586 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8589 AM.BaseOffs = -Offset->getSExtValue();
8596 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8599 /// Try turning a load/store into a pre-indexed load/store when the base
8600 /// pointer is an add or subtract and it has other uses besides the load/store.
8601 /// After the transformation, the new indexed load/store has effectively folded
8602 /// the add/subtract in and all of its other uses are redirected to the
8604 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8605 if (Level < AfterLegalizeDAG)
8611 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8612 if (LD->isIndexed())
8614 VT = LD->getMemoryVT();
8615 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8616 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8618 Ptr = LD->getBasePtr();
8619 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8620 if (ST->isIndexed())
8622 VT = ST->getMemoryVT();
8623 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8624 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8626 Ptr = ST->getBasePtr();
8632 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8633 // out. There is no reason to make this a preinc/predec.
8634 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8635 Ptr.getNode()->hasOneUse())
8638 // Ask the target to do addressing mode selection.
8641 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8642 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8645 // Backends without true r+i pre-indexed forms may need to pass a
8646 // constant base with a variable offset so that constant coercion
8647 // will work with the patterns in canonical form.
8648 bool Swapped = false;
8649 if (isa<ConstantSDNode>(BasePtr)) {
8650 std::swap(BasePtr, Offset);
8654 // Don't create a indexed load / store with zero offset.
8655 if (isa<ConstantSDNode>(Offset) &&
8656 cast<ConstantSDNode>(Offset)->isNullValue())
8659 // Try turning it into a pre-indexed load / store except when:
8660 // 1) The new base ptr is a frame index.
8661 // 2) If N is a store and the new base ptr is either the same as or is a
8662 // predecessor of the value being stored.
8663 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8664 // that would create a cycle.
8665 // 4) All uses are load / store ops that use it as old base ptr.
8667 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8668 // (plus the implicit offset) to a register to preinc anyway.
8669 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8674 SDValue Val = cast<StoreSDNode>(N)->getValue();
8675 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8679 // If the offset is a constant, there may be other adds of constants that
8680 // can be folded with this one. We should do this to avoid having to keep
8681 // a copy of the original base pointer.
8682 SmallVector<SDNode *, 16> OtherUses;
8683 if (isa<ConstantSDNode>(Offset))
8684 for (SDNode *Use : BasePtr.getNode()->uses()) {
8685 if (Use == Ptr.getNode())
8688 if (Use->isPredecessorOf(N))
8691 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8696 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8697 if (Op1.getNode() == BasePtr.getNode())
8698 std::swap(Op0, Op1);
8699 assert(Op0.getNode() == BasePtr.getNode() &&
8700 "Use of ADD/SUB but not an operand");
8702 if (!isa<ConstantSDNode>(Op1)) {
8707 // FIXME: In some cases, we can be smarter about this.
8708 if (Op1.getValueType() != Offset.getValueType()) {
8713 OtherUses.push_back(Use);
8717 std::swap(BasePtr, Offset);
8719 // Now check for #3 and #4.
8720 bool RealUse = false;
8722 // Caches for hasPredecessorHelper
8723 SmallPtrSet<const SDNode *, 32> Visited;
8724 SmallVector<const SDNode *, 16> Worklist;
8726 for (SDNode *Use : Ptr.getNode()->uses()) {
8729 if (N->hasPredecessorHelper(Use, Visited, Worklist))
8732 // If Ptr may be folded in addressing mode of other use, then it's
8733 // not profitable to do this transformation.
8734 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8743 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8744 BasePtr, Offset, AM);
8746 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8747 BasePtr, Offset, AM);
8750 DEBUG(dbgs() << "\nReplacing.4 ";
8752 dbgs() << "\nWith: ";
8753 Result.getNode()->dump(&DAG);
8755 WorklistRemover DeadNodes(*this);
8757 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8758 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8760 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8763 // Finally, since the node is now dead, remove it from the graph.
8764 deleteAndRecombine(N);
8767 std::swap(BasePtr, Offset);
8769 // Replace other uses of BasePtr that can be updated to use Ptr
8770 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8771 unsigned OffsetIdx = 1;
8772 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8774 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8775 BasePtr.getNode() && "Expected BasePtr operand");
8777 // We need to replace ptr0 in the following expression:
8778 // x0 * offset0 + y0 * ptr0 = t0
8780 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8782 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8783 // indexed load/store and the expresion that needs to be re-written.
8785 // Therefore, we have:
8786 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8788 ConstantSDNode *CN =
8789 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8791 APInt Offset0 = CN->getAPIntValue();
8792 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8794 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8795 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8796 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8797 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8799 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8801 APInt CNV = Offset0;
8802 if (X0 < 0) CNV = -CNV;
8803 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8804 else CNV = CNV - Offset1;
8806 // We can now generate the new expression.
8807 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8808 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8810 SDValue NewUse = DAG.getNode(Opcode,
8811 SDLoc(OtherUses[i]),
8812 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8813 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8814 deleteAndRecombine(OtherUses[i]);
8817 // Replace the uses of Ptr with uses of the updated base value.
8818 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8819 deleteAndRecombine(Ptr.getNode());
8824 /// Try to combine a load/store with a add/sub of the base pointer node into a
8825 /// post-indexed load/store. The transformation folded the add/subtract into the
8826 /// new indexed load/store effectively and all of its uses are redirected to the
8828 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8829 if (Level < AfterLegalizeDAG)
8835 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8836 if (LD->isIndexed())
8838 VT = LD->getMemoryVT();
8839 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8840 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8842 Ptr = LD->getBasePtr();
8843 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8844 if (ST->isIndexed())
8846 VT = ST->getMemoryVT();
8847 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8848 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8850 Ptr = ST->getBasePtr();
8856 if (Ptr.getNode()->hasOneUse())
8859 for (SDNode *Op : Ptr.getNode()->uses()) {
8861 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8866 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8867 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8868 // Don't create a indexed load / store with zero offset.
8869 if (isa<ConstantSDNode>(Offset) &&
8870 cast<ConstantSDNode>(Offset)->isNullValue())
8873 // Try turning it into a post-indexed load / store except when
8874 // 1) All uses are load / store ops that use it as base ptr (and
8875 // it may be folded as addressing mmode).
8876 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8877 // nor a successor of N. Otherwise, if Op is folded that would
8880 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8884 bool TryNext = false;
8885 for (SDNode *Use : BasePtr.getNode()->uses()) {
8886 if (Use == Ptr.getNode())
8889 // If all the uses are load / store addresses, then don't do the
8891 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8892 bool RealUse = false;
8893 for (SDNode *UseUse : Use->uses()) {
8894 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8909 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8910 SDValue Result = isLoad
8911 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8912 BasePtr, Offset, AM)
8913 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8914 BasePtr, Offset, AM);
8917 DEBUG(dbgs() << "\nReplacing.5 ";
8919 dbgs() << "\nWith: ";
8920 Result.getNode()->dump(&DAG);
8922 WorklistRemover DeadNodes(*this);
8924 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8925 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8927 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8930 // Finally, since the node is now dead, remove it from the graph.
8931 deleteAndRecombine(N);
8933 // Replace the uses of Use with uses of the updated base value.
8934 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8935 Result.getValue(isLoad ? 1 : 0));
8936 deleteAndRecombine(Op);
8945 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8946 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8947 ISD::MemIndexedMode AM = LD->getAddressingMode();
8948 assert(AM != ISD::UNINDEXED);
8949 SDValue BP = LD->getOperand(1);
8950 SDValue Inc = LD->getOperand(2);
8952 // Some backends use TargetConstants for load offsets, but don't expect
8953 // TargetConstants in general ADD nodes. We can convert these constants into
8954 // regular Constants (if the constant is not opaque).
8955 assert((Inc.getOpcode() != ISD::TargetConstant ||
8956 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8957 "Cannot split out indexing using opaque target constants");
8958 if (Inc.getOpcode() == ISD::TargetConstant) {
8959 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8960 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8961 ConstInc->getValueType(0));
8965 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8966 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8969 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8970 LoadSDNode *LD = cast<LoadSDNode>(N);
8971 SDValue Chain = LD->getChain();
8972 SDValue Ptr = LD->getBasePtr();
8974 // If load is not volatile and there are no uses of the loaded value (and
8975 // the updated indexed value in case of indexed loads), change uses of the
8976 // chain value into uses of the chain input (i.e. delete the dead load).
8977 if (!LD->isVolatile()) {
8978 if (N->getValueType(1) == MVT::Other) {
8980 if (!N->hasAnyUseOfValue(0)) {
8981 // It's not safe to use the two value CombineTo variant here. e.g.
8982 // v1, chain2 = load chain1, loc
8983 // v2, chain3 = load chain2, loc
8985 // Now we replace use of chain2 with chain1. This makes the second load
8986 // isomorphic to the one we are deleting, and thus makes this load live.
8987 DEBUG(dbgs() << "\nReplacing.6 ";
8989 dbgs() << "\nWith chain: ";
8990 Chain.getNode()->dump(&DAG);
8992 WorklistRemover DeadNodes(*this);
8993 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8996 deleteAndRecombine(N);
8998 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9002 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9004 // If this load has an opaque TargetConstant offset, then we cannot split
9005 // the indexing into an add/sub directly (that TargetConstant may not be
9006 // valid for a different type of node, and we cannot convert an opaque
9007 // target constant into a regular constant).
9008 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9009 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9011 if (!N->hasAnyUseOfValue(0) &&
9012 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9013 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9015 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9016 Index = SplitIndexingFromLoad(LD);
9017 // Try to fold the base pointer arithmetic into subsequent loads and
9019 AddUsersToWorklist(N);
9021 Index = DAG.getUNDEF(N->getValueType(1));
9022 DEBUG(dbgs() << "\nReplacing.7 ";
9024 dbgs() << "\nWith: ";
9025 Undef.getNode()->dump(&DAG);
9026 dbgs() << " and 2 other values\n");
9027 WorklistRemover DeadNodes(*this);
9028 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9029 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9030 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9031 deleteAndRecombine(N);
9032 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9037 // If this load is directly stored, replace the load value with the stored
9039 // TODO: Handle store large -> read small portion.
9040 // TODO: Handle TRUNCSTORE/LOADEXT
9041 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9042 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9043 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9044 if (PrevST->getBasePtr() == Ptr &&
9045 PrevST->getValue().getValueType() == N->getValueType(0))
9046 return CombineTo(N, Chain.getOperand(1), Chain);
9050 // Try to infer better alignment information than the load already has.
9051 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9052 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9053 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9055 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9056 LD->getValueType(0),
9057 Chain, Ptr, LD->getPointerInfo(),
9059 LD->isVolatile(), LD->isNonTemporal(),
9060 LD->isInvariant(), Align, LD->getAAInfo());
9061 if (NewLoad.getNode() != N)
9062 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9067 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9068 : DAG.getSubtarget().useAA();
9070 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9071 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9074 if (UseAA && LD->isUnindexed()) {
9075 // Walk up chain skipping non-aliasing memory nodes.
9076 SDValue BetterChain = FindBetterChain(N, Chain);
9078 // If there is a better chain.
9079 if (Chain != BetterChain) {
9082 // Replace the chain to void dependency.
9083 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9084 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9085 BetterChain, Ptr, LD->getMemOperand());
9087 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9088 LD->getValueType(0),
9089 BetterChain, Ptr, LD->getMemoryVT(),
9090 LD->getMemOperand());
9093 // Create token factor to keep old chain connected.
9094 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9095 MVT::Other, Chain, ReplLoad.getValue(1));
9097 // Make sure the new and old chains are cleaned up.
9098 AddToWorklist(Token.getNode());
9100 // Replace uses with load result and token factor. Don't add users
9102 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9106 // Try transforming N to an indexed load.
9107 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9108 return SDValue(N, 0);
9110 // Try to slice up N to more direct loads if the slices are mapped to
9111 // different register banks or pairing can take place.
9113 return SDValue(N, 0);
9119 /// \brief Helper structure used to slice a load in smaller loads.
9120 /// Basically a slice is obtained from the following sequence:
9121 /// Origin = load Ty1, Base
9122 /// Shift = srl Ty1 Origin, CstTy Amount
9123 /// Inst = trunc Shift to Ty2
9125 /// Then, it will be rewriten into:
9126 /// Slice = load SliceTy, Base + SliceOffset
9127 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9129 /// SliceTy is deduced from the number of bits that are actually used to
9131 struct LoadedSlice {
9132 /// \brief Helper structure used to compute the cost of a slice.
9134 /// Are we optimizing for code size.
9139 unsigned CrossRegisterBanksCopies;
9143 Cost(bool ForCodeSize = false)
9144 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9145 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9147 /// \brief Get the cost of one isolated slice.
9148 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9149 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9150 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9151 EVT TruncType = LS.Inst->getValueType(0);
9152 EVT LoadedType = LS.getLoadedType();
9153 if (TruncType != LoadedType &&
9154 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9158 /// \brief Account for slicing gain in the current cost.
9159 /// Slicing provide a few gains like removing a shift or a
9160 /// truncate. This method allows to grow the cost of the original
9161 /// load with the gain from this slice.
9162 void addSliceGain(const LoadedSlice &LS) {
9163 // Each slice saves a truncate.
9164 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9165 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9166 LS.Inst->getOperand(0).getValueType()))
9168 // If there is a shift amount, this slice gets rid of it.
9171 // If this slice can merge a cross register bank copy, account for it.
9172 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9173 ++CrossRegisterBanksCopies;
9176 Cost &operator+=(const Cost &RHS) {
9178 Truncates += RHS.Truncates;
9179 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9185 bool operator==(const Cost &RHS) const {
9186 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9187 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9188 ZExts == RHS.ZExts && Shift == RHS.Shift;
9191 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9193 bool operator<(const Cost &RHS) const {
9194 // Assume cross register banks copies are as expensive as loads.
9195 // FIXME: Do we want some more target hooks?
9196 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9197 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9198 // Unless we are optimizing for code size, consider the
9199 // expensive operation first.
9200 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9201 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9202 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9203 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9206 bool operator>(const Cost &RHS) const { return RHS < *this; }
9208 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9210 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9212 // The last instruction that represent the slice. This should be a
9213 // truncate instruction.
9215 // The original load instruction.
9217 // The right shift amount in bits from the original load.
9219 // The DAG from which Origin came from.
9220 // This is used to get some contextual information about legal types, etc.
9223 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9224 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9225 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9227 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9228 /// \return Result is \p BitWidth and has used bits set to 1 and
9229 /// not used bits set to 0.
9230 APInt getUsedBits() const {
9231 // Reproduce the trunc(lshr) sequence:
9232 // - Start from the truncated value.
9233 // - Zero extend to the desired bit width.
9235 assert(Origin && "No original load to compare against.");
9236 unsigned BitWidth = Origin->getValueSizeInBits(0);
9237 assert(Inst && "This slice is not bound to an instruction");
9238 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9239 "Extracted slice is bigger than the whole type!");
9240 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9241 UsedBits.setAllBits();
9242 UsedBits = UsedBits.zext(BitWidth);
9247 /// \brief Get the size of the slice to be loaded in bytes.
9248 unsigned getLoadedSize() const {
9249 unsigned SliceSize = getUsedBits().countPopulation();
9250 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9251 return SliceSize / 8;
9254 /// \brief Get the type that will be loaded for this slice.
9255 /// Note: This may not be the final type for the slice.
9256 EVT getLoadedType() const {
9257 assert(DAG && "Missing context");
9258 LLVMContext &Ctxt = *DAG->getContext();
9259 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9262 /// \brief Get the alignment of the load used for this slice.
9263 unsigned getAlignment() const {
9264 unsigned Alignment = Origin->getAlignment();
9265 unsigned Offset = getOffsetFromBase();
9267 Alignment = MinAlign(Alignment, Alignment + Offset);
9271 /// \brief Check if this slice can be rewritten with legal operations.
9272 bool isLegal() const {
9273 // An invalid slice is not legal.
9274 if (!Origin || !Inst || !DAG)
9277 // Offsets are for indexed load only, we do not handle that.
9278 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9281 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9283 // Check that the type is legal.
9284 EVT SliceType = getLoadedType();
9285 if (!TLI.isTypeLegal(SliceType))
9288 // Check that the load is legal for this type.
9289 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9292 // Check that the offset can be computed.
9293 // 1. Check its type.
9294 EVT PtrType = Origin->getBasePtr().getValueType();
9295 if (PtrType == MVT::Untyped || PtrType.isExtended())
9298 // 2. Check that it fits in the immediate.
9299 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9302 // 3. Check that the computation is legal.
9303 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9306 // Check that the zext is legal if it needs one.
9307 EVT TruncateType = Inst->getValueType(0);
9308 if (TruncateType != SliceType &&
9309 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9315 /// \brief Get the offset in bytes of this slice in the original chunk of
9317 /// \pre DAG != nullptr.
9318 uint64_t getOffsetFromBase() const {
9319 assert(DAG && "Missing context.");
9321 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9322 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9323 uint64_t Offset = Shift / 8;
9324 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9325 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9326 "The size of the original loaded type is not a multiple of a"
9328 // If Offset is bigger than TySizeInBytes, it means we are loading all
9329 // zeros. This should have been optimized before in the process.
9330 assert(TySizeInBytes > Offset &&
9331 "Invalid shift amount for given loaded size");
9333 Offset = TySizeInBytes - Offset - getLoadedSize();
9337 /// \brief Generate the sequence of instructions to load the slice
9338 /// represented by this object and redirect the uses of this slice to
9339 /// this new sequence of instructions.
9340 /// \pre this->Inst && this->Origin are valid Instructions and this
9341 /// object passed the legal check: LoadedSlice::isLegal returned true.
9342 /// \return The last instruction of the sequence used to load the slice.
9343 SDValue loadSlice() const {
9344 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9345 const SDValue &OldBaseAddr = Origin->getBasePtr();
9346 SDValue BaseAddr = OldBaseAddr;
9347 // Get the offset in that chunk of bytes w.r.t. the endianess.
9348 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9349 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9351 // BaseAddr = BaseAddr + Offset.
9352 EVT ArithType = BaseAddr.getValueType();
9353 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9354 DAG->getConstant(Offset, ArithType));
9357 // Create the type of the loaded slice according to its size.
9358 EVT SliceType = getLoadedType();
9360 // Create the load for the slice.
9361 SDValue LastInst = DAG->getLoad(
9362 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9363 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9364 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9365 // If the final type is not the same as the loaded type, this means that
9366 // we have to pad with zero. Create a zero extend for that.
9367 EVT FinalType = Inst->getValueType(0);
9368 if (SliceType != FinalType)
9370 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9374 /// \brief Check if this slice can be merged with an expensive cross register
9375 /// bank copy. E.g.,
9377 /// f = bitcast i32 i to float
9378 bool canMergeExpensiveCrossRegisterBankCopy() const {
9379 if (!Inst || !Inst->hasOneUse())
9381 SDNode *Use = *Inst->use_begin();
9382 if (Use->getOpcode() != ISD::BITCAST)
9384 assert(DAG && "Missing context");
9385 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9386 EVT ResVT = Use->getValueType(0);
9387 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9388 const TargetRegisterClass *ArgRC =
9389 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9390 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9393 // At this point, we know that we perform a cross-register-bank copy.
9394 // Check if it is expensive.
9395 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9396 // Assume bitcasts are cheap, unless both register classes do not
9397 // explicitly share a common sub class.
9398 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9401 // Check if it will be merged with the load.
9402 // 1. Check the alignment constraint.
9403 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9404 ResVT.getTypeForEVT(*DAG->getContext()));
9406 if (RequiredAlignment > getAlignment())
9409 // 2. Check that the load is a legal operation for that type.
9410 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9413 // 3. Check that we do not have a zext in the way.
9414 if (Inst->getValueType(0) != getLoadedType())
9422 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9423 /// \p UsedBits looks like 0..0 1..1 0..0.
9424 static bool areUsedBitsDense(const APInt &UsedBits) {
9425 // If all the bits are one, this is dense!
9426 if (UsedBits.isAllOnesValue())
9429 // Get rid of the unused bits on the right.
9430 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9431 // Get rid of the unused bits on the left.
9432 if (NarrowedUsedBits.countLeadingZeros())
9433 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9434 // Check that the chunk of bits is completely used.
9435 return NarrowedUsedBits.isAllOnesValue();
9438 /// \brief Check whether or not \p First and \p Second are next to each other
9439 /// in memory. This means that there is no hole between the bits loaded
9440 /// by \p First and the bits loaded by \p Second.
9441 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9442 const LoadedSlice &Second) {
9443 assert(First.Origin == Second.Origin && First.Origin &&
9444 "Unable to match different memory origins.");
9445 APInt UsedBits = First.getUsedBits();
9446 assert((UsedBits & Second.getUsedBits()) == 0 &&
9447 "Slices are not supposed to overlap.");
9448 UsedBits |= Second.getUsedBits();
9449 return areUsedBitsDense(UsedBits);
9452 /// \brief Adjust the \p GlobalLSCost according to the target
9453 /// paring capabilities and the layout of the slices.
9454 /// \pre \p GlobalLSCost should account for at least as many loads as
9455 /// there is in the slices in \p LoadedSlices.
9456 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9457 LoadedSlice::Cost &GlobalLSCost) {
9458 unsigned NumberOfSlices = LoadedSlices.size();
9459 // If there is less than 2 elements, no pairing is possible.
9460 if (NumberOfSlices < 2)
9463 // Sort the slices so that elements that are likely to be next to each
9464 // other in memory are next to each other in the list.
9465 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9466 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9467 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9468 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9470 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9471 // First (resp. Second) is the first (resp. Second) potentially candidate
9472 // to be placed in a paired load.
9473 const LoadedSlice *First = nullptr;
9474 const LoadedSlice *Second = nullptr;
9475 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9476 // Set the beginning of the pair.
9479 Second = &LoadedSlices[CurrSlice];
9481 // If First is NULL, it means we start a new pair.
9482 // Get to the next slice.
9486 EVT LoadedType = First->getLoadedType();
9488 // If the types of the slices are different, we cannot pair them.
9489 if (LoadedType != Second->getLoadedType())
9492 // Check if the target supplies paired loads for this type.
9493 unsigned RequiredAlignment = 0;
9494 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9495 // move to the next pair, this type is hopeless.
9499 // Check if we meet the alignment requirement.
9500 if (RequiredAlignment > First->getAlignment())
9503 // Check that both loads are next to each other in memory.
9504 if (!areSlicesNextToEachOther(*First, *Second))
9507 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9508 --GlobalLSCost.Loads;
9509 // Move to the next pair.
9514 /// \brief Check the profitability of all involved LoadedSlice.
9515 /// Currently, it is considered profitable if there is exactly two
9516 /// involved slices (1) which are (2) next to each other in memory, and
9517 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9519 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9520 /// the elements themselves.
9522 /// FIXME: When the cost model will be mature enough, we can relax
9523 /// constraints (1) and (2).
9524 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9525 const APInt &UsedBits, bool ForCodeSize) {
9526 unsigned NumberOfSlices = LoadedSlices.size();
9527 if (StressLoadSlicing)
9528 return NumberOfSlices > 1;
9531 if (NumberOfSlices != 2)
9535 if (!areUsedBitsDense(UsedBits))
9539 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9540 // The original code has one big load.
9542 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9543 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9544 // Accumulate the cost of all the slices.
9545 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9546 GlobalSlicingCost += SliceCost;
9548 // Account as cost in the original configuration the gain obtained
9549 // with the current slices.
9550 OrigCost.addSliceGain(LS);
9553 // If the target supports paired load, adjust the cost accordingly.
9554 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9555 return OrigCost > GlobalSlicingCost;
9558 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9559 /// operations, split it in the various pieces being extracted.
9561 /// This sort of thing is introduced by SROA.
9562 /// This slicing takes care not to insert overlapping loads.
9563 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9564 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9565 if (Level < AfterLegalizeDAG)
9568 LoadSDNode *LD = cast<LoadSDNode>(N);
9569 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9570 !LD->getValueType(0).isInteger())
9573 // Keep track of already used bits to detect overlapping values.
9574 // In that case, we will just abort the transformation.
9575 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9577 SmallVector<LoadedSlice, 4> LoadedSlices;
9579 // Check if this load is used as several smaller chunks of bits.
9580 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9581 // of computation for each trunc.
9582 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9583 UI != UIEnd; ++UI) {
9584 // Skip the uses of the chain.
9585 if (UI.getUse().getResNo() != 0)
9591 // Check if this is a trunc(lshr).
9592 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9593 isa<ConstantSDNode>(User->getOperand(1))) {
9594 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9595 User = *User->use_begin();
9598 // At this point, User is a Truncate, iff we encountered, trunc or
9600 if (User->getOpcode() != ISD::TRUNCATE)
9603 // The width of the type must be a power of 2 and greater than 8-bits.
9604 // Otherwise the load cannot be represented in LLVM IR.
9605 // Moreover, if we shifted with a non-8-bits multiple, the slice
9606 // will be across several bytes. We do not support that.
9607 unsigned Width = User->getValueSizeInBits(0);
9608 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9611 // Build the slice for this chain of computations.
9612 LoadedSlice LS(User, LD, Shift, &DAG);
9613 APInt CurrentUsedBits = LS.getUsedBits();
9615 // Check if this slice overlaps with another.
9616 if ((CurrentUsedBits & UsedBits) != 0)
9618 // Update the bits used globally.
9619 UsedBits |= CurrentUsedBits;
9621 // Check if the new slice would be legal.
9625 // Record the slice.
9626 LoadedSlices.push_back(LS);
9629 // Abort slicing if it does not seem to be profitable.
9630 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9635 // Rewrite each chain to use an independent load.
9636 // By construction, each chain can be represented by a unique load.
9638 // Prepare the argument for the new token factor for all the slices.
9639 SmallVector<SDValue, 8> ArgChains;
9640 for (SmallVectorImpl<LoadedSlice>::const_iterator
9641 LSIt = LoadedSlices.begin(),
9642 LSItEnd = LoadedSlices.end();
9643 LSIt != LSItEnd; ++LSIt) {
9644 SDValue SliceInst = LSIt->loadSlice();
9645 CombineTo(LSIt->Inst, SliceInst, true);
9646 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9647 SliceInst = SliceInst.getOperand(0);
9648 assert(SliceInst->getOpcode() == ISD::LOAD &&
9649 "It takes more than a zext to get to the loaded slice!!");
9650 ArgChains.push_back(SliceInst.getValue(1));
9653 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9655 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9659 /// Check to see if V is (and load (ptr), imm), where the load is having
9660 /// specific bytes cleared out. If so, return the byte size being masked out
9661 /// and the shift amount.
9662 static std::pair<unsigned, unsigned>
9663 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9664 std::pair<unsigned, unsigned> Result(0, 0);
9666 // Check for the structure we're looking for.
9667 if (V->getOpcode() != ISD::AND ||
9668 !isa<ConstantSDNode>(V->getOperand(1)) ||
9669 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9672 // Check the chain and pointer.
9673 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9674 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
9676 // The store should be chained directly to the load or be an operand of a
9678 if (LD == Chain.getNode())
9680 else if (Chain->getOpcode() != ISD::TokenFactor)
9681 return Result; // Fail.
9684 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9685 if (Chain->getOperand(i).getNode() == LD) {
9689 if (!isOk) return Result;
9692 // This only handles simple types.
9693 if (V.getValueType() != MVT::i16 &&
9694 V.getValueType() != MVT::i32 &&
9695 V.getValueType() != MVT::i64)
9698 // Check the constant mask. Invert it so that the bits being masked out are
9699 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9700 // follow the sign bit for uniformity.
9701 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9702 unsigned NotMaskLZ = countLeadingZeros(NotMask);
9703 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
9704 unsigned NotMaskTZ = countTrailingZeros(NotMask);
9705 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9706 if (NotMaskLZ == 64) return Result; // All zero mask.
9708 // See if we have a continuous run of bits. If so, we have 0*1+0*
9709 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9712 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9713 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9714 NotMaskLZ -= 64-V.getValueSizeInBits();
9716 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9717 switch (MaskedBytes) {
9721 default: return Result; // All one mask, or 5-byte mask.
9724 // Verify that the first bit starts at a multiple of mask so that the access
9725 // is aligned the same as the access width.
9726 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9728 Result.first = MaskedBytes;
9729 Result.second = NotMaskTZ/8;
9734 /// Check to see if IVal is something that provides a value as specified by
9735 /// MaskInfo. If so, replace the specified store with a narrower store of
9738 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9739 SDValue IVal, StoreSDNode *St,
9741 unsigned NumBytes = MaskInfo.first;
9742 unsigned ByteShift = MaskInfo.second;
9743 SelectionDAG &DAG = DC->getDAG();
9745 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9746 // that uses this. If not, this is not a replacement.
9747 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9748 ByteShift*8, (ByteShift+NumBytes)*8);
9749 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9751 // Check that it is legal on the target to do this. It is legal if the new
9752 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9754 MVT VT = MVT::getIntegerVT(NumBytes*8);
9755 if (!DC->isTypeLegal(VT))
9758 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9759 // shifted by ByteShift and truncated down to NumBytes.
9761 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9762 DAG.getConstant(ByteShift*8,
9763 DC->getShiftAmountTy(IVal.getValueType())));
9765 // Figure out the offset for the store and the alignment of the access.
9767 unsigned NewAlign = St->getAlignment();
9769 if (DAG.getTargetLoweringInfo().isLittleEndian())
9770 StOffset = ByteShift;
9772 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9774 SDValue Ptr = St->getBasePtr();
9776 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9777 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9778 NewAlign = MinAlign(NewAlign, StOffset);
9781 // Truncate down to the new size.
9782 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9785 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9786 St->getPointerInfo().getWithOffset(StOffset),
9787 false, false, NewAlign).getNode();
9791 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9792 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9793 /// narrowing the load and store if it would end up being a win for performance
9795 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9796 StoreSDNode *ST = cast<StoreSDNode>(N);
9797 if (ST->isVolatile())
9800 SDValue Chain = ST->getChain();
9801 SDValue Value = ST->getValue();
9802 SDValue Ptr = ST->getBasePtr();
9803 EVT VT = Value.getValueType();
9805 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9808 unsigned Opc = Value.getOpcode();
9810 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9811 // is a byte mask indicating a consecutive number of bytes, check to see if
9812 // Y is known to provide just those bytes. If so, we try to replace the
9813 // load + replace + store sequence with a single (narrower) store, which makes
9815 if (Opc == ISD::OR) {
9816 std::pair<unsigned, unsigned> MaskedLoad;
9817 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9818 if (MaskedLoad.first)
9819 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9820 Value.getOperand(1), ST,this))
9821 return SDValue(NewST, 0);
9823 // Or is commutative, so try swapping X and Y.
9824 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9825 if (MaskedLoad.first)
9826 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9827 Value.getOperand(0), ST,this))
9828 return SDValue(NewST, 0);
9831 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9832 Value.getOperand(1).getOpcode() != ISD::Constant)
9835 SDValue N0 = Value.getOperand(0);
9836 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9837 Chain == SDValue(N0.getNode(), 1)) {
9838 LoadSDNode *LD = cast<LoadSDNode>(N0);
9839 if (LD->getBasePtr() != Ptr ||
9840 LD->getPointerInfo().getAddrSpace() !=
9841 ST->getPointerInfo().getAddrSpace())
9844 // Find the type to narrow it the load / op / store to.
9845 SDValue N1 = Value.getOperand(1);
9846 unsigned BitWidth = N1.getValueSizeInBits();
9847 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9848 if (Opc == ISD::AND)
9849 Imm ^= APInt::getAllOnesValue(BitWidth);
9850 if (Imm == 0 || Imm.isAllOnesValue())
9852 unsigned ShAmt = Imm.countTrailingZeros();
9853 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9854 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9855 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9856 // The narrowing should be profitable, the load/store operation should be
9857 // legal (or custom) and the store size should be equal to the NewVT width.
9858 while (NewBW < BitWidth &&
9859 (NewVT.getStoreSizeInBits() != NewBW ||
9860 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9861 !TLI.isNarrowingProfitable(VT, NewVT))) {
9862 NewBW = NextPowerOf2(NewBW);
9863 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9865 if (NewBW >= BitWidth)
9868 // If the lsb changed does not start at the type bitwidth boundary,
9869 // start at the previous one.
9871 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9872 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9873 std::min(BitWidth, ShAmt + NewBW));
9874 if ((Imm & Mask) == Imm) {
9875 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9876 if (Opc == ISD::AND)
9877 NewImm ^= APInt::getAllOnesValue(NewBW);
9878 uint64_t PtrOff = ShAmt / 8;
9879 // For big endian targets, we need to adjust the offset to the pointer to
9880 // load the correct bytes.
9881 if (TLI.isBigEndian())
9882 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9884 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9885 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9886 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9889 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9890 Ptr.getValueType(), Ptr,
9891 DAG.getConstant(PtrOff, Ptr.getValueType()));
9892 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9893 LD->getChain(), NewPtr,
9894 LD->getPointerInfo().getWithOffset(PtrOff),
9895 LD->isVolatile(), LD->isNonTemporal(),
9896 LD->isInvariant(), NewAlign,
9898 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9899 DAG.getConstant(NewImm, NewVT));
9900 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9902 ST->getPointerInfo().getWithOffset(PtrOff),
9903 false, false, NewAlign);
9905 AddToWorklist(NewPtr.getNode());
9906 AddToWorklist(NewLD.getNode());
9907 AddToWorklist(NewVal.getNode());
9908 WorklistRemover DeadNodes(*this);
9909 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9918 /// For a given floating point load / store pair, if the load value isn't used
9919 /// by any other operations, then consider transforming the pair to integer
9920 /// load / store operations if the target deems the transformation profitable.
9921 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9922 StoreSDNode *ST = cast<StoreSDNode>(N);
9923 SDValue Chain = ST->getChain();
9924 SDValue Value = ST->getValue();
9925 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9926 Value.hasOneUse() &&
9927 Chain == SDValue(Value.getNode(), 1)) {
9928 LoadSDNode *LD = cast<LoadSDNode>(Value);
9929 EVT VT = LD->getMemoryVT();
9930 if (!VT.isFloatingPoint() ||
9931 VT != ST->getMemoryVT() ||
9932 LD->isNonTemporal() ||
9933 ST->isNonTemporal() ||
9934 LD->getPointerInfo().getAddrSpace() != 0 ||
9935 ST->getPointerInfo().getAddrSpace() != 0)
9938 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9939 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9940 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9941 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9942 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9945 unsigned LDAlign = LD->getAlignment();
9946 unsigned STAlign = ST->getAlignment();
9947 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9948 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9949 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9952 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9953 LD->getChain(), LD->getBasePtr(),
9954 LD->getPointerInfo(),
9955 false, false, false, LDAlign);
9957 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9958 NewLD, ST->getBasePtr(),
9959 ST->getPointerInfo(),
9960 false, false, STAlign);
9962 AddToWorklist(NewLD.getNode());
9963 AddToWorklist(NewST.getNode());
9964 WorklistRemover DeadNodes(*this);
9965 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9974 /// Helper struct to parse and store a memory address as base + index + offset.
9975 /// We ignore sign extensions when it is safe to do so.
9976 /// The following two expressions are not equivalent. To differentiate we need
9977 /// to store whether there was a sign extension involved in the index
9979 /// (load (i64 add (i64 copyfromreg %c)
9980 /// (i64 signextend (add (i8 load %index)
9984 /// (load (i64 add (i64 copyfromreg %c)
9985 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9987 struct BaseIndexOffset {
9991 bool IsIndexSignExt;
9993 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9995 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9996 bool IsIndexSignExt) :
9997 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9999 bool equalBaseIndex(const BaseIndexOffset &Other) {
10000 return Other.Base == Base && Other.Index == Index &&
10001 Other.IsIndexSignExt == IsIndexSignExt;
10004 /// Parses tree in Ptr for base, index, offset addresses.
10005 static BaseIndexOffset match(SDValue Ptr) {
10006 bool IsIndexSignExt = false;
10008 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10009 // instruction, then it could be just the BASE or everything else we don't
10010 // know how to handle. Just use Ptr as BASE and give up.
10011 if (Ptr->getOpcode() != ISD::ADD)
10012 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10014 // We know that we have at least an ADD instruction. Try to pattern match
10015 // the simple case of BASE + OFFSET.
10016 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10017 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10018 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10022 // Inside a loop the current BASE pointer is calculated using an ADD and a
10023 // MUL instruction. In this case Ptr is the actual BASE pointer.
10024 // (i64 add (i64 %array_ptr)
10025 // (i64 mul (i64 %induction_var)
10026 // (i64 %element_size)))
10027 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10028 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10030 // Look at Base + Index + Offset cases.
10031 SDValue Base = Ptr->getOperand(0);
10032 SDValue IndexOffset = Ptr->getOperand(1);
10034 // Skip signextends.
10035 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10036 IndexOffset = IndexOffset->getOperand(0);
10037 IsIndexSignExt = true;
10040 // Either the case of Base + Index (no offset) or something else.
10041 if (IndexOffset->getOpcode() != ISD::ADD)
10042 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10044 // Now we have the case of Base + Index + offset.
10045 SDValue Index = IndexOffset->getOperand(0);
10046 SDValue Offset = IndexOffset->getOperand(1);
10048 if (!isa<ConstantSDNode>(Offset))
10049 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10051 // Ignore signextends.
10052 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10053 Index = Index->getOperand(0);
10054 IsIndexSignExt = true;
10055 } else IsIndexSignExt = false;
10057 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10058 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10063 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10064 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10065 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10066 // Make sure we have something to merge.
10070 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10071 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10072 unsigned EarliestNodeUsed = 0;
10074 for (unsigned i=0; i < NumElem; ++i) {
10075 // Find a chain for the new wide-store operand. Notice that some
10076 // of the store nodes that we found may not be selected for inclusion
10077 // in the wide store. The chain we use needs to be the chain of the
10078 // earliest store node which is *used* and replaced by the wide store.
10079 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10080 EarliestNodeUsed = i;
10083 // The earliest Node in the DAG.
10084 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10085 SDLoc DL(StoreNodes[0].MemNode);
10089 // Find a legal type for the vector store.
10090 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10091 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10092 if (IsConstantSrc) {
10093 // A vector store with a constant source implies that the constant is
10094 // zero; we only handle merging stores of constant zeros because the zero
10095 // can be materialized without a load.
10096 // It may be beneficial to loosen this restriction to allow non-zero
10098 StoredVal = DAG.getConstant(0, Ty);
10100 SmallVector<SDValue, 8> Ops;
10101 for (unsigned i = 0; i < NumElem ; ++i) {
10102 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10103 SDValue Val = St->getValue();
10104 // All of the operands of a BUILD_VECTOR must have the same type.
10105 if (Val.getValueType() != MemVT)
10107 Ops.push_back(Val);
10110 // Build the extracted vector elements back into a vector.
10111 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10114 // We should always use a vector store when merging extracted vector
10115 // elements, so this path implies a store of constants.
10116 assert(IsConstantSrc && "Merged vector elements should use vector store");
10118 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10119 APInt StoreInt(StoreBW, 0);
10121 // Construct a single integer constant which is made of the smaller
10122 // constant inputs.
10123 bool IsLE = TLI.isLittleEndian();
10124 for (unsigned i = 0; i < NumElem ; ++i) {
10125 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10126 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10127 SDValue Val = St->getValue();
10128 StoreInt <<= ElementSizeBytes*8;
10129 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10130 StoreInt |= C->getAPIntValue().zext(StoreBW);
10131 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10132 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10134 llvm_unreachable("Invalid constant element type");
10138 // Create the new Load and Store operations.
10139 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10140 StoredVal = DAG.getConstant(StoreInt, StoreTy);
10143 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
10144 FirstInChain->getBasePtr(),
10145 FirstInChain->getPointerInfo(),
10147 FirstInChain->getAlignment());
10149 // Replace the first store with the new store
10150 CombineTo(EarliestOp, NewStore);
10151 // Erase all other stores.
10152 for (unsigned i = 0; i < NumElem ; ++i) {
10153 if (StoreNodes[i].MemNode == EarliestOp)
10155 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10156 // ReplaceAllUsesWith will replace all uses that existed when it was
10157 // called, but graph optimizations may cause new ones to appear. For
10158 // example, the case in pr14333 looks like
10160 // St's chain -> St -> another store -> X
10162 // And the only difference from St to the other store is the chain.
10163 // When we change it's chain to be St's chain they become identical,
10164 // get CSEed and the net result is that X is now a use of St.
10165 // Since we know that St is redundant, just iterate.
10166 while (!St->use_empty())
10167 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10168 deleteAndRecombine(St);
10174 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10175 if (OptLevel == CodeGenOpt::None)
10178 EVT MemVT = St->getMemoryVT();
10179 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10180 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10181 Attribute::NoImplicitFloat);
10183 // Don't merge vectors into wider inputs.
10184 if (MemVT.isVector() || !MemVT.isSimple())
10187 // Perform an early exit check. Do not bother looking at stored values that
10188 // are not constants, loads, or extracted vector elements.
10189 SDValue StoredVal = St->getValue();
10190 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10191 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10192 isa<ConstantFPSDNode>(StoredVal);
10193 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10195 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10198 // Only look at ends of store sequences.
10199 SDValue Chain = SDValue(St, 0);
10200 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10203 // This holds the base pointer, index, and the offset in bytes from the base
10205 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10207 // We must have a base and an offset.
10208 if (!BasePtr.Base.getNode())
10211 // Do not handle stores to undef base pointers.
10212 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10215 // Save the LoadSDNodes that we find in the chain.
10216 // We need to make sure that these nodes do not interfere with
10217 // any of the store nodes.
10218 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10220 // Save the StoreSDNodes that we find in the chain.
10221 SmallVector<MemOpLink, 8> StoreNodes;
10223 // Walk up the chain and look for nodes with offsets from the same
10224 // base pointer. Stop when reaching an instruction with a different kind
10225 // or instruction which has a different base pointer.
10227 StoreSDNode *Index = St;
10229 // If the chain has more than one use, then we can't reorder the mem ops.
10230 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10233 // Find the base pointer and offset for this memory node.
10234 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10236 // Check that the base pointer is the same as the original one.
10237 if (!Ptr.equalBaseIndex(BasePtr))
10240 // Check that the alignment is the same.
10241 if (Index->getAlignment() != St->getAlignment())
10244 // The memory operands must not be volatile.
10245 if (Index->isVolatile() || Index->isIndexed())
10249 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10250 if (St->isTruncatingStore())
10253 // The stored memory type must be the same.
10254 if (Index->getMemoryVT() != MemVT)
10257 // We do not allow unaligned stores because we want to prevent overriding
10259 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10262 // We found a potential memory operand to merge.
10263 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10265 // Find the next memory operand in the chain. If the next operand in the
10266 // chain is a store then move up and continue the scan with the next
10267 // memory operand. If the next operand is a load save it and use alias
10268 // information to check if it interferes with anything.
10269 SDNode *NextInChain = Index->getChain().getNode();
10271 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10272 // We found a store node. Use it for the next iteration.
10275 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10276 if (Ldn->isVolatile()) {
10281 // Save the load node for later. Continue the scan.
10282 AliasLoadNodes.push_back(Ldn);
10283 NextInChain = Ldn->getChain().getNode();
10292 // Check if there is anything to merge.
10293 if (StoreNodes.size() < 2)
10296 // Sort the memory operands according to their distance from the base pointer.
10297 std::sort(StoreNodes.begin(), StoreNodes.end(),
10298 [](MemOpLink LHS, MemOpLink RHS) {
10299 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10300 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10301 LHS.SequenceNum > RHS.SequenceNum);
10304 // Scan the memory operations on the chain and find the first non-consecutive
10305 // store memory address.
10306 unsigned LastConsecutiveStore = 0;
10307 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10308 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10310 // Check that the addresses are consecutive starting from the second
10311 // element in the list of stores.
10313 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10314 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10318 bool Alias = false;
10319 // Check if this store interferes with any of the loads that we found.
10320 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10321 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10325 // We found a load that alias with this store. Stop the sequence.
10329 // Mark this node as useful.
10330 LastConsecutiveStore = i;
10333 // The node with the lowest store address.
10334 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10336 // Store the constants into memory as one consecutive store.
10337 if (IsConstantSrc) {
10338 unsigned LastLegalType = 0;
10339 unsigned LastLegalVectorType = 0;
10340 bool NonZero = false;
10341 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10342 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10343 SDValue StoredVal = St->getValue();
10345 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10346 NonZero |= !C->isNullValue();
10347 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10348 NonZero |= !C->getConstantFPValue()->isNullValue();
10354 // Find a legal type for the constant store.
10355 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10356 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10357 if (TLI.isTypeLegal(StoreTy))
10358 LastLegalType = i+1;
10359 // Or check whether a truncstore is legal.
10360 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10361 TargetLowering::TypePromoteInteger) {
10362 EVT LegalizedStoredValueTy =
10363 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10364 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10365 LastLegalType = i+1;
10368 // Find a legal type for the vector store.
10369 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10370 if (TLI.isTypeLegal(Ty))
10371 LastLegalVectorType = i + 1;
10374 // We only use vectors if the constant is known to be zero and the
10375 // function is not marked with the noimplicitfloat attribute.
10376 if (NonZero || NoVectors)
10377 LastLegalVectorType = 0;
10379 // Check if we found a legal integer type to store.
10380 if (LastLegalType == 0 && LastLegalVectorType == 0)
10383 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10384 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10386 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10390 // When extracting multiple vector elements, try to store them
10391 // in one vector store rather than a sequence of scalar stores.
10392 if (IsExtractVecEltSrc) {
10393 unsigned NumElem = 0;
10394 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10395 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10396 SDValue StoredVal = St->getValue();
10397 // This restriction could be loosened.
10398 // Bail out if any stored values are not elements extracted from a vector.
10399 // It should be possible to handle mixed sources, but load sources need
10400 // more careful handling (see the block of code below that handles
10401 // consecutive loads).
10402 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10405 // Find a legal type for the vector store.
10406 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10407 if (TLI.isTypeLegal(Ty))
10411 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10415 // Below we handle the case of multiple consecutive stores that
10416 // come from multiple consecutive loads. We merge them into a single
10417 // wide load and a single wide store.
10419 // Look for load nodes which are used by the stored values.
10420 SmallVector<MemOpLink, 8> LoadNodes;
10422 // Find acceptable loads. Loads need to have the same chain (token factor),
10423 // must not be zext, volatile, indexed, and they must be consecutive.
10424 BaseIndexOffset LdBasePtr;
10425 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10426 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10427 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10430 // Loads must only have one use.
10431 if (!Ld->hasNUsesOfValue(1, 0))
10434 // Check that the alignment is the same as the stores.
10435 if (Ld->getAlignment() != St->getAlignment())
10438 // The memory operands must not be volatile.
10439 if (Ld->isVolatile() || Ld->isIndexed())
10442 // We do not accept ext loads.
10443 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10446 // The stored memory type must be the same.
10447 if (Ld->getMemoryVT() != MemVT)
10450 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10451 // If this is not the first ptr that we check.
10452 if (LdBasePtr.Base.getNode()) {
10453 // The base ptr must be the same.
10454 if (!LdPtr.equalBaseIndex(LdBasePtr))
10457 // Check that all other base pointers are the same as this one.
10461 // We found a potential memory operand to merge.
10462 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10465 if (LoadNodes.size() < 2)
10468 // If we have load/store pair instructions and we only have two values,
10470 unsigned RequiredAlignment;
10471 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10472 St->getAlignment() >= RequiredAlignment)
10475 // Scan the memory operations on the chain and find the first non-consecutive
10476 // load memory address. These variables hold the index in the store node
10478 unsigned LastConsecutiveLoad = 0;
10479 // This variable refers to the size and not index in the array.
10480 unsigned LastLegalVectorType = 0;
10481 unsigned LastLegalIntegerType = 0;
10482 StartAddress = LoadNodes[0].OffsetFromBase;
10483 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10484 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10485 // All loads much share the same chain.
10486 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10489 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10490 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10492 LastConsecutiveLoad = i;
10494 // Find a legal type for the vector store.
10495 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10496 if (TLI.isTypeLegal(StoreTy))
10497 LastLegalVectorType = i + 1;
10499 // Find a legal type for the integer store.
10500 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10501 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10502 if (TLI.isTypeLegal(StoreTy))
10503 LastLegalIntegerType = i + 1;
10504 // Or check whether a truncstore and extload is legal.
10505 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10506 TargetLowering::TypePromoteInteger) {
10507 EVT LegalizedStoredValueTy =
10508 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10509 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10510 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10511 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10512 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10513 LastLegalIntegerType = i+1;
10517 // Only use vector types if the vector type is larger than the integer type.
10518 // If they are the same, use integers.
10519 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10520 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10522 // We add +1 here because the LastXXX variables refer to location while
10523 // the NumElem refers to array/index size.
10524 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10525 NumElem = std::min(LastLegalType, NumElem);
10530 // The earliest Node in the DAG.
10531 unsigned EarliestNodeUsed = 0;
10532 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10533 for (unsigned i=1; i<NumElem; ++i) {
10534 // Find a chain for the new wide-store operand. Notice that some
10535 // of the store nodes that we found may not be selected for inclusion
10536 // in the wide store. The chain we use needs to be the chain of the
10537 // earliest store node which is *used* and replaced by the wide store.
10538 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10539 EarliestNodeUsed = i;
10542 // Find if it is better to use vectors or integers to load and store
10546 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10548 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10549 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10552 SDLoc LoadDL(LoadNodes[0].MemNode);
10553 SDLoc StoreDL(StoreNodes[0].MemNode);
10555 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10556 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10557 FirstLoad->getChain(),
10558 FirstLoad->getBasePtr(),
10559 FirstLoad->getPointerInfo(),
10560 false, false, false,
10561 FirstLoad->getAlignment());
10563 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10564 FirstInChain->getBasePtr(),
10565 FirstInChain->getPointerInfo(), false, false,
10566 FirstInChain->getAlignment());
10568 // Replace one of the loads with the new load.
10569 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10570 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10571 SDValue(NewLoad.getNode(), 1));
10573 // Remove the rest of the load chains.
10574 for (unsigned i = 1; i < NumElem ; ++i) {
10575 // Replace all chain users of the old load nodes with the chain of the new
10577 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10578 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10581 // Replace the first store with the new store.
10582 CombineTo(EarliestOp, NewStore);
10583 // Erase all other stores.
10584 for (unsigned i = 0; i < NumElem ; ++i) {
10585 // Remove all Store nodes.
10586 if (StoreNodes[i].MemNode == EarliestOp)
10588 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10589 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10590 deleteAndRecombine(St);
10596 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10597 StoreSDNode *ST = cast<StoreSDNode>(N);
10598 SDValue Chain = ST->getChain();
10599 SDValue Value = ST->getValue();
10600 SDValue Ptr = ST->getBasePtr();
10602 // If this is a store of a bit convert, store the input value if the
10603 // resultant store does not need a higher alignment than the original.
10604 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10605 ST->isUnindexed()) {
10606 unsigned OrigAlign = ST->getAlignment();
10607 EVT SVT = Value.getOperand(0).getValueType();
10608 unsigned Align = TLI.getDataLayout()->
10609 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10610 if (Align <= OrigAlign &&
10611 ((!LegalOperations && !ST->isVolatile()) ||
10612 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10613 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10614 Ptr, ST->getPointerInfo(), ST->isVolatile(),
10615 ST->isNonTemporal(), OrigAlign,
10619 // Turn 'store undef, Ptr' -> nothing.
10620 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10623 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10624 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10625 // NOTE: If the original store is volatile, this transform must not increase
10626 // the number of stores. For example, on x86-32 an f64 can be stored in one
10627 // processor operation but an i64 (which is not legal) requires two. So the
10628 // transform should not be done in this case.
10629 if (Value.getOpcode() != ISD::TargetConstantFP) {
10631 switch (CFP->getSimpleValueType(0).SimpleTy) {
10632 default: llvm_unreachable("Unknown FP type");
10633 case MVT::f16: // We don't do this for these yet.
10639 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10640 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10641 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10642 bitcastToAPInt().getZExtValue(), MVT::i32);
10643 return DAG.getStore(Chain, SDLoc(N), Tmp,
10644 Ptr, ST->getMemOperand());
10648 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10649 !ST->isVolatile()) ||
10650 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10651 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10652 getZExtValue(), MVT::i64);
10653 return DAG.getStore(Chain, SDLoc(N), Tmp,
10654 Ptr, ST->getMemOperand());
10657 if (!ST->isVolatile() &&
10658 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10659 // Many FP stores are not made apparent until after legalize, e.g. for
10660 // argument passing. Since this is so common, custom legalize the
10661 // 64-bit integer store into two 32-bit stores.
10662 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10663 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10664 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10665 if (TLI.isBigEndian()) std::swap(Lo, Hi);
10667 unsigned Alignment = ST->getAlignment();
10668 bool isVolatile = ST->isVolatile();
10669 bool isNonTemporal = ST->isNonTemporal();
10670 AAMDNodes AAInfo = ST->getAAInfo();
10672 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10673 Ptr, ST->getPointerInfo(),
10674 isVolatile, isNonTemporal,
10675 ST->getAlignment(), AAInfo);
10676 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10677 DAG.getConstant(4, Ptr.getValueType()));
10678 Alignment = MinAlign(Alignment, 4U);
10679 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10680 Ptr, ST->getPointerInfo().getWithOffset(4),
10681 isVolatile, isNonTemporal,
10682 Alignment, AAInfo);
10683 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10692 // Try to infer better alignment information than the store already has.
10693 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10694 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10695 if (Align > ST->getAlignment()) {
10697 DAG.getTruncStore(Chain, SDLoc(N), Value,
10698 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10699 ST->isVolatile(), ST->isNonTemporal(), Align,
10701 if (NewStore.getNode() != N)
10702 return CombineTo(ST, NewStore, true);
10707 // Try transforming a pair floating point load / store ops to integer
10708 // load / store ops.
10709 SDValue NewST = TransformFPLoadStorePair(N);
10710 if (NewST.getNode())
10713 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10714 : DAG.getSubtarget().useAA();
10716 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10717 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10720 if (UseAA && ST->isUnindexed()) {
10721 // Walk up chain skipping non-aliasing memory nodes.
10722 SDValue BetterChain = FindBetterChain(N, Chain);
10724 // If there is a better chain.
10725 if (Chain != BetterChain) {
10728 // Replace the chain to avoid dependency.
10729 if (ST->isTruncatingStore()) {
10730 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10731 ST->getMemoryVT(), ST->getMemOperand());
10733 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10734 ST->getMemOperand());
10737 // Create token to keep both nodes around.
10738 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10739 MVT::Other, Chain, ReplStore);
10741 // Make sure the new and old chains are cleaned up.
10742 AddToWorklist(Token.getNode());
10744 // Don't add users to work list.
10745 return CombineTo(N, Token, false);
10749 // Try transforming N to an indexed store.
10750 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10751 return SDValue(N, 0);
10753 // FIXME: is there such a thing as a truncating indexed store?
10754 if (ST->isTruncatingStore() && ST->isUnindexed() &&
10755 Value.getValueType().isInteger()) {
10756 // See if we can simplify the input to this truncstore with knowledge that
10757 // only the low bits are being used. For example:
10758 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
10760 GetDemandedBits(Value,
10761 APInt::getLowBitsSet(
10762 Value.getValueType().getScalarType().getSizeInBits(),
10763 ST->getMemoryVT().getScalarType().getSizeInBits()));
10764 AddToWorklist(Value.getNode());
10765 if (Shorter.getNode())
10766 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10767 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10769 // Otherwise, see if we can simplify the operation with
10770 // SimplifyDemandedBits, which only works if the value has a single use.
10771 if (SimplifyDemandedBits(Value,
10772 APInt::getLowBitsSet(
10773 Value.getValueType().getScalarType().getSizeInBits(),
10774 ST->getMemoryVT().getScalarType().getSizeInBits())))
10775 return SDValue(N, 0);
10778 // If this is a load followed by a store to the same location, then the store
10780 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10781 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10782 ST->isUnindexed() && !ST->isVolatile() &&
10783 // There can't be any side effects between the load and store, such as
10784 // a call or store.
10785 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10786 // The store is dead, remove it.
10791 // If this is a store followed by a store with the same value to the same
10792 // location, then the store is dead/noop.
10793 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10794 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10795 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10796 ST1->isUnindexed() && !ST1->isVolatile()) {
10797 // The store is dead, remove it.
10802 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10803 // truncating store. We can do this even if this is already a truncstore.
10804 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10805 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10806 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10807 ST->getMemoryVT())) {
10808 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10809 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10812 // Only perform this optimization before the types are legal, because we
10813 // don't want to perform this optimization on every DAGCombine invocation.
10815 bool EverChanged = false;
10818 // There can be multiple store sequences on the same chain.
10819 // Keep trying to merge store sequences until we are unable to do so
10820 // or until we merge the last store on the chain.
10821 bool Changed = MergeConsecutiveStores(ST);
10822 EverChanged |= Changed;
10823 if (!Changed) break;
10824 } while (ST->getOpcode() != ISD::DELETED_NODE);
10827 return SDValue(N, 0);
10830 return ReduceLoadOpStoreWidth(N);
10833 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10834 SDValue InVec = N->getOperand(0);
10835 SDValue InVal = N->getOperand(1);
10836 SDValue EltNo = N->getOperand(2);
10839 // If the inserted element is an UNDEF, just use the input vector.
10840 if (InVal.getOpcode() == ISD::UNDEF)
10843 EVT VT = InVec.getValueType();
10845 // If we can't generate a legal BUILD_VECTOR, exit
10846 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10849 // Check that we know which element is being inserted
10850 if (!isa<ConstantSDNode>(EltNo))
10852 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10854 // Canonicalize insert_vector_elt dag nodes.
10856 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10857 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10859 // Do this only if the child insert_vector node has one use; also
10860 // do this only if indices are both constants and Idx1 < Idx0.
10861 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10862 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10863 unsigned OtherElt =
10864 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10865 if (Elt < OtherElt) {
10867 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10868 InVec.getOperand(0), InVal, EltNo);
10869 AddToWorklist(NewOp.getNode());
10870 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10871 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10875 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10876 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10877 // vector elements.
10878 SmallVector<SDValue, 8> Ops;
10879 // Do not combine these two vectors if the output vector will not replace
10880 // the input vector.
10881 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10882 Ops.append(InVec.getNode()->op_begin(),
10883 InVec.getNode()->op_end());
10884 } else if (InVec.getOpcode() == ISD::UNDEF) {
10885 unsigned NElts = VT.getVectorNumElements();
10886 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10891 // Insert the element
10892 if (Elt < Ops.size()) {
10893 // All the operands of BUILD_VECTOR must have the same type;
10894 // we enforce that here.
10895 EVT OpVT = Ops[0].getValueType();
10896 if (InVal.getValueType() != OpVT)
10897 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10898 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10899 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10903 // Return the new vector
10904 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10907 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10908 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10909 EVT ResultVT = EVE->getValueType(0);
10910 EVT VecEltVT = InVecVT.getVectorElementType();
10911 unsigned Align = OriginalLoad->getAlignment();
10912 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10913 VecEltVT.getTypeForEVT(*DAG.getContext()));
10915 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10920 SDValue NewPtr = OriginalLoad->getBasePtr();
10922 EVT PtrType = NewPtr.getValueType();
10923 MachinePointerInfo MPI;
10924 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10925 int Elt = ConstEltNo->getZExtValue();
10926 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10927 if (TLI.isBigEndian())
10928 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10929 Offset = DAG.getConstant(PtrOff, PtrType);
10930 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10932 Offset = DAG.getNode(
10933 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10934 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10935 if (TLI.isBigEndian())
10936 Offset = DAG.getNode(
10937 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10938 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10939 MPI = OriginalLoad->getPointerInfo();
10941 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10943 // The replacement we need to do here is a little tricky: we need to
10944 // replace an extractelement of a load with a load.
10945 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10946 // Note that this replacement assumes that the extractvalue is the only
10947 // use of the load; that's okay because we don't want to perform this
10948 // transformation in other cases anyway.
10951 if (ResultVT.bitsGT(VecEltVT)) {
10952 // If the result type of vextract is wider than the load, then issue an
10953 // extending load instead.
10954 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10958 Load = DAG.getExtLoad(
10959 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10960 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10961 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10962 Chain = Load.getValue(1);
10964 Load = DAG.getLoad(
10965 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10966 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10967 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10968 Chain = Load.getValue(1);
10969 if (ResultVT.bitsLT(VecEltVT))
10970 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10972 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10974 WorklistRemover DeadNodes(*this);
10975 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10976 SDValue To[] = { Load, Chain };
10977 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10978 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10979 // worklist explicitly as well.
10980 AddToWorklist(Load.getNode());
10981 AddUsersToWorklist(Load.getNode()); // Add users too
10982 // Make sure to revisit this node to clean it up; it will usually be dead.
10983 AddToWorklist(EVE);
10985 return SDValue(EVE, 0);
10988 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10989 // (vextract (scalar_to_vector val, 0) -> val
10990 SDValue InVec = N->getOperand(0);
10991 EVT VT = InVec.getValueType();
10992 EVT NVT = N->getValueType(0);
10994 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10995 // Check if the result type doesn't match the inserted element type. A
10996 // SCALAR_TO_VECTOR may truncate the inserted element and the
10997 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10998 SDValue InOp = InVec.getOperand(0);
10999 if (InOp.getValueType() != NVT) {
11000 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11001 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11006 SDValue EltNo = N->getOperand(1);
11007 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11009 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11010 // We only perform this optimization before the op legalization phase because
11011 // we may introduce new vector instructions which are not backed by TD
11012 // patterns. For example on AVX, extracting elements from a wide vector
11013 // without using extract_subvector. However, if we can find an underlying
11014 // scalar value, then we can always use that.
11015 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11017 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11018 int NumElem = VT.getVectorNumElements();
11019 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11020 // Find the new index to extract from.
11021 int OrigElt = SVOp->getMaskElt(Elt);
11023 // Extracting an undef index is undef.
11025 return DAG.getUNDEF(NVT);
11027 // Select the right vector half to extract from.
11029 if (OrigElt < NumElem) {
11030 SVInVec = InVec->getOperand(0);
11032 SVInVec = InVec->getOperand(1);
11033 OrigElt -= NumElem;
11036 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11037 SDValue InOp = SVInVec.getOperand(OrigElt);
11038 if (InOp.getValueType() != NVT) {
11039 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11040 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11046 // FIXME: We should handle recursing on other vector shuffles and
11047 // scalar_to_vector here as well.
11049 if (!LegalOperations) {
11050 EVT IndexTy = TLI.getVectorIdxTy();
11051 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11052 SVInVec, DAG.getConstant(OrigElt, IndexTy));
11056 bool BCNumEltsChanged = false;
11057 EVT ExtVT = VT.getVectorElementType();
11060 // If the result of load has to be truncated, then it's not necessarily
11062 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11065 if (InVec.getOpcode() == ISD::BITCAST) {
11066 // Don't duplicate a load with other uses.
11067 if (!InVec.hasOneUse())
11070 EVT BCVT = InVec.getOperand(0).getValueType();
11071 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11073 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11074 BCNumEltsChanged = true;
11075 InVec = InVec.getOperand(0);
11076 ExtVT = BCVT.getVectorElementType();
11079 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11080 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11081 ISD::isNormalLoad(InVec.getNode()) &&
11082 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11083 SDValue Index = N->getOperand(1);
11084 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11085 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11089 // Perform only after legalization to ensure build_vector / vector_shuffle
11090 // optimizations have already been done.
11091 if (!LegalOperations) return SDValue();
11093 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11094 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11095 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11098 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11100 LoadSDNode *LN0 = nullptr;
11101 const ShuffleVectorSDNode *SVN = nullptr;
11102 if (ISD::isNormalLoad(InVec.getNode())) {
11103 LN0 = cast<LoadSDNode>(InVec);
11104 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11105 InVec.getOperand(0).getValueType() == ExtVT &&
11106 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11107 // Don't duplicate a load with other uses.
11108 if (!InVec.hasOneUse())
11111 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11112 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11113 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11115 // (load $addr+1*size)
11117 // Don't duplicate a load with other uses.
11118 if (!InVec.hasOneUse())
11121 // If the bit convert changed the number of elements, it is unsafe
11122 // to examine the mask.
11123 if (BCNumEltsChanged)
11126 // Select the input vector, guarding against out of range extract vector.
11127 unsigned NumElems = VT.getVectorNumElements();
11128 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11129 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11131 if (InVec.getOpcode() == ISD::BITCAST) {
11132 // Don't duplicate a load with other uses.
11133 if (!InVec.hasOneUse())
11136 InVec = InVec.getOperand(0);
11138 if (ISD::isNormalLoad(InVec.getNode())) {
11139 LN0 = cast<LoadSDNode>(InVec);
11140 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11141 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
11145 // Make sure we found a non-volatile load and the extractelement is
11147 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11150 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11152 return DAG.getUNDEF(LVT);
11154 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11160 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11161 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11162 // We perform this optimization post type-legalization because
11163 // the type-legalizer often scalarizes integer-promoted vectors.
11164 // Performing this optimization before may create bit-casts which
11165 // will be type-legalized to complex code sequences.
11166 // We perform this optimization only before the operation legalizer because we
11167 // may introduce illegal operations.
11168 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11171 unsigned NumInScalars = N->getNumOperands();
11173 EVT VT = N->getValueType(0);
11175 // Check to see if this is a BUILD_VECTOR of a bunch of values
11176 // which come from any_extend or zero_extend nodes. If so, we can create
11177 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11178 // optimizations. We do not handle sign-extend because we can't fill the sign
11180 EVT SourceType = MVT::Other;
11181 bool AllAnyExt = true;
11183 for (unsigned i = 0; i != NumInScalars; ++i) {
11184 SDValue In = N->getOperand(i);
11185 // Ignore undef inputs.
11186 if (In.getOpcode() == ISD::UNDEF) continue;
11188 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11189 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11191 // Abort if the element is not an extension.
11192 if (!ZeroExt && !AnyExt) {
11193 SourceType = MVT::Other;
11197 // The input is a ZeroExt or AnyExt. Check the original type.
11198 EVT InTy = In.getOperand(0).getValueType();
11200 // Check that all of the widened source types are the same.
11201 if (SourceType == MVT::Other)
11204 else if (InTy != SourceType) {
11205 // Multiple income types. Abort.
11206 SourceType = MVT::Other;
11210 // Check if all of the extends are ANY_EXTENDs.
11211 AllAnyExt &= AnyExt;
11214 // In order to have valid types, all of the inputs must be extended from the
11215 // same source type and all of the inputs must be any or zero extend.
11216 // Scalar sizes must be a power of two.
11217 EVT OutScalarTy = VT.getScalarType();
11218 bool ValidTypes = SourceType != MVT::Other &&
11219 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11220 isPowerOf2_32(SourceType.getSizeInBits());
11222 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11223 // turn into a single shuffle instruction.
11227 bool isLE = TLI.isLittleEndian();
11228 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11229 assert(ElemRatio > 1 && "Invalid element size ratio");
11230 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11231 DAG.getConstant(0, SourceType);
11233 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11234 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11236 // Populate the new build_vector
11237 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11238 SDValue Cast = N->getOperand(i);
11239 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11240 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11241 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11243 if (Cast.getOpcode() == ISD::UNDEF)
11244 In = DAG.getUNDEF(SourceType);
11246 In = Cast->getOperand(0);
11247 unsigned Index = isLE ? (i * ElemRatio) :
11248 (i * ElemRatio + (ElemRatio - 1));
11250 assert(Index < Ops.size() && "Invalid index");
11254 // The type of the new BUILD_VECTOR node.
11255 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11256 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11257 "Invalid vector size");
11258 // Check if the new vector type is legal.
11259 if (!isTypeLegal(VecVT)) return SDValue();
11261 // Make the new BUILD_VECTOR.
11262 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11264 // The new BUILD_VECTOR node has the potential to be further optimized.
11265 AddToWorklist(BV.getNode());
11266 // Bitcast to the desired type.
11267 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11270 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11271 EVT VT = N->getValueType(0);
11273 unsigned NumInScalars = N->getNumOperands();
11276 EVT SrcVT = MVT::Other;
11277 unsigned Opcode = ISD::DELETED_NODE;
11278 unsigned NumDefs = 0;
11280 for (unsigned i = 0; i != NumInScalars; ++i) {
11281 SDValue In = N->getOperand(i);
11282 unsigned Opc = In.getOpcode();
11284 if (Opc == ISD::UNDEF)
11287 // If all scalar values are floats and converted from integers.
11288 if (Opcode == ISD::DELETED_NODE &&
11289 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11296 EVT InVT = In.getOperand(0).getValueType();
11298 // If all scalar values are typed differently, bail out. It's chosen to
11299 // simplify BUILD_VECTOR of integer types.
11300 if (SrcVT == MVT::Other)
11307 // If the vector has just one element defined, it's not worth to fold it into
11308 // a vectorized one.
11312 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11313 && "Should only handle conversion from integer to float.");
11314 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11316 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11318 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11321 // Just because the floating-point vector type is legal does not necessarily
11322 // mean that the corresponding integer vector type is.
11323 if (!isTypeLegal(NVT))
11326 SmallVector<SDValue, 8> Opnds;
11327 for (unsigned i = 0; i != NumInScalars; ++i) {
11328 SDValue In = N->getOperand(i);
11330 if (In.getOpcode() == ISD::UNDEF)
11331 Opnds.push_back(DAG.getUNDEF(SrcVT));
11333 Opnds.push_back(In.getOperand(0));
11335 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11336 AddToWorklist(BV.getNode());
11338 return DAG.getNode(Opcode, dl, VT, BV);
11341 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11342 unsigned NumInScalars = N->getNumOperands();
11344 EVT VT = N->getValueType(0);
11346 // A vector built entirely of undefs is undef.
11347 if (ISD::allOperandsUndef(N))
11348 return DAG.getUNDEF(VT);
11350 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11353 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11356 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11357 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11358 // at most two distinct vectors, turn this into a shuffle node.
11360 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11361 if (!isTypeLegal(VT))
11364 // May only combine to shuffle after legalize if shuffle is legal.
11365 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11368 SDValue VecIn1, VecIn2;
11369 bool UsesZeroVector = false;
11370 for (unsigned i = 0; i != NumInScalars; ++i) {
11371 SDValue Op = N->getOperand(i);
11372 // Ignore undef inputs.
11373 if (Op.getOpcode() == ISD::UNDEF) continue;
11375 // See if we can combine this build_vector into a blend with a zero vector.
11376 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11377 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11378 (Op.getOpcode() == ISD::ConstantFP &&
11379 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11380 UsesZeroVector = true;
11384 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11385 // constant index, bail out.
11386 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11387 !isa<ConstantSDNode>(Op.getOperand(1))) {
11388 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11392 // We allow up to two distinct input vectors.
11393 SDValue ExtractedFromVec = Op.getOperand(0);
11394 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11397 if (!VecIn1.getNode()) {
11398 VecIn1 = ExtractedFromVec;
11399 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11400 VecIn2 = ExtractedFromVec;
11402 // Too many inputs.
11403 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11408 // If everything is good, we can make a shuffle operation.
11409 if (VecIn1.getNode()) {
11410 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11411 SmallVector<int, 8> Mask;
11412 for (unsigned i = 0; i != NumInScalars; ++i) {
11413 unsigned Opcode = N->getOperand(i).getOpcode();
11414 if (Opcode == ISD::UNDEF) {
11415 Mask.push_back(-1);
11419 // Operands can also be zero.
11420 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11421 assert(UsesZeroVector &&
11422 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11423 "Unexpected node found!");
11424 Mask.push_back(NumInScalars+i);
11428 // If extracting from the first vector, just use the index directly.
11429 SDValue Extract = N->getOperand(i);
11430 SDValue ExtVal = Extract.getOperand(1);
11431 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11432 if (Extract.getOperand(0) == VecIn1) {
11433 Mask.push_back(ExtIndex);
11437 // Otherwise, use InIdx + InputVecSize
11438 Mask.push_back(InNumElements + ExtIndex);
11441 // Avoid introducing illegal shuffles with zero.
11442 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11445 // We can't generate a shuffle node with mismatched input and output types.
11446 // Attempt to transform a single input vector to the correct type.
11447 if ((VT != VecIn1.getValueType())) {
11448 // If the input vector type has a different base type to the output
11449 // vector type, bail out.
11450 EVT VTElemType = VT.getVectorElementType();
11451 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11452 (VecIn2.getNode() &&
11453 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11456 // If the input vector is too small, widen it.
11457 // We only support widening of vectors which are half the size of the
11458 // output registers. For example XMM->YMM widening on X86 with AVX.
11459 EVT VecInT = VecIn1.getValueType();
11460 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11461 // If we only have one small input, widen it by adding undef values.
11462 if (!VecIn2.getNode())
11463 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11464 DAG.getUNDEF(VecIn1.getValueType()));
11465 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11466 // If we have two small inputs of the same type, try to concat them.
11467 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11468 VecIn2 = SDValue(nullptr, 0);
11471 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11472 // If the input vector is too large, try to split it.
11473 // We don't support having two input vectors that are too large.
11474 // If the zero vector was used, we can not split the vector,
11475 // since we'd need 3 inputs.
11476 if (UsesZeroVector || VecIn2.getNode())
11479 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11482 // Try to replace VecIn1 with two extract_subvectors
11483 // No need to update the masks, they should still be correct.
11484 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11485 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11486 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11487 DAG.getConstant(0, TLI.getVectorIdxTy()));
11492 if (UsesZeroVector)
11493 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11494 DAG.getConstantFP(0.0, VT);
11496 // If VecIn2 is unused then change it to undef.
11497 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11499 // Check that we were able to transform all incoming values to the same
11501 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11502 VecIn1.getValueType() != VT)
11505 // Return the new VECTOR_SHUFFLE node.
11509 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11515 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11516 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11517 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11518 // inputs come from at most two distinct vectors, turn this into a shuffle
11521 // If we only have one input vector, we don't need to do any concatenation.
11522 if (N->getNumOperands() == 1)
11523 return N->getOperand(0);
11525 // Check if all of the operands are undefs.
11526 EVT VT = N->getValueType(0);
11527 if (ISD::allOperandsUndef(N))
11528 return DAG.getUNDEF(VT);
11530 // Optimize concat_vectors where one of the vectors is undef.
11531 if (N->getNumOperands() == 2 &&
11532 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11533 SDValue In = N->getOperand(0);
11534 assert(In.getValueType().isVector() && "Must concat vectors");
11536 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11537 if (In->getOpcode() == ISD::BITCAST &&
11538 !In->getOperand(0)->getValueType(0).isVector()) {
11539 SDValue Scalar = In->getOperand(0);
11540 EVT SclTy = Scalar->getValueType(0);
11542 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11545 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11546 VT.getSizeInBits() / SclTy.getSizeInBits());
11547 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11550 SDLoc dl = SDLoc(N);
11551 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11552 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11556 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11557 // We have already tested above for an UNDEF only concatenation.
11558 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11559 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11560 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11561 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11563 bool AllBuildVectorsOrUndefs =
11564 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11565 if (AllBuildVectorsOrUndefs) {
11566 SmallVector<SDValue, 8> Opnds;
11567 EVT SVT = VT.getScalarType();
11570 if (!SVT.isFloatingPoint()) {
11571 // If BUILD_VECTOR are from built from integer, they may have different
11572 // operand types. Get the smallest type and truncate all operands to it.
11573 bool FoundMinVT = false;
11574 for (const SDValue &Op : N->ops())
11575 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11576 EVT OpSVT = Op.getOperand(0)->getValueType(0);
11577 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11580 assert(FoundMinVT && "Concat vector type mismatch");
11583 for (const SDValue &Op : N->ops()) {
11584 EVT OpVT = Op.getValueType();
11585 unsigned NumElts = OpVT.getVectorNumElements();
11587 if (ISD::UNDEF == Op.getOpcode())
11588 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
11590 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11591 if (SVT.isFloatingPoint()) {
11592 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
11593 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
11595 for (unsigned i = 0; i != NumElts; ++i)
11597 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11602 assert(VT.getVectorNumElements() == Opnds.size() &&
11603 "Concat vector type mismatch");
11604 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11607 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11608 // nodes often generate nop CONCAT_VECTOR nodes.
11609 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11610 // place the incoming vectors at the exact same location.
11611 SDValue SingleSource = SDValue();
11612 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11614 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11615 SDValue Op = N->getOperand(i);
11617 if (Op.getOpcode() == ISD::UNDEF)
11620 // Check if this is the identity extract:
11621 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11624 // Find the single incoming vector for the extract_subvector.
11625 if (SingleSource.getNode()) {
11626 if (Op.getOperand(0) != SingleSource)
11629 SingleSource = Op.getOperand(0);
11631 // Check the source type is the same as the type of the result.
11632 // If not, this concat may extend the vector, so we can not
11633 // optimize it away.
11634 if (SingleSource.getValueType() != N->getValueType(0))
11638 unsigned IdentityIndex = i * PartNumElem;
11639 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11640 // The extract index must be constant.
11644 // Check that we are reading from the identity index.
11645 if (CS->getZExtValue() != IdentityIndex)
11649 if (SingleSource.getNode())
11650 return SingleSource;
11655 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11656 EVT NVT = N->getValueType(0);
11657 SDValue V = N->getOperand(0);
11659 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11661 // (extract_subvec (concat V1, V2, ...), i)
11664 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11666 if (V->getOperand(0).getValueType() != NVT)
11668 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11669 unsigned NumElems = NVT.getVectorNumElements();
11670 assert((Idx % NumElems) == 0 &&
11671 "IDX in concat is not a multiple of the result vector length.");
11672 return V->getOperand(Idx / NumElems);
11676 if (V->getOpcode() == ISD::BITCAST)
11677 V = V.getOperand(0);
11679 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11681 // Handle only simple case where vector being inserted and vector
11682 // being extracted are of same type, and are half size of larger vectors.
11683 EVT BigVT = V->getOperand(0).getValueType();
11684 EVT SmallVT = V->getOperand(1).getValueType();
11685 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11688 // Only handle cases where both indexes are constants with the same type.
11689 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11690 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11692 if (InsIdx && ExtIdx &&
11693 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11694 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11696 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11698 // indices are equal or bit offsets are equal => V1
11699 // otherwise => (extract_subvec V1, ExtIdx)
11700 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11701 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11702 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11703 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11704 DAG.getNode(ISD::BITCAST, dl,
11705 N->getOperand(0).getValueType(),
11706 V->getOperand(0)), N->getOperand(1));
11713 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11714 SDValue V, SelectionDAG &DAG) {
11716 EVT VT = V.getValueType();
11718 switch (V.getOpcode()) {
11722 case ISD::CONCAT_VECTORS: {
11723 EVT OpVT = V->getOperand(0).getValueType();
11724 int OpSize = OpVT.getVectorNumElements();
11725 SmallBitVector OpUsedElements(OpSize, false);
11726 bool FoundSimplification = false;
11727 SmallVector<SDValue, 4> NewOps;
11728 NewOps.reserve(V->getNumOperands());
11729 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11730 SDValue Op = V->getOperand(i);
11731 bool OpUsed = false;
11732 for (int j = 0; j < OpSize; ++j)
11733 if (UsedElements[i * OpSize + j]) {
11734 OpUsedElements[j] = true;
11738 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11739 : DAG.getUNDEF(OpVT));
11740 FoundSimplification |= Op == NewOps.back();
11741 OpUsedElements.reset();
11743 if (FoundSimplification)
11744 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11748 case ISD::INSERT_SUBVECTOR: {
11749 SDValue BaseV = V->getOperand(0);
11750 SDValue SubV = V->getOperand(1);
11751 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11755 int SubSize = SubV.getValueType().getVectorNumElements();
11756 int Idx = IdxN->getZExtValue();
11757 bool SubVectorUsed = false;
11758 SmallBitVector SubUsedElements(SubSize, false);
11759 for (int i = 0; i < SubSize; ++i)
11760 if (UsedElements[i + Idx]) {
11761 SubVectorUsed = true;
11762 SubUsedElements[i] = true;
11763 UsedElements[i + Idx] = false;
11766 // Now recurse on both the base and sub vectors.
11767 SDValue SimplifiedSubV =
11769 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11770 : DAG.getUNDEF(SubV.getValueType());
11771 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11772 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11773 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11774 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11780 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11781 SDValue N1, SelectionDAG &DAG) {
11782 EVT VT = SVN->getValueType(0);
11783 int NumElts = VT.getVectorNumElements();
11784 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11785 for (int M : SVN->getMask())
11786 if (M >= 0 && M < NumElts)
11787 N0UsedElements[M] = true;
11788 else if (M >= NumElts)
11789 N1UsedElements[M - NumElts] = true;
11791 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11792 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11793 if (S0 == N0 && S1 == N1)
11796 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11799 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11800 // or turn a shuffle of a single concat into simpler shuffle then concat.
11801 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11802 EVT VT = N->getValueType(0);
11803 unsigned NumElts = VT.getVectorNumElements();
11805 SDValue N0 = N->getOperand(0);
11806 SDValue N1 = N->getOperand(1);
11807 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11809 SmallVector<SDValue, 4> Ops;
11810 EVT ConcatVT = N0.getOperand(0).getValueType();
11811 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11812 unsigned NumConcats = NumElts / NumElemsPerConcat;
11814 // Special case: shuffle(concat(A,B)) can be more efficiently represented
11815 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11816 // half vector elements.
11817 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11818 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11819 SVN->getMask().end(), [](int i) { return i == -1; })) {
11820 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11821 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11822 N1 = DAG.getUNDEF(ConcatVT);
11823 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11826 // Look at every vector that's inserted. We're looking for exact
11827 // subvector-sized copies from a concatenated vector
11828 for (unsigned I = 0; I != NumConcats; ++I) {
11829 // Make sure we're dealing with a copy.
11830 unsigned Begin = I * NumElemsPerConcat;
11831 bool AllUndef = true, NoUndef = true;
11832 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11833 if (SVN->getMaskElt(J) >= 0)
11840 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11843 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11844 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11847 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11848 if (FirstElt < N0.getNumOperands())
11849 Ops.push_back(N0.getOperand(FirstElt));
11851 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11853 } else if (AllUndef) {
11854 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11855 } else { // Mixed with general masks and undefs, can't do optimization.
11860 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11863 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11864 EVT VT = N->getValueType(0);
11865 unsigned NumElts = VT.getVectorNumElements();
11867 SDValue N0 = N->getOperand(0);
11868 SDValue N1 = N->getOperand(1);
11870 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11872 // Canonicalize shuffle undef, undef -> undef
11873 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11874 return DAG.getUNDEF(VT);
11876 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11878 // Canonicalize shuffle v, v -> v, undef
11880 SmallVector<int, 8> NewMask;
11881 for (unsigned i = 0; i != NumElts; ++i) {
11882 int Idx = SVN->getMaskElt(i);
11883 if (Idx >= (int)NumElts) Idx -= NumElts;
11884 NewMask.push_back(Idx);
11886 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11890 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11891 if (N0.getOpcode() == ISD::UNDEF) {
11892 SmallVector<int, 8> NewMask;
11893 for (unsigned i = 0; i != NumElts; ++i) {
11894 int Idx = SVN->getMaskElt(i);
11896 if (Idx >= (int)NumElts)
11899 Idx = -1; // remove reference to lhs
11901 NewMask.push_back(Idx);
11903 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11907 // Remove references to rhs if it is undef
11908 if (N1.getOpcode() == ISD::UNDEF) {
11909 bool Changed = false;
11910 SmallVector<int, 8> NewMask;
11911 for (unsigned i = 0; i != NumElts; ++i) {
11912 int Idx = SVN->getMaskElt(i);
11913 if (Idx >= (int)NumElts) {
11917 NewMask.push_back(Idx);
11920 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11923 // If it is a splat, check if the argument vector is another splat or a
11925 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11926 SDNode *V = N0.getNode();
11928 // If this is a bit convert that changes the element type of the vector but
11929 // not the number of vector elements, look through it. Be careful not to
11930 // look though conversions that change things like v4f32 to v2f64.
11931 if (V->getOpcode() == ISD::BITCAST) {
11932 SDValue ConvInput = V->getOperand(0);
11933 if (ConvInput.getValueType().isVector() &&
11934 ConvInput.getValueType().getVectorNumElements() == NumElts)
11935 V = ConvInput.getNode();
11938 if (V->getOpcode() == ISD::BUILD_VECTOR) {
11939 assert(V->getNumOperands() == NumElts &&
11940 "BUILD_VECTOR has wrong number of operands");
11942 bool AllSame = true;
11943 for (unsigned i = 0; i != NumElts; ++i) {
11944 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11945 Base = V->getOperand(i);
11949 // Splat of <u, u, u, u>, return <u, u, u, u>
11950 if (!Base.getNode())
11952 for (unsigned i = 0; i != NumElts; ++i) {
11953 if (V->getOperand(i) != Base) {
11958 // Splat of <x, x, x, x>, return <x, x, x, x>
11962 // Canonicalize any other splat as a build_vector.
11963 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11964 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
11965 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11966 V->getValueType(0), Ops);
11968 // We may have jumped through bitcasts, so the type of the
11969 // BUILD_VECTOR may not match the type of the shuffle.
11970 if (V->getValueType(0) != VT)
11971 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11976 // There are various patterns used to build up a vector from smaller vectors,
11977 // subvectors, or elements. Scan chains of these and replace unused insertions
11978 // or components with undef.
11979 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11982 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11983 Level < AfterLegalizeVectorOps &&
11984 (N1.getOpcode() == ISD::UNDEF ||
11985 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11986 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11987 SDValue V = partitionShuffleOfConcats(N, DAG);
11993 // If this shuffle only has a single input that is a bitcasted shuffle,
11994 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
11995 // back to their original types.
11996 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
11997 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
11998 TLI.isTypeLegal(VT)) {
12000 // Peek through the bitcast only if there is one user.
12002 while (BC0.getOpcode() == ISD::BITCAST) {
12003 if (!BC0.hasOneUse())
12005 BC0 = BC0.getOperand(0);
12008 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12010 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12012 SmallVector<int, 8> NewMask;
12014 for (int s = 0; s != Scale; ++s)
12015 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12019 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12020 EVT SVT = VT.getScalarType();
12021 EVT InnerVT = BC0->getValueType(0);
12022 EVT InnerSVT = InnerVT.getScalarType();
12024 // Determine which shuffle works with the smaller scalar type.
12025 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12026 EVT ScaleSVT = ScaleVT.getScalarType();
12028 if (TLI.isTypeLegal(ScaleVT) &&
12029 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12030 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12032 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12033 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12035 // Scale the shuffle masks to the smaller scalar type.
12036 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12037 SmallVector<int, 8> InnerMask =
12038 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12039 SmallVector<int, 8> OuterMask =
12040 ScaleShuffleMask(SVN->getMask(), OuterScale);
12042 // Merge the shuffle masks.
12043 SmallVector<int, 8> NewMask;
12044 for (int M : OuterMask)
12045 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12047 // Test for shuffle mask legality over both commutations.
12048 SDValue SV0 = BC0->getOperand(0);
12049 SDValue SV1 = BC0->getOperand(1);
12050 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12052 std::swap(SV0, SV1);
12053 ShuffleVectorSDNode::commuteMask(NewMask);
12054 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12058 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12059 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12060 return DAG.getNode(
12061 ISD::BITCAST, SDLoc(N), VT,
12062 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12068 // Canonicalize shuffles according to rules:
12069 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12070 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12071 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12072 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12073 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12074 TLI.isTypeLegal(VT)) {
12075 // The incoming shuffle must be of the same type as the result of the
12076 // current shuffle.
12077 assert(N1->getOperand(0).getValueType() == VT &&
12078 "Shuffle types don't match");
12080 SDValue SV0 = N1->getOperand(0);
12081 SDValue SV1 = N1->getOperand(1);
12082 bool HasSameOp0 = N0 == SV0;
12083 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12084 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12085 // Commute the operands of this shuffle so that next rule
12087 return DAG.getCommutedVectorShuffle(*SVN);
12090 // Try to fold according to rules:
12091 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12092 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12093 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12094 // Don't try to fold shuffles with illegal type.
12095 // Only fold if this shuffle is the only user of the other shuffle.
12096 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12097 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12098 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12100 // The incoming shuffle must be of the same type as the result of the
12101 // current shuffle.
12102 assert(OtherSV->getOperand(0).getValueType() == VT &&
12103 "Shuffle types don't match");
12106 SmallVector<int, 4> Mask;
12107 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12108 // operand, and SV1 as the second operand.
12109 for (unsigned i = 0; i != NumElts; ++i) {
12110 int Idx = SVN->getMaskElt(i);
12112 // Propagate Undef.
12113 Mask.push_back(Idx);
12117 SDValue CurrentVec;
12118 if (Idx < (int)NumElts) {
12119 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12120 // shuffle mask to identify which vector is actually referenced.
12121 Idx = OtherSV->getMaskElt(Idx);
12123 // Propagate Undef.
12124 Mask.push_back(Idx);
12128 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12129 : OtherSV->getOperand(1);
12131 // This shuffle index references an element within N1.
12135 // Simple case where 'CurrentVec' is UNDEF.
12136 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12137 Mask.push_back(-1);
12141 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12142 // will be the first or second operand of the combined shuffle.
12143 Idx = Idx % NumElts;
12144 if (!SV0.getNode() || SV0 == CurrentVec) {
12145 // Ok. CurrentVec is the left hand side.
12146 // Update the mask accordingly.
12148 Mask.push_back(Idx);
12152 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12153 if (SV1.getNode() && SV1 != CurrentVec)
12156 // Ok. CurrentVec is the right hand side.
12157 // Update the mask accordingly.
12159 Mask.push_back(Idx + NumElts);
12162 // Check if all indices in Mask are Undef. In case, propagate Undef.
12163 bool isUndefMask = true;
12164 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12165 isUndefMask &= Mask[i] < 0;
12168 return DAG.getUNDEF(VT);
12170 if (!SV0.getNode())
12171 SV0 = DAG.getUNDEF(VT);
12172 if (!SV1.getNode())
12173 SV1 = DAG.getUNDEF(VT);
12175 // Avoid introducing shuffles with illegal mask.
12176 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12177 ShuffleVectorSDNode::commuteMask(Mask);
12179 if (!TLI.isShuffleMaskLegal(Mask, VT))
12182 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12183 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12184 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12185 std::swap(SV0, SV1);
12188 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12189 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12190 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12191 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12197 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12198 SDValue InVal = N->getOperand(0);
12199 EVT VT = N->getValueType(0);
12201 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12202 // with a VECTOR_SHUFFLE.
12203 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12204 SDValue InVec = InVal->getOperand(0);
12205 SDValue EltNo = InVal->getOperand(1);
12207 // FIXME: We could support implicit truncation if the shuffle can be
12208 // scaled to a smaller vector scalar type.
12209 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12210 if (C0 && VT == InVec.getValueType() &&
12211 VT.getScalarType() == InVal.getValueType()) {
12212 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12213 int Elt = C0->getZExtValue();
12216 if (TLI.isShuffleMaskLegal(NewMask, VT))
12217 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12225 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12226 SDValue N0 = N->getOperand(0);
12227 SDValue N2 = N->getOperand(2);
12229 // If the input vector is a concatenation, and the insert replaces
12230 // one of the halves, we can optimize into a single concat_vectors.
12231 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12232 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12233 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12234 EVT VT = N->getValueType(0);
12236 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12237 // (concat_vectors Z, Y)
12239 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12240 N->getOperand(1), N0.getOperand(1));
12242 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12243 // (concat_vectors X, Z)
12244 if (InsIdx == VT.getVectorNumElements()/2)
12245 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12246 N0.getOperand(0), N->getOperand(1));
12252 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12253 /// with the destination vector and a zero vector.
12254 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12255 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12256 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12257 EVT VT = N->getValueType(0);
12258 SDValue LHS = N->getOperand(0);
12259 SDValue RHS = N->getOperand(1);
12262 // Make sure we're not running after operation legalization where it
12263 // may have custom lowered the vector shuffles.
12264 if (LegalOperations)
12267 if (N->getOpcode() != ISD::AND)
12270 if (RHS.getOpcode() == ISD::BITCAST)
12271 RHS = RHS.getOperand(0);
12273 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12274 SmallVector<int, 8> Indices;
12275 unsigned NumElts = RHS.getNumOperands();
12277 for (unsigned i = 0; i != NumElts; ++i) {
12278 SDValue Elt = RHS.getOperand(i);
12279 if (!isa<ConstantSDNode>(Elt))
12282 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12283 Indices.push_back(i);
12284 else if (cast<ConstantSDNode>(Elt)->isNullValue())
12285 Indices.push_back(NumElts+i);
12290 // Let's see if the target supports this vector_shuffle.
12291 EVT RVT = RHS.getValueType();
12292 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12295 // Return the new VECTOR_SHUFFLE node.
12296 EVT EltVT = RVT.getVectorElementType();
12297 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12298 DAG.getConstant(0, EltVT));
12299 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12300 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12301 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12302 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12308 /// Visit a binary vector operation, like ADD.
12309 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12310 assert(N->getValueType(0).isVector() &&
12311 "SimplifyVBinOp only works on vectors!");
12313 SDValue LHS = N->getOperand(0);
12314 SDValue RHS = N->getOperand(1);
12316 if (SDValue Shuffle = XformToShuffleWithZero(N))
12319 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12321 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12322 RHS.getOpcode() == ISD::BUILD_VECTOR) {
12323 // Check if both vectors are constants. If not bail out.
12324 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12325 cast<BuildVectorSDNode>(RHS)->isConstant()))
12328 SmallVector<SDValue, 8> Ops;
12329 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12330 SDValue LHSOp = LHS.getOperand(i);
12331 SDValue RHSOp = RHS.getOperand(i);
12333 // Can't fold divide by zero.
12334 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12335 N->getOpcode() == ISD::FDIV) {
12336 if ((RHSOp.getOpcode() == ISD::Constant &&
12337 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12338 (RHSOp.getOpcode() == ISD::ConstantFP &&
12339 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12343 EVT VT = LHSOp.getValueType();
12344 EVT RVT = RHSOp.getValueType();
12346 // Integer BUILD_VECTOR operands may have types larger than the element
12347 // size (e.g., when the element type is not legal). Prior to type
12348 // legalization, the types may not match between the two BUILD_VECTORS.
12349 // Truncate one of the operands to make them match.
12350 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12351 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12353 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12357 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12359 if (FoldOp.getOpcode() != ISD::UNDEF &&
12360 FoldOp.getOpcode() != ISD::Constant &&
12361 FoldOp.getOpcode() != ISD::ConstantFP)
12363 Ops.push_back(FoldOp);
12364 AddToWorklist(FoldOp.getNode());
12367 if (Ops.size() == LHS.getNumOperands())
12368 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12371 // Type legalization might introduce new shuffles in the DAG.
12372 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12373 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12374 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12375 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12376 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12377 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12378 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12379 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12381 if (SVN0->getMask().equals(SVN1->getMask())) {
12382 EVT VT = N->getValueType(0);
12383 SDValue UndefVector = LHS.getOperand(1);
12384 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12385 LHS.getOperand(0), RHS.getOperand(0));
12386 AddUsersToWorklist(N);
12387 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12388 &SVN0->getMask()[0]);
12395 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12396 SDValue N1, SDValue N2){
12397 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12399 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12400 cast<CondCodeSDNode>(N0.getOperand(2))->get());
12402 // If we got a simplified select_cc node back from SimplifySelectCC, then
12403 // break it down into a new SETCC node, and a new SELECT node, and then return
12404 // the SELECT node, since we were called with a SELECT node.
12405 if (SCC.getNode()) {
12406 // Check to see if we got a select_cc back (to turn into setcc/select).
12407 // Otherwise, just return whatever node we got back, like fabs.
12408 if (SCC.getOpcode() == ISD::SELECT_CC) {
12409 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12411 SCC.getOperand(0), SCC.getOperand(1),
12412 SCC.getOperand(4));
12413 AddToWorklist(SETCC.getNode());
12414 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12415 SCC.getOperand(2), SCC.getOperand(3));
12423 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12424 /// being selected between, see if we can simplify the select. Callers of this
12425 /// should assume that TheSelect is deleted if this returns true. As such, they
12426 /// should return the appropriate thing (e.g. the node) back to the top-level of
12427 /// the DAG combiner loop to avoid it being looked at.
12428 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12431 // Cannot simplify select with vector condition
12432 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12434 // If this is a select from two identical things, try to pull the operation
12435 // through the select.
12436 if (LHS.getOpcode() != RHS.getOpcode() ||
12437 !LHS.hasOneUse() || !RHS.hasOneUse())
12440 // If this is a load and the token chain is identical, replace the select
12441 // of two loads with a load through a select of the address to load from.
12442 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12443 // constants have been dropped into the constant pool.
12444 if (LHS.getOpcode() == ISD::LOAD) {
12445 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12446 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12448 // Token chains must be identical.
12449 if (LHS.getOperand(0) != RHS.getOperand(0) ||
12450 // Do not let this transformation reduce the number of volatile loads.
12451 LLD->isVolatile() || RLD->isVolatile() ||
12452 // If this is an EXTLOAD, the VT's must match.
12453 LLD->getMemoryVT() != RLD->getMemoryVT() ||
12454 // If this is an EXTLOAD, the kind of extension must match.
12455 (LLD->getExtensionType() != RLD->getExtensionType() &&
12456 // The only exception is if one of the extensions is anyext.
12457 LLD->getExtensionType() != ISD::EXTLOAD &&
12458 RLD->getExtensionType() != ISD::EXTLOAD) ||
12459 // FIXME: this discards src value information. This is
12460 // over-conservative. It would be beneficial to be able to remember
12461 // both potential memory locations. Since we are discarding
12462 // src value info, don't do the transformation if the memory
12463 // locations are not in the default address space.
12464 LLD->getPointerInfo().getAddrSpace() != 0 ||
12465 RLD->getPointerInfo().getAddrSpace() != 0 ||
12466 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12467 LLD->getBasePtr().getValueType()))
12470 // Check that the select condition doesn't reach either load. If so,
12471 // folding this will induce a cycle into the DAG. If not, this is safe to
12472 // xform, so create a select of the addresses.
12474 if (TheSelect->getOpcode() == ISD::SELECT) {
12475 SDNode *CondNode = TheSelect->getOperand(0).getNode();
12476 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12477 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12479 // The loads must not depend on one another.
12480 if (LLD->isPredecessorOf(RLD) ||
12481 RLD->isPredecessorOf(LLD))
12483 Addr = DAG.getSelect(SDLoc(TheSelect),
12484 LLD->getBasePtr().getValueType(),
12485 TheSelect->getOperand(0), LLD->getBasePtr(),
12486 RLD->getBasePtr());
12487 } else { // Otherwise SELECT_CC
12488 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12489 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12491 if ((LLD->hasAnyUseOfValue(1) &&
12492 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12493 (RLD->hasAnyUseOfValue(1) &&
12494 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12497 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12498 LLD->getBasePtr().getValueType(),
12499 TheSelect->getOperand(0),
12500 TheSelect->getOperand(1),
12501 LLD->getBasePtr(), RLD->getBasePtr(),
12502 TheSelect->getOperand(4));
12506 // It is safe to replace the two loads if they have different alignments,
12507 // but the new load must be the minimum (most restrictive) alignment of the
12509 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12510 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12511 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12512 Load = DAG.getLoad(TheSelect->getValueType(0),
12514 // FIXME: Discards pointer and AA info.
12515 LLD->getChain(), Addr, MachinePointerInfo(),
12516 LLD->isVolatile(), LLD->isNonTemporal(),
12517 isInvariant, Alignment);
12519 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12520 RLD->getExtensionType() : LLD->getExtensionType(),
12522 TheSelect->getValueType(0),
12523 // FIXME: Discards pointer and AA info.
12524 LLD->getChain(), Addr, MachinePointerInfo(),
12525 LLD->getMemoryVT(), LLD->isVolatile(),
12526 LLD->isNonTemporal(), isInvariant, Alignment);
12529 // Users of the select now use the result of the load.
12530 CombineTo(TheSelect, Load);
12532 // Users of the old loads now use the new load's chain. We know the
12533 // old-load value is dead now.
12534 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12535 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12542 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12543 /// where 'cond' is the comparison specified by CC.
12544 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12545 SDValue N2, SDValue N3,
12546 ISD::CondCode CC, bool NotExtCompare) {
12547 // (x ? y : y) -> y.
12548 if (N2 == N3) return N2;
12550 EVT VT = N2.getValueType();
12551 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12552 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12553 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12555 // Determine if the condition we're dealing with is constant
12556 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12557 N0, N1, CC, DL, false);
12558 if (SCC.getNode()) AddToWorklist(SCC.getNode());
12559 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12561 // fold select_cc true, x, y -> x
12562 if (SCCC && !SCCC->isNullValue())
12564 // fold select_cc false, x, y -> y
12565 if (SCCC && SCCC->isNullValue())
12568 // Check to see if we can simplify the select into an fabs node
12569 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12570 // Allow either -0.0 or 0.0
12571 if (CFP->getValueAPF().isZero()) {
12572 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12573 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12574 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12575 N2 == N3.getOperand(0))
12576 return DAG.getNode(ISD::FABS, DL, VT, N0);
12578 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12579 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12580 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12581 N2.getOperand(0) == N3)
12582 return DAG.getNode(ISD::FABS, DL, VT, N3);
12586 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12587 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12588 // in it. This is a win when the constant is not otherwise available because
12589 // it replaces two constant pool loads with one. We only do this if the FP
12590 // type is known to be legal, because if it isn't, then we are before legalize
12591 // types an we want the other legalization to happen first (e.g. to avoid
12592 // messing with soft float) and if the ConstantFP is not legal, because if
12593 // it is legal, we may not need to store the FP constant in a constant pool.
12594 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12595 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12596 if (TLI.isTypeLegal(N2.getValueType()) &&
12597 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12598 TargetLowering::Legal &&
12599 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12600 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12601 // If both constants have multiple uses, then we won't need to do an
12602 // extra load, they are likely around in registers for other users.
12603 (TV->hasOneUse() || FV->hasOneUse())) {
12604 Constant *Elts[] = {
12605 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12606 const_cast<ConstantFP*>(TV->getConstantFPValue())
12608 Type *FPTy = Elts[0]->getType();
12609 const DataLayout &TD = *TLI.getDataLayout();
12611 // Create a ConstantArray of the two constants.
12612 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12613 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12614 TD.getPrefTypeAlignment(FPTy));
12615 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12617 // Get the offsets to the 0 and 1 element of the array so that we can
12618 // select between them.
12619 SDValue Zero = DAG.getIntPtrConstant(0);
12620 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12621 SDValue One = DAG.getIntPtrConstant(EltSize);
12623 SDValue Cond = DAG.getSetCC(DL,
12624 getSetCCResultType(N0.getValueType()),
12626 AddToWorklist(Cond.getNode());
12627 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12629 AddToWorklist(CstOffset.getNode());
12630 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12632 AddToWorklist(CPIdx.getNode());
12633 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12634 MachinePointerInfo::getConstantPool(), false,
12635 false, false, Alignment);
12640 // Check to see if we can perform the "gzip trick", transforming
12641 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12642 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12643 (N1C->isNullValue() || // (a < 0) ? b : 0
12644 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
12645 EVT XType = N0.getValueType();
12646 EVT AType = N2.getValueType();
12647 if (XType.bitsGE(AType)) {
12648 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12649 // single-bit constant.
12650 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12651 unsigned ShCtV = N2C->getAPIntValue().logBase2();
12652 ShCtV = XType.getSizeInBits()-ShCtV-1;
12653 SDValue ShCt = DAG.getConstant(ShCtV,
12654 getShiftAmountTy(N0.getValueType()));
12655 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12657 AddToWorklist(Shift.getNode());
12659 if (XType.bitsGT(AType)) {
12660 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12661 AddToWorklist(Shift.getNode());
12664 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12667 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12669 DAG.getConstant(XType.getSizeInBits()-1,
12670 getShiftAmountTy(N0.getValueType())));
12671 AddToWorklist(Shift.getNode());
12673 if (XType.bitsGT(AType)) {
12674 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12675 AddToWorklist(Shift.getNode());
12678 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12682 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12683 // where y is has a single bit set.
12684 // A plaintext description would be, we can turn the SELECT_CC into an AND
12685 // when the condition can be materialized as an all-ones register. Any
12686 // single bit-test can be materialized as an all-ones register with
12687 // shift-left and shift-right-arith.
12688 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12689 N0->getValueType(0) == VT &&
12690 N1C && N1C->isNullValue() &&
12691 N2C && N2C->isNullValue()) {
12692 SDValue AndLHS = N0->getOperand(0);
12693 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12694 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12695 // Shift the tested bit over the sign bit.
12696 APInt AndMask = ConstAndRHS->getAPIntValue();
12698 DAG.getConstant(AndMask.countLeadingZeros(),
12699 getShiftAmountTy(AndLHS.getValueType()));
12700 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12702 // Now arithmetic right shift it all the way over, so the result is either
12703 // all-ones, or zero.
12705 DAG.getConstant(AndMask.getBitWidth()-1,
12706 getShiftAmountTy(Shl.getValueType()));
12707 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12709 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12713 // fold select C, 16, 0 -> shl C, 4
12714 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12715 TLI.getBooleanContents(N0.getValueType()) ==
12716 TargetLowering::ZeroOrOneBooleanContent) {
12718 // If the caller doesn't want us to simplify this into a zext of a compare,
12720 if (NotExtCompare && N2C->getAPIntValue() == 1)
12723 // Get a SetCC of the condition
12724 // NOTE: Don't create a SETCC if it's not legal on this target.
12725 if (!LegalOperations ||
12726 TLI.isOperationLegal(ISD::SETCC,
12727 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12729 // cast from setcc result type to select result type
12731 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12733 if (N2.getValueType().bitsLT(SCC.getValueType()))
12734 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12735 N2.getValueType());
12737 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12738 N2.getValueType(), SCC);
12740 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12741 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12742 N2.getValueType(), SCC);
12745 AddToWorklist(SCC.getNode());
12746 AddToWorklist(Temp.getNode());
12748 if (N2C->getAPIntValue() == 1)
12751 // shl setcc result by log2 n2c
12752 return DAG.getNode(
12753 ISD::SHL, DL, N2.getValueType(), Temp,
12754 DAG.getConstant(N2C->getAPIntValue().logBase2(),
12755 getShiftAmountTy(Temp.getValueType())));
12759 // Check to see if this is the equivalent of setcc
12760 // FIXME: Turn all of these into setcc if setcc if setcc is legal
12761 // otherwise, go ahead with the folds.
12762 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12763 EVT XType = N0.getValueType();
12764 if (!LegalOperations ||
12765 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12766 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12767 if (Res.getValueType() != VT)
12768 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12772 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12773 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12774 (!LegalOperations ||
12775 TLI.isOperationLegal(ISD::CTLZ, XType))) {
12776 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12777 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12778 DAG.getConstant(Log2_32(XType.getSizeInBits()),
12779 getShiftAmountTy(Ctlz.getValueType())));
12781 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12782 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12783 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12784 XType, DAG.getConstant(0, XType), N0);
12785 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12786 return DAG.getNode(ISD::SRL, DL, XType,
12787 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12788 DAG.getConstant(XType.getSizeInBits()-1,
12789 getShiftAmountTy(XType)));
12791 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12792 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12793 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12794 DAG.getConstant(XType.getSizeInBits()-1,
12795 getShiftAmountTy(N0.getValueType())));
12796 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12800 // Check to see if this is an integer abs.
12801 // select_cc setg[te] X, 0, X, -X ->
12802 // select_cc setgt X, -1, X, -X ->
12803 // select_cc setl[te] X, 0, -X, X ->
12804 // select_cc setlt X, 1, -X, X ->
12805 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12807 ConstantSDNode *SubC = nullptr;
12808 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12809 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12810 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12811 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12812 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12813 (N1C->isOne() && CC == ISD::SETLT)) &&
12814 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12815 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12817 EVT XType = N0.getValueType();
12818 if (SubC && SubC->isNullValue() && XType.isInteger()) {
12819 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12821 DAG.getConstant(XType.getSizeInBits()-1,
12822 getShiftAmountTy(N0.getValueType())));
12823 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12825 AddToWorklist(Shift.getNode());
12826 AddToWorklist(Add.getNode());
12827 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12834 /// This is a stub for TargetLowering::SimplifySetCC.
12835 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12836 SDValue N1, ISD::CondCode Cond,
12837 SDLoc DL, bool foldBooleans) {
12838 TargetLowering::DAGCombinerInfo
12839 DagCombineInfo(DAG, Level, false, this);
12840 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12843 /// Given an ISD::SDIV node expressing a divide by constant, return
12844 /// a DAG expression to select that will generate the same value by multiplying
12845 /// by a magic number.
12846 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12847 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12848 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12852 // Avoid division by zero.
12853 if (!C->getAPIntValue())
12856 std::vector<SDNode*> Built;
12858 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12860 for (SDNode *N : Built)
12865 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12866 /// DAG expression that will generate the same value by right shifting.
12867 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12868 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12872 // Avoid division by zero.
12873 if (!C->getAPIntValue())
12876 std::vector<SDNode *> Built;
12877 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12879 for (SDNode *N : Built)
12884 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12885 /// expression that will generate the same value by multiplying by a magic
12887 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12888 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12889 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12893 // Avoid division by zero.
12894 if (!C->getAPIntValue())
12897 std::vector<SDNode*> Built;
12899 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12901 for (SDNode *N : Built)
12906 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12907 if (Level >= AfterLegalizeDAG)
12910 // Expose the DAG combiner to the target combiner implementations.
12911 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12913 unsigned Iterations = 0;
12914 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12916 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12917 // For the reciprocal, we need to find the zero of the function:
12918 // F(X) = A X - 1 [which has a zero at X = 1/A]
12920 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12921 // does not require additional intermediate precision]
12922 EVT VT = Op.getValueType();
12924 SDValue FPOne = DAG.getConstantFP(1.0, VT);
12926 AddToWorklist(Est.getNode());
12928 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12929 for (unsigned i = 0; i < Iterations; ++i) {
12930 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12931 AddToWorklist(NewEst.getNode());
12933 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12934 AddToWorklist(NewEst.getNode());
12936 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12937 AddToWorklist(NewEst.getNode());
12939 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12940 AddToWorklist(Est.getNode());
12949 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12950 /// For the reciprocal sqrt, we need to find the zero of the function:
12951 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12953 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12954 /// As a result, we precompute A/2 prior to the iteration loop.
12955 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12956 unsigned Iterations) {
12957 EVT VT = Arg.getValueType();
12959 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12961 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12962 // this entire sequence requires only one FP constant.
12963 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12964 AddToWorklist(HalfArg.getNode());
12966 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12967 AddToWorklist(HalfArg.getNode());
12969 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12970 for (unsigned i = 0; i < Iterations; ++i) {
12971 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12972 AddToWorklist(NewEst.getNode());
12974 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12975 AddToWorklist(NewEst.getNode());
12977 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12978 AddToWorklist(NewEst.getNode());
12980 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12981 AddToWorklist(Est.getNode());
12986 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12987 /// For the reciprocal sqrt, we need to find the zero of the function:
12988 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12990 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12991 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12992 unsigned Iterations) {
12993 EVT VT = Arg.getValueType();
12995 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12996 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12998 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12999 for (unsigned i = 0; i < Iterations; ++i) {
13000 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13001 AddToWorklist(HalfEst.getNode());
13003 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13004 AddToWorklist(Est.getNode());
13006 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13007 AddToWorklist(Est.getNode());
13009 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13010 AddToWorklist(Est.getNode());
13012 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13013 AddToWorklist(Est.getNode());
13018 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13019 if (Level >= AfterLegalizeDAG)
13022 // Expose the DAG combiner to the target combiner implementations.
13023 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13024 unsigned Iterations = 0;
13025 bool UseOneConstNR = false;
13026 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13027 AddToWorklist(Est.getNode());
13029 Est = UseOneConstNR ?
13030 BuildRsqrtNROneConst(Op, Est, Iterations) :
13031 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13039 /// Return true if base is a frame index, which is known not to alias with
13040 /// anything but itself. Provides base object and offset as results.
13041 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13042 const GlobalValue *&GV, const void *&CV) {
13043 // Assume it is a primitive operation.
13044 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13046 // If it's an adding a simple constant then integrate the offset.
13047 if (Base.getOpcode() == ISD::ADD) {
13048 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13049 Base = Base.getOperand(0);
13050 Offset += C->getZExtValue();
13054 // Return the underlying GlobalValue, and update the Offset. Return false
13055 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13056 // by multiple nodes with different offsets.
13057 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13058 GV = G->getGlobal();
13059 Offset += G->getOffset();
13063 // Return the underlying Constant value, and update the Offset. Return false
13064 // for ConstantSDNodes since the same constant pool entry may be represented
13065 // by multiple nodes with different offsets.
13066 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13067 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13068 : (const void *)C->getConstVal();
13069 Offset += C->getOffset();
13072 // If it's any of the following then it can't alias with anything but itself.
13073 return isa<FrameIndexSDNode>(Base);
13076 /// Return true if there is any possibility that the two addresses overlap.
13077 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13078 // If they are the same then they must be aliases.
13079 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13081 // If they are both volatile then they cannot be reordered.
13082 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13084 // Gather base node and offset information.
13085 SDValue Base1, Base2;
13086 int64_t Offset1, Offset2;
13087 const GlobalValue *GV1, *GV2;
13088 const void *CV1, *CV2;
13089 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13090 Base1, Offset1, GV1, CV1);
13091 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13092 Base2, Offset2, GV2, CV2);
13094 // If they have a same base address then check to see if they overlap.
13095 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13096 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13097 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13099 // It is possible for different frame indices to alias each other, mostly
13100 // when tail call optimization reuses return address slots for arguments.
13101 // To catch this case, look up the actual index of frame indices to compute
13102 // the real alias relationship.
13103 if (isFrameIndex1 && isFrameIndex2) {
13104 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13105 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13106 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13107 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13108 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13111 // Otherwise, if we know what the bases are, and they aren't identical, then
13112 // we know they cannot alias.
13113 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13116 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13117 // compared to the size and offset of the access, we may be able to prove they
13118 // do not alias. This check is conservative for now to catch cases created by
13119 // splitting vector types.
13120 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13121 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13122 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13123 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13124 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13125 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13126 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13128 // There is no overlap between these relatively aligned accesses of similar
13129 // size, return no alias.
13130 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13131 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13135 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13137 : DAG.getSubtarget().useAA();
13139 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13140 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13144 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13145 // Use alias analysis information.
13146 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13147 Op1->getSrcValueOffset());
13148 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13149 Op0->getSrcValueOffset() - MinOffset;
13150 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13151 Op1->getSrcValueOffset() - MinOffset;
13152 AliasAnalysis::AliasResult AAResult =
13153 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13155 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13156 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13158 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13159 if (AAResult == AliasAnalysis::NoAlias)
13163 // Otherwise we have to assume they alias.
13167 /// Walk up chain skipping non-aliasing memory nodes,
13168 /// looking for aliasing nodes and adding them to the Aliases vector.
13169 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13170 SmallVectorImpl<SDValue> &Aliases) {
13171 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13172 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13174 // Get alias information for node.
13175 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13178 Chains.push_back(OriginalChain);
13179 unsigned Depth = 0;
13181 // Look at each chain and determine if it is an alias. If so, add it to the
13182 // aliases list. If not, then continue up the chain looking for the next
13184 while (!Chains.empty()) {
13185 SDValue Chain = Chains.back();
13188 // For TokenFactor nodes, look at each operand and only continue up the
13189 // chain until we find two aliases. If we've seen two aliases, assume we'll
13190 // find more and revert to original chain since the xform is unlikely to be
13193 // FIXME: The depth check could be made to return the last non-aliasing
13194 // chain we found before we hit a tokenfactor rather than the original
13196 if (Depth > 6 || Aliases.size() == 2) {
13198 Aliases.push_back(OriginalChain);
13202 // Don't bother if we've been before.
13203 if (!Visited.insert(Chain.getNode()).second)
13206 switch (Chain.getOpcode()) {
13207 case ISD::EntryToken:
13208 // Entry token is ideal chain operand, but handled in FindBetterChain.
13213 // Get alias information for Chain.
13214 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13215 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13217 // If chain is alias then stop here.
13218 if (!(IsLoad && IsOpLoad) &&
13219 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13220 Aliases.push_back(Chain);
13222 // Look further up the chain.
13223 Chains.push_back(Chain.getOperand(0));
13229 case ISD::TokenFactor:
13230 // We have to check each of the operands of the token factor for "small"
13231 // token factors, so we queue them up. Adding the operands to the queue
13232 // (stack) in reverse order maintains the original order and increases the
13233 // likelihood that getNode will find a matching token factor (CSE.)
13234 if (Chain.getNumOperands() > 16) {
13235 Aliases.push_back(Chain);
13238 for (unsigned n = Chain.getNumOperands(); n;)
13239 Chains.push_back(Chain.getOperand(--n));
13244 // For all other instructions we will just have to take what we can get.
13245 Aliases.push_back(Chain);
13250 // We need to be careful here to also search for aliases through the
13251 // value operand of a store, etc. Consider the following situation:
13253 // L1 = load Token1, %52
13254 // S1 = store Token1, L1, %51
13255 // L2 = load Token1, %52+8
13256 // S2 = store Token1, L2, %51+8
13257 // Token2 = Token(S1, S2)
13258 // L3 = load Token2, %53
13259 // S3 = store Token2, L3, %52
13260 // L4 = load Token2, %53+8
13261 // S4 = store Token2, L4, %52+8
13262 // If we search for aliases of S3 (which loads address %52), and we look
13263 // only through the chain, then we'll miss the trivial dependence on L1
13264 // (which also loads from %52). We then might change all loads and
13265 // stores to use Token1 as their chain operand, which could result in
13266 // copying %53 into %52 before copying %52 into %51 (which should
13269 // The problem is, however, that searching for such data dependencies
13270 // can become expensive, and the cost is not directly related to the
13271 // chain depth. Instead, we'll rule out such configurations here by
13272 // insisting that we've visited all chain users (except for users
13273 // of the original chain, which is not necessary). When doing this,
13274 // we need to look through nodes we don't care about (otherwise, things
13275 // like register copies will interfere with trivial cases).
13277 SmallVector<const SDNode *, 16> Worklist;
13278 for (const SDNode *N : Visited)
13279 if (N != OriginalChain.getNode())
13280 Worklist.push_back(N);
13282 while (!Worklist.empty()) {
13283 const SDNode *M = Worklist.pop_back_val();
13285 // We have already visited M, and want to make sure we've visited any uses
13286 // of M that we care about. For uses that we've not visisted, and don't
13287 // care about, queue them to the worklist.
13289 for (SDNode::use_iterator UI = M->use_begin(),
13290 UIE = M->use_end(); UI != UIE; ++UI)
13291 if (UI.getUse().getValueType() == MVT::Other &&
13292 Visited.insert(*UI).second) {
13293 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13294 // We've not visited this use, and we care about it (it could have an
13295 // ordering dependency with the original node).
13297 Aliases.push_back(OriginalChain);
13301 // We've not visited this use, but we don't care about it. Mark it as
13302 // visited and enqueue it to the worklist.
13303 Worklist.push_back(*UI);
13308 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13309 /// (aliasing node.)
13310 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13311 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
13313 // Accumulate all the aliases to this node.
13314 GatherAllAliases(N, OldChain, Aliases);
13316 // If no operands then chain to entry token.
13317 if (Aliases.size() == 0)
13318 return DAG.getEntryNode();
13320 // If a single operand then chain to it. We don't need to revisit it.
13321 if (Aliases.size() == 1)
13324 // Construct a custom tailored token factor.
13325 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13328 /// This is the entry point for the file.
13329 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13330 CodeGenOpt::Level OptLevel) {
13331 /// This is the main entry point to this class.
13332 DAGCombiner(*this, AA, OptLevel).Run(Level);