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/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SetVector.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 visitOR(SDNode *N);
250 SDValue visitXOR(SDNode *N);
251 SDValue SimplifyVBinOp(SDNode *N);
252 SDValue SimplifyVUnaryOp(SDNode *N);
253 SDValue visitSHL(SDNode *N);
254 SDValue visitSRA(SDNode *N);
255 SDValue visitSRL(SDNode *N);
256 SDValue visitRotate(SDNode *N);
257 SDValue visitCTLZ(SDNode *N);
258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259 SDValue visitCTTZ(SDNode *N);
260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTPOP(SDNode *N);
262 SDValue visitSELECT(SDNode *N);
263 SDValue visitVSELECT(SDNode *N);
264 SDValue visitSELECT_CC(SDNode *N);
265 SDValue visitSETCC(SDNode *N);
266 SDValue visitSIGN_EXTEND(SDNode *N);
267 SDValue visitZERO_EXTEND(SDNode *N);
268 SDValue visitANY_EXTEND(SDNode *N);
269 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270 SDValue visitTRUNCATE(SDNode *N);
271 SDValue visitBITCAST(SDNode *N);
272 SDValue visitBUILD_PAIR(SDNode *N);
273 SDValue visitFADD(SDNode *N);
274 SDValue visitFSUB(SDNode *N);
275 SDValue visitFMUL(SDNode *N);
276 SDValue visitFMA(SDNode *N);
277 SDValue visitFDIV(SDNode *N);
278 SDValue visitFREM(SDNode *N);
279 SDValue visitFSQRT(SDNode *N);
280 SDValue visitFCOPYSIGN(SDNode *N);
281 SDValue visitSINT_TO_FP(SDNode *N);
282 SDValue visitUINT_TO_FP(SDNode *N);
283 SDValue visitFP_TO_SINT(SDNode *N);
284 SDValue visitFP_TO_UINT(SDNode *N);
285 SDValue visitFP_ROUND(SDNode *N);
286 SDValue visitFP_ROUND_INREG(SDNode *N);
287 SDValue visitFP_EXTEND(SDNode *N);
288 SDValue visitFNEG(SDNode *N);
289 SDValue visitFABS(SDNode *N);
290 SDValue visitFCEIL(SDNode *N);
291 SDValue visitFTRUNC(SDNode *N);
292 SDValue visitFFLOOR(SDNode *N);
293 SDValue visitFMINNUM(SDNode *N);
294 SDValue visitFMAXNUM(SDNode *N);
295 SDValue visitBRCOND(SDNode *N);
296 SDValue visitBR_CC(SDNode *N);
297 SDValue visitLOAD(SDNode *N);
298 SDValue visitSTORE(SDNode *N);
299 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301 SDValue visitBUILD_VECTOR(SDNode *N);
302 SDValue visitCONCAT_VECTORS(SDNode *N);
303 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304 SDValue visitVECTOR_SHUFFLE(SDNode *N);
305 SDValue visitINSERT_SUBVECTOR(SDNode *N);
306 SDValue visitMLOAD(SDNode *N);
307 SDValue visitMSTORE(SDNode *N);
309 SDValue XformToShuffleWithZero(SDNode *N);
310 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
312 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
314 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
315 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
316 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
317 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
318 SDValue N3, ISD::CondCode CC,
319 bool NotExtCompare = false);
320 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
321 SDLoc DL, bool foldBooleans = true);
323 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
325 bool isOneUseSetCC(SDValue N) const;
327 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
329 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
330 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
331 SDValue BuildSDIV(SDNode *N);
332 SDValue BuildSDIVPow2(SDNode *N);
333 SDValue BuildUDIV(SDNode *N);
334 SDValue BuildReciprocalEstimate(SDValue Op);
335 SDValue BuildRsqrtEstimate(SDValue Op);
336 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
337 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
338 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
339 bool DemandHighBits = true);
340 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
341 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
342 SDValue InnerPos, SDValue InnerNeg,
343 unsigned PosOpcode, unsigned NegOpcode,
345 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
346 SDValue ReduceLoadWidth(SDNode *N);
347 SDValue ReduceLoadOpStoreWidth(SDNode *N);
348 SDValue TransformFPLoadStorePair(SDNode *N);
349 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
350 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
352 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
354 /// Walk up chain skipping non-aliasing memory nodes,
355 /// looking for aliasing nodes and adding them to the Aliases vector.
356 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
357 SmallVectorImpl<SDValue> &Aliases);
359 /// Return true if there is any possibility that the two addresses overlap.
360 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
362 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
363 /// chain (aliasing node.)
364 SDValue FindBetterChain(SDNode *N, SDValue Chain);
366 /// Merge consecutive store operations into a wide store.
367 /// This optimization uses wide integers or vectors when possible.
368 /// \return True if some memory operations were changed.
369 bool MergeConsecutiveStores(StoreSDNode *N);
371 /// \brief Try to transform a truncation where C is a constant:
372 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
374 /// \p N needs to be a truncation and its first operand an AND. Other
375 /// requirements are checked by the function (e.g. that trunc is
376 /// single-use) and if missed an empty SDValue is returned.
377 SDValue distributeTruncateThroughAnd(SDNode *N);
380 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
381 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
382 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
383 AttributeSet FnAttrs =
384 DAG.getMachineFunction().getFunction()->getAttributes();
386 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
387 Attribute::OptimizeForSize) ||
388 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
391 /// Runs the dag combiner on all nodes in the work list
392 void Run(CombineLevel AtLevel);
394 SelectionDAG &getDAG() const { return DAG; }
396 /// Returns a type large enough to hold any valid shift amount - before type
397 /// legalization these can be huge.
398 EVT getShiftAmountTy(EVT LHSTy) {
399 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
400 if (LHSTy.isVector())
402 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
403 : TLI.getPointerTy();
406 /// This method returns true if we are running before type legalization or
407 /// if the specified VT is legal.
408 bool isTypeLegal(const EVT &VT) {
409 if (!LegalTypes) return true;
410 return TLI.isTypeLegal(VT);
413 /// Convenience wrapper around TargetLowering::getSetCCResultType
414 EVT getSetCCResultType(EVT VT) const {
415 return TLI.getSetCCResultType(*DAG.getContext(), VT);
422 /// This class is a DAGUpdateListener that removes any deleted
423 /// nodes from the worklist.
424 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
427 explicit WorklistRemover(DAGCombiner &dc)
428 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
430 void NodeDeleted(SDNode *N, SDNode *E) override {
431 DC.removeFromWorklist(N);
436 //===----------------------------------------------------------------------===//
437 // TargetLowering::DAGCombinerInfo implementation
438 //===----------------------------------------------------------------------===//
440 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
441 ((DAGCombiner*)DC)->AddToWorklist(N);
444 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
445 ((DAGCombiner*)DC)->removeFromWorklist(N);
448 SDValue TargetLowering::DAGCombinerInfo::
449 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
450 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
453 SDValue TargetLowering::DAGCombinerInfo::
454 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
455 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
459 SDValue TargetLowering::DAGCombinerInfo::
460 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
461 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
464 void TargetLowering::DAGCombinerInfo::
465 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
466 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
469 //===----------------------------------------------------------------------===//
471 //===----------------------------------------------------------------------===//
473 void DAGCombiner::deleteAndRecombine(SDNode *N) {
474 removeFromWorklist(N);
476 // If the operands of this node are only used by the node, they will now be
477 // dead. Make sure to re-visit them and recursively delete dead nodes.
478 for (const SDValue &Op : N->ops())
479 // For an operand generating multiple values, one of the values may
480 // become dead allowing further simplification (e.g. split index
481 // arithmetic from an indexed load).
482 if (Op->hasOneUse() || Op->getNumValues() > 1)
483 AddToWorklist(Op.getNode());
488 /// Return 1 if we can compute the negated form of the specified expression for
489 /// the same cost as the expression itself, or 2 if we can compute the negated
490 /// form more cheaply than the expression itself.
491 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
492 const TargetLowering &TLI,
493 const TargetOptions *Options,
494 unsigned Depth = 0) {
495 // fneg is removable even if it has multiple uses.
496 if (Op.getOpcode() == ISD::FNEG) return 2;
498 // Don't allow anything with multiple uses.
499 if (!Op.hasOneUse()) return 0;
501 // Don't recurse exponentially.
502 if (Depth > 6) return 0;
504 switch (Op.getOpcode()) {
505 default: return false;
506 case ISD::ConstantFP:
507 // Don't invert constant FP values after legalize. The negated constant
508 // isn't necessarily legal.
509 return LegalOperations ? 0 : 1;
511 // FIXME: determine better conditions for this xform.
512 if (!Options->UnsafeFPMath) return 0;
514 // After operation legalization, it might not be legal to create new FSUBs.
515 if (LegalOperations &&
516 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
519 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
520 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
523 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
524 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
527 // We can't turn -(A-B) into B-A when we honor signed zeros.
528 if (!Options->UnsafeFPMath) return 0;
530 // fold (fneg (fsub A, B)) -> (fsub B, A)
535 if (Options->HonorSignDependentRoundingFPMath()) return 0;
537 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
538 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
542 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
548 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
553 /// If isNegatibleForFree returns true, return the newly negated expression.
554 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
555 bool LegalOperations, unsigned Depth = 0) {
556 const TargetOptions &Options = DAG.getTarget().Options;
557 // fneg is removable even if it has multiple uses.
558 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
560 // Don't allow anything with multiple uses.
561 assert(Op.hasOneUse() && "Unknown reuse!");
563 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
564 switch (Op.getOpcode()) {
565 default: llvm_unreachable("Unknown code");
566 case ISD::ConstantFP: {
567 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
569 return DAG.getConstantFP(V, Op.getValueType());
572 // FIXME: determine better conditions for this xform.
573 assert(Options.UnsafeFPMath);
575 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
576 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
577 DAG.getTargetLoweringInfo(), &Options, Depth+1))
578 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
579 GetNegatedExpression(Op.getOperand(0), DAG,
580 LegalOperations, Depth+1),
582 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
583 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
584 GetNegatedExpression(Op.getOperand(1), DAG,
585 LegalOperations, Depth+1),
588 // We can't turn -(A-B) into B-A when we honor signed zeros.
589 assert(Options.UnsafeFPMath);
591 // fold (fneg (fsub 0, B)) -> B
592 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
593 if (N0CFP->getValueAPF().isZero())
594 return Op.getOperand(1);
596 // fold (fneg (fsub A, B)) -> (fsub B, A)
597 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
598 Op.getOperand(1), Op.getOperand(0));
602 assert(!Options.HonorSignDependentRoundingFPMath());
604 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
605 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
606 DAG.getTargetLoweringInfo(), &Options, Depth+1))
607 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
608 GetNegatedExpression(Op.getOperand(0), DAG,
609 LegalOperations, Depth+1),
612 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
613 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
615 GetNegatedExpression(Op.getOperand(1), DAG,
616 LegalOperations, Depth+1));
620 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
621 GetNegatedExpression(Op.getOperand(0), DAG,
622 LegalOperations, Depth+1));
624 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
625 GetNegatedExpression(Op.getOperand(0), DAG,
626 LegalOperations, Depth+1),
631 // Return true if this node is a setcc, or is a select_cc
632 // that selects between the target values used for true and false, making it
633 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
634 // the appropriate nodes based on the type of node we are checking. This
635 // simplifies life a bit for the callers.
636 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
638 if (N.getOpcode() == ISD::SETCC) {
639 LHS = N.getOperand(0);
640 RHS = N.getOperand(1);
641 CC = N.getOperand(2);
645 if (N.getOpcode() != ISD::SELECT_CC ||
646 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
647 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
650 if (TLI.getBooleanContents(N.getValueType()) ==
651 TargetLowering::UndefinedBooleanContent)
654 LHS = N.getOperand(0);
655 RHS = N.getOperand(1);
656 CC = N.getOperand(4);
660 /// Return true if this is a SetCC-equivalent operation with only one use.
661 /// If this is true, it allows the users to invert the operation for free when
662 /// it is profitable to do so.
663 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
665 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
670 /// Returns true if N is a BUILD_VECTOR node whose
671 /// elements are all the same constant or undefined.
672 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
673 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
678 unsigned SplatBitSize;
680 EVT EltVT = N->getValueType(0).getVectorElementType();
681 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
683 EltVT.getSizeInBits() >= SplatBitSize);
686 // \brief Returns the SDNode if it is a constant BuildVector or constant.
687 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
688 if (isa<ConstantSDNode>(N))
690 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
691 if (BV && BV->isConstant())
696 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
698 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
699 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
702 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
703 BitVector UndefElements;
704 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
706 // BuildVectors can truncate their operands. Ignore that case here.
707 // FIXME: We blindly ignore splats which include undef which is overly
709 if (CN && UndefElements.none() &&
710 CN->getValueType(0) == N.getValueType().getScalarType())
717 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
719 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
720 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
723 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
724 BitVector UndefElements;
725 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
727 if (CN && UndefElements.none())
734 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
735 SDValue N0, SDValue N1) {
736 EVT VT = N0.getValueType();
737 if (N0.getOpcode() == Opc) {
738 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
739 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
740 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
741 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
742 if (!OpNode.getNode())
744 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
746 if (N0.hasOneUse()) {
747 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
749 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
750 if (!OpNode.getNode())
752 AddToWorklist(OpNode.getNode());
753 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
758 if (N1.getOpcode() == Opc) {
759 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
760 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
761 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
762 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
763 if (!OpNode.getNode())
765 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
767 if (N1.hasOneUse()) {
768 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
770 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
771 if (!OpNode.getNode())
773 AddToWorklist(OpNode.getNode());
774 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
782 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
784 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
786 DEBUG(dbgs() << "\nReplacing.1 ";
788 dbgs() << "\nWith: ";
789 To[0].getNode()->dump(&DAG);
790 dbgs() << " and " << NumTo-1 << " other values\n");
791 for (unsigned i = 0, e = NumTo; i != e; ++i)
792 assert((!To[i].getNode() ||
793 N->getValueType(i) == To[i].getValueType()) &&
794 "Cannot combine value to value of different type!");
796 WorklistRemover DeadNodes(*this);
797 DAG.ReplaceAllUsesWith(N, To);
799 // Push the new nodes and any users onto the worklist
800 for (unsigned i = 0, e = NumTo; i != e; ++i) {
801 if (To[i].getNode()) {
802 AddToWorklist(To[i].getNode());
803 AddUsersToWorklist(To[i].getNode());
808 // Finally, if the node is now dead, remove it from the graph. The node
809 // may not be dead if the replacement process recursively simplified to
810 // something else needing this node.
812 deleteAndRecombine(N);
813 return SDValue(N, 0);
817 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
818 // Replace all uses. If any nodes become isomorphic to other nodes and
819 // are deleted, make sure to remove them from our worklist.
820 WorklistRemover DeadNodes(*this);
821 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
823 // Push the new node and any (possibly new) users onto the worklist.
824 AddToWorklist(TLO.New.getNode());
825 AddUsersToWorklist(TLO.New.getNode());
827 // Finally, if the node is now dead, remove it from the graph. The node
828 // may not be dead if the replacement process recursively simplified to
829 // something else needing this node.
830 if (TLO.Old.getNode()->use_empty())
831 deleteAndRecombine(TLO.Old.getNode());
834 /// Check the specified integer node value to see if it can be simplified or if
835 /// things it uses can be simplified by bit propagation. If so, return true.
836 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
837 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
838 APInt KnownZero, KnownOne;
839 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
843 AddToWorklist(Op.getNode());
845 // Replace the old value with the new one.
847 DEBUG(dbgs() << "\nReplacing.2 ";
848 TLO.Old.getNode()->dump(&DAG);
849 dbgs() << "\nWith: ";
850 TLO.New.getNode()->dump(&DAG);
853 CommitTargetLoweringOpt(TLO);
857 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
859 EVT VT = Load->getValueType(0);
860 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
862 DEBUG(dbgs() << "\nReplacing.9 ";
864 dbgs() << "\nWith: ";
865 Trunc.getNode()->dump(&DAG);
867 WorklistRemover DeadNodes(*this);
868 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
869 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
870 deleteAndRecombine(Load);
871 AddToWorklist(Trunc.getNode());
874 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
877 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
878 EVT MemVT = LD->getMemoryVT();
879 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
880 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
882 : LD->getExtensionType();
884 return DAG.getExtLoad(ExtType, dl, PVT,
885 LD->getChain(), LD->getBasePtr(),
886 MemVT, LD->getMemOperand());
889 unsigned Opc = Op.getOpcode();
892 case ISD::AssertSext:
893 return DAG.getNode(ISD::AssertSext, dl, PVT,
894 SExtPromoteOperand(Op.getOperand(0), PVT),
896 case ISD::AssertZext:
897 return DAG.getNode(ISD::AssertZext, dl, PVT,
898 ZExtPromoteOperand(Op.getOperand(0), PVT),
900 case ISD::Constant: {
902 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
903 return DAG.getNode(ExtOpc, dl, PVT, Op);
907 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
909 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
912 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
913 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
915 EVT OldVT = Op.getValueType();
917 bool Replace = false;
918 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
919 if (!NewOp.getNode())
921 AddToWorklist(NewOp.getNode());
924 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
925 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
926 DAG.getValueType(OldVT));
929 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
930 EVT OldVT = Op.getValueType();
932 bool Replace = false;
933 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
934 if (!NewOp.getNode())
936 AddToWorklist(NewOp.getNode());
939 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
940 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
943 /// Promote the specified integer binary operation if the target indicates it is
944 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
945 /// i32 since i16 instructions are longer.
946 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
947 if (!LegalOperations)
950 EVT VT = Op.getValueType();
951 if (VT.isVector() || !VT.isInteger())
954 // If operation type is 'undesirable', e.g. i16 on x86, consider
956 unsigned Opc = Op.getOpcode();
957 if (TLI.isTypeDesirableForOp(Opc, VT))
961 // Consult target whether it is a good idea to promote this operation and
962 // what's the right type to promote it to.
963 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
964 assert(PVT != VT && "Don't know what type to promote to!");
966 bool Replace0 = false;
967 SDValue N0 = Op.getOperand(0);
968 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
972 bool Replace1 = false;
973 SDValue N1 = Op.getOperand(1);
978 NN1 = PromoteOperand(N1, PVT, Replace1);
983 AddToWorklist(NN0.getNode());
985 AddToWorklist(NN1.getNode());
988 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
990 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
992 DEBUG(dbgs() << "\nPromoting ";
993 Op.getNode()->dump(&DAG));
995 return DAG.getNode(ISD::TRUNCATE, dl, VT,
996 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1001 /// Promote the specified integer shift operation if the target indicates it is
1002 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1003 /// i32 since i16 instructions are longer.
1004 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1005 if (!LegalOperations)
1008 EVT VT = Op.getValueType();
1009 if (VT.isVector() || !VT.isInteger())
1012 // If operation type is 'undesirable', e.g. i16 on x86, consider
1014 unsigned Opc = Op.getOpcode();
1015 if (TLI.isTypeDesirableForOp(Opc, VT))
1019 // Consult target whether it is a good idea to promote this operation and
1020 // what's the right type to promote it to.
1021 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1022 assert(PVT != VT && "Don't know what type to promote to!");
1024 bool Replace = false;
1025 SDValue N0 = Op.getOperand(0);
1026 if (Opc == ISD::SRA)
1027 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1028 else if (Opc == ISD::SRL)
1029 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1031 N0 = PromoteOperand(N0, PVT, Replace);
1035 AddToWorklist(N0.getNode());
1037 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1039 DEBUG(dbgs() << "\nPromoting ";
1040 Op.getNode()->dump(&DAG));
1042 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1043 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1048 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1049 if (!LegalOperations)
1052 EVT VT = Op.getValueType();
1053 if (VT.isVector() || !VT.isInteger())
1056 // If operation type is 'undesirable', e.g. i16 on x86, consider
1058 unsigned Opc = Op.getOpcode();
1059 if (TLI.isTypeDesirableForOp(Opc, VT))
1063 // Consult target whether it is a good idea to promote this operation and
1064 // what's the right type to promote it to.
1065 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1066 assert(PVT != VT && "Don't know what type to promote to!");
1067 // fold (aext (aext x)) -> (aext x)
1068 // fold (aext (zext x)) -> (zext x)
1069 // fold (aext (sext x)) -> (sext x)
1070 DEBUG(dbgs() << "\nPromoting ";
1071 Op.getNode()->dump(&DAG));
1072 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1077 bool DAGCombiner::PromoteLoad(SDValue Op) {
1078 if (!LegalOperations)
1081 EVT VT = Op.getValueType();
1082 if (VT.isVector() || !VT.isInteger())
1085 // If operation type is 'undesirable', e.g. i16 on x86, consider
1087 unsigned Opc = Op.getOpcode();
1088 if (TLI.isTypeDesirableForOp(Opc, VT))
1092 // Consult target whether it is a good idea to promote this operation and
1093 // what's the right type to promote it to.
1094 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1095 assert(PVT != VT && "Don't know what type to promote to!");
1098 SDNode *N = Op.getNode();
1099 LoadSDNode *LD = cast<LoadSDNode>(N);
1100 EVT MemVT = LD->getMemoryVT();
1101 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1102 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1104 : LD->getExtensionType();
1105 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1106 LD->getChain(), LD->getBasePtr(),
1107 MemVT, LD->getMemOperand());
1108 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1110 DEBUG(dbgs() << "\nPromoting ";
1113 Result.getNode()->dump(&DAG);
1115 WorklistRemover DeadNodes(*this);
1116 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1117 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1118 deleteAndRecombine(N);
1119 AddToWorklist(Result.getNode());
1125 /// \brief Recursively delete a node which has no uses and any operands for
1126 /// which it is the only use.
1128 /// Note that this both deletes the nodes and removes them from the worklist.
1129 /// It also adds any nodes who have had a user deleted to the worklist as they
1130 /// may now have only one use and subject to other combines.
1131 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1132 if (!N->use_empty())
1135 SmallSetVector<SDNode *, 16> Nodes;
1138 N = Nodes.pop_back_val();
1142 if (N->use_empty()) {
1143 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1144 Nodes.insert(N->getOperand(i).getNode());
1146 removeFromWorklist(N);
1151 } while (!Nodes.empty());
1155 //===----------------------------------------------------------------------===//
1156 // Main DAG Combiner implementation
1157 //===----------------------------------------------------------------------===//
1159 void DAGCombiner::Run(CombineLevel AtLevel) {
1160 // set the instance variables, so that the various visit routines may use it.
1162 LegalOperations = Level >= AfterLegalizeVectorOps;
1163 LegalTypes = Level >= AfterLegalizeTypes;
1165 // Early exit if this basic block is in an optnone function.
1166 AttributeSet FnAttrs =
1167 DAG.getMachineFunction().getFunction()->getAttributes();
1168 if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1169 Attribute::OptimizeNone))
1172 // Add all the dag nodes to the worklist.
1173 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1174 E = DAG.allnodes_end(); I != E; ++I)
1177 // Create a dummy node (which is not added to allnodes), that adds a reference
1178 // to the root node, preventing it from being deleted, and tracking any
1179 // changes of the root.
1180 HandleSDNode Dummy(DAG.getRoot());
1182 // while the worklist isn't empty, find a node and
1183 // try and combine it.
1184 while (!WorklistMap.empty()) {
1186 // The Worklist holds the SDNodes in order, but it may contain null entries.
1188 N = Worklist.pop_back_val();
1191 bool GoodWorklistEntry = WorklistMap.erase(N);
1192 (void)GoodWorklistEntry;
1193 assert(GoodWorklistEntry &&
1194 "Found a worklist entry without a corresponding map entry!");
1196 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1197 // N is deleted from the DAG, since they too may now be dead or may have a
1198 // reduced number of uses, allowing other xforms.
1199 if (recursivelyDeleteUnusedNodes(N))
1202 WorklistRemover DeadNodes(*this);
1204 // If this combine is running after legalizing the DAG, re-legalize any
1205 // nodes pulled off the worklist.
1206 if (Level == AfterLegalizeDAG) {
1207 SmallSetVector<SDNode *, 16> UpdatedNodes;
1208 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1210 for (SDNode *LN : UpdatedNodes) {
1212 AddUsersToWorklist(LN);
1218 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1220 // Add any operands of the new node which have not yet been combined to the
1221 // worklist as well. Because the worklist uniques things already, this
1222 // won't repeatedly process the same operand.
1223 CombinedNodes.insert(N);
1224 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1225 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1226 AddToWorklist(N->getOperand(i).getNode());
1228 SDValue RV = combine(N);
1235 // If we get back the same node we passed in, rather than a new node or
1236 // zero, we know that the node must have defined multiple values and
1237 // CombineTo was used. Since CombineTo takes care of the worklist
1238 // mechanics for us, we have no work to do in this case.
1239 if (RV.getNode() == N)
1242 assert(N->getOpcode() != ISD::DELETED_NODE &&
1243 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1244 "Node was deleted but visit returned new node!");
1246 DEBUG(dbgs() << " ... into: ";
1247 RV.getNode()->dump(&DAG));
1249 // Transfer debug value.
1250 DAG.TransferDbgValues(SDValue(N, 0), RV);
1251 if (N->getNumValues() == RV.getNode()->getNumValues())
1252 DAG.ReplaceAllUsesWith(N, RV.getNode());
1254 assert(N->getValueType(0) == RV.getValueType() &&
1255 N->getNumValues() == 1 && "Type mismatch");
1257 DAG.ReplaceAllUsesWith(N, &OpV);
1260 // Push the new node and any users onto the worklist
1261 AddToWorklist(RV.getNode());
1262 AddUsersToWorklist(RV.getNode());
1264 // Finally, if the node is now dead, remove it from the graph. The node
1265 // may not be dead if the replacement process recursively simplified to
1266 // something else needing this node. This will also take care of adding any
1267 // operands which have lost a user to the worklist.
1268 recursivelyDeleteUnusedNodes(N);
1271 // If the root changed (e.g. it was a dead load, update the root).
1272 DAG.setRoot(Dummy.getValue());
1273 DAG.RemoveDeadNodes();
1276 SDValue DAGCombiner::visit(SDNode *N) {
1277 switch (N->getOpcode()) {
1279 case ISD::TokenFactor: return visitTokenFactor(N);
1280 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1281 case ISD::ADD: return visitADD(N);
1282 case ISD::SUB: return visitSUB(N);
1283 case ISD::ADDC: return visitADDC(N);
1284 case ISD::SUBC: return visitSUBC(N);
1285 case ISD::ADDE: return visitADDE(N);
1286 case ISD::SUBE: return visitSUBE(N);
1287 case ISD::MUL: return visitMUL(N);
1288 case ISD::SDIV: return visitSDIV(N);
1289 case ISD::UDIV: return visitUDIV(N);
1290 case ISD::SREM: return visitSREM(N);
1291 case ISD::UREM: return visitUREM(N);
1292 case ISD::MULHU: return visitMULHU(N);
1293 case ISD::MULHS: return visitMULHS(N);
1294 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1295 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1296 case ISD::SMULO: return visitSMULO(N);
1297 case ISD::UMULO: return visitUMULO(N);
1298 case ISD::SDIVREM: return visitSDIVREM(N);
1299 case ISD::UDIVREM: return visitUDIVREM(N);
1300 case ISD::AND: return visitAND(N);
1301 case ISD::OR: return visitOR(N);
1302 case ISD::XOR: return visitXOR(N);
1303 case ISD::SHL: return visitSHL(N);
1304 case ISD::SRA: return visitSRA(N);
1305 case ISD::SRL: return visitSRL(N);
1307 case ISD::ROTL: return visitRotate(N);
1308 case ISD::CTLZ: return visitCTLZ(N);
1309 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1310 case ISD::CTTZ: return visitCTTZ(N);
1311 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1312 case ISD::CTPOP: return visitCTPOP(N);
1313 case ISD::SELECT: return visitSELECT(N);
1314 case ISD::VSELECT: return visitVSELECT(N);
1315 case ISD::SELECT_CC: return visitSELECT_CC(N);
1316 case ISD::SETCC: return visitSETCC(N);
1317 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1318 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1319 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1320 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1321 case ISD::TRUNCATE: return visitTRUNCATE(N);
1322 case ISD::BITCAST: return visitBITCAST(N);
1323 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1324 case ISD::FADD: return visitFADD(N);
1325 case ISD::FSUB: return visitFSUB(N);
1326 case ISD::FMUL: return visitFMUL(N);
1327 case ISD::FMA: return visitFMA(N);
1328 case ISD::FDIV: return visitFDIV(N);
1329 case ISD::FREM: return visitFREM(N);
1330 case ISD::FSQRT: return visitFSQRT(N);
1331 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1332 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1333 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1334 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1335 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1336 case ISD::FP_ROUND: return visitFP_ROUND(N);
1337 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1338 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1339 case ISD::FNEG: return visitFNEG(N);
1340 case ISD::FABS: return visitFABS(N);
1341 case ISD::FFLOOR: return visitFFLOOR(N);
1342 case ISD::FMINNUM: return visitFMINNUM(N);
1343 case ISD::FMAXNUM: return visitFMAXNUM(N);
1344 case ISD::FCEIL: return visitFCEIL(N);
1345 case ISD::FTRUNC: return visitFTRUNC(N);
1346 case ISD::BRCOND: return visitBRCOND(N);
1347 case ISD::BR_CC: return visitBR_CC(N);
1348 case ISD::LOAD: return visitLOAD(N);
1349 case ISD::STORE: return visitSTORE(N);
1350 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1351 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1352 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1353 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1354 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1355 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1356 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1357 case ISD::MLOAD: return visitMLOAD(N);
1358 case ISD::MSTORE: return visitMSTORE(N);
1363 SDValue DAGCombiner::combine(SDNode *N) {
1364 SDValue RV = visit(N);
1366 // If nothing happened, try a target-specific DAG combine.
1367 if (!RV.getNode()) {
1368 assert(N->getOpcode() != ISD::DELETED_NODE &&
1369 "Node was deleted but visit returned NULL!");
1371 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1372 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1374 // Expose the DAG combiner to the target combiner impls.
1375 TargetLowering::DAGCombinerInfo
1376 DagCombineInfo(DAG, Level, false, this);
1378 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1382 // If nothing happened still, try promoting the operation.
1383 if (!RV.getNode()) {
1384 switch (N->getOpcode()) {
1392 RV = PromoteIntBinOp(SDValue(N, 0));
1397 RV = PromoteIntShiftOp(SDValue(N, 0));
1399 case ISD::SIGN_EXTEND:
1400 case ISD::ZERO_EXTEND:
1401 case ISD::ANY_EXTEND:
1402 RV = PromoteExtend(SDValue(N, 0));
1405 if (PromoteLoad(SDValue(N, 0)))
1411 // If N is a commutative binary node, try commuting it to enable more
1413 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1414 N->getNumValues() == 1) {
1415 SDValue N0 = N->getOperand(0);
1416 SDValue N1 = N->getOperand(1);
1418 // Constant operands are canonicalized to RHS.
1419 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1420 SDValue Ops[] = {N1, N0};
1422 if (const BinaryWithFlagsSDNode *BinNode =
1423 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1424 CSENode = DAG.getNodeIfExists(
1425 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1426 BinNode->hasNoSignedWrap(), BinNode->isExact());
1428 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1431 return SDValue(CSENode, 0);
1438 /// Given a node, return its input chain if it has one, otherwise return a null
1440 static SDValue getInputChainForNode(SDNode *N) {
1441 if (unsigned NumOps = N->getNumOperands()) {
1442 if (N->getOperand(0).getValueType() == MVT::Other)
1443 return N->getOperand(0);
1444 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1445 return N->getOperand(NumOps-1);
1446 for (unsigned i = 1; i < NumOps-1; ++i)
1447 if (N->getOperand(i).getValueType() == MVT::Other)
1448 return N->getOperand(i);
1453 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1454 // If N has two operands, where one has an input chain equal to the other,
1455 // the 'other' chain is redundant.
1456 if (N->getNumOperands() == 2) {
1457 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1458 return N->getOperand(0);
1459 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1460 return N->getOperand(1);
1463 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1464 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1465 SmallPtrSet<SDNode*, 16> SeenOps;
1466 bool Changed = false; // If we should replace this token factor.
1468 // Start out with this token factor.
1471 // Iterate through token factors. The TFs grows when new token factors are
1473 for (unsigned i = 0; i < TFs.size(); ++i) {
1474 SDNode *TF = TFs[i];
1476 // Check each of the operands.
1477 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1478 SDValue Op = TF->getOperand(i);
1480 switch (Op.getOpcode()) {
1481 case ISD::EntryToken:
1482 // Entry tokens don't need to be added to the list. They are
1487 case ISD::TokenFactor:
1488 if (Op.hasOneUse() &&
1489 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1490 // Queue up for processing.
1491 TFs.push_back(Op.getNode());
1492 // Clean up in case the token factor is removed.
1493 AddToWorklist(Op.getNode());
1500 // Only add if it isn't already in the list.
1501 if (SeenOps.insert(Op.getNode()).second)
1512 // If we've change things around then replace token factor.
1515 // The entry token is the only possible outcome.
1516 Result = DAG.getEntryNode();
1518 // New and improved token factor.
1519 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1522 // Don't add users to work list.
1523 return CombineTo(N, Result, false);
1529 /// MERGE_VALUES can always be eliminated.
1530 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1531 WorklistRemover DeadNodes(*this);
1532 // Replacing results may cause a different MERGE_VALUES to suddenly
1533 // be CSE'd with N, and carry its uses with it. Iterate until no
1534 // uses remain, to ensure that the node can be safely deleted.
1535 // First add the users of this node to the work list so that they
1536 // can be tried again once they have new operands.
1537 AddUsersToWorklist(N);
1539 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1540 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1541 } while (!N->use_empty());
1542 deleteAndRecombine(N);
1543 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1546 SDValue DAGCombiner::visitADD(SDNode *N) {
1547 SDValue N0 = N->getOperand(0);
1548 SDValue N1 = N->getOperand(1);
1549 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1550 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1551 EVT VT = N0.getValueType();
1554 if (VT.isVector()) {
1555 SDValue FoldedVOp = SimplifyVBinOp(N);
1556 if (FoldedVOp.getNode()) return FoldedVOp;
1558 // fold (add x, 0) -> x, vector edition
1559 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1561 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1565 // fold (add x, undef) -> undef
1566 if (N0.getOpcode() == ISD::UNDEF)
1568 if (N1.getOpcode() == ISD::UNDEF)
1570 // fold (add c1, c2) -> c1+c2
1572 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1573 // canonicalize constant to RHS
1575 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1576 // fold (add x, 0) -> x
1577 if (N1C && N1C->isNullValue())
1579 // fold (add Sym, c) -> Sym+c
1580 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1581 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1582 GA->getOpcode() == ISD::GlobalAddress)
1583 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1585 (uint64_t)N1C->getSExtValue());
1586 // fold ((c1-A)+c2) -> (c1+c2)-A
1587 if (N1C && N0.getOpcode() == ISD::SUB)
1588 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1589 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1590 DAG.getConstant(N1C->getAPIntValue()+
1591 N0C->getAPIntValue(), VT),
1594 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1597 // fold ((0-A) + B) -> B-A
1598 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1599 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1600 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1601 // fold (A + (0-B)) -> A-B
1602 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1603 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1604 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1605 // fold (A+(B-A)) -> B
1606 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1607 return N1.getOperand(0);
1608 // fold ((B-A)+A) -> B
1609 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1610 return N0.getOperand(0);
1611 // fold (A+(B-(A+C))) to (B-C)
1612 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1613 N0 == N1.getOperand(1).getOperand(0))
1614 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1615 N1.getOperand(1).getOperand(1));
1616 // fold (A+(B-(C+A))) to (B-C)
1617 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1618 N0 == N1.getOperand(1).getOperand(1))
1619 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1620 N1.getOperand(1).getOperand(0));
1621 // fold (A+((B-A)+or-C)) to (B+or-C)
1622 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1623 N1.getOperand(0).getOpcode() == ISD::SUB &&
1624 N0 == N1.getOperand(0).getOperand(1))
1625 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1626 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1628 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1629 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1630 SDValue N00 = N0.getOperand(0);
1631 SDValue N01 = N0.getOperand(1);
1632 SDValue N10 = N1.getOperand(0);
1633 SDValue N11 = N1.getOperand(1);
1635 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1636 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1637 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1638 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1641 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1642 return SDValue(N, 0);
1644 // fold (a+b) -> (a|b) iff a and b share no bits.
1645 if (VT.isInteger() && !VT.isVector()) {
1646 APInt LHSZero, LHSOne;
1647 APInt RHSZero, RHSOne;
1648 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1650 if (LHSZero.getBoolValue()) {
1651 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1653 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1654 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1655 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1656 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1657 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1662 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1663 if (N1.getOpcode() == ISD::SHL &&
1664 N1.getOperand(0).getOpcode() == ISD::SUB)
1665 if (ConstantSDNode *C =
1666 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1667 if (C->getAPIntValue() == 0)
1668 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1669 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1670 N1.getOperand(0).getOperand(1),
1672 if (N0.getOpcode() == ISD::SHL &&
1673 N0.getOperand(0).getOpcode() == ISD::SUB)
1674 if (ConstantSDNode *C =
1675 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1676 if (C->getAPIntValue() == 0)
1677 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1678 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1679 N0.getOperand(0).getOperand(1),
1682 if (N1.getOpcode() == ISD::AND) {
1683 SDValue AndOp0 = N1.getOperand(0);
1684 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1685 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1686 unsigned DestBits = VT.getScalarType().getSizeInBits();
1688 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1689 // and similar xforms where the inner op is either ~0 or 0.
1690 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1692 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1696 // add (sext i1), X -> sub X, (zext i1)
1697 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1698 N0.getOperand(0).getValueType() == MVT::i1 &&
1699 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1701 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1702 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1705 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1706 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1707 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1708 if (TN->getVT() == MVT::i1) {
1710 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1711 DAG.getConstant(1, VT));
1712 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1719 SDValue DAGCombiner::visitADDC(SDNode *N) {
1720 SDValue N0 = N->getOperand(0);
1721 SDValue N1 = N->getOperand(1);
1722 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1723 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1724 EVT VT = N0.getValueType();
1726 // If the flag result is dead, turn this into an ADD.
1727 if (!N->hasAnyUseOfValue(1))
1728 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1729 DAG.getNode(ISD::CARRY_FALSE,
1730 SDLoc(N), MVT::Glue));
1732 // canonicalize constant to RHS.
1734 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1736 // fold (addc x, 0) -> x + no carry out
1737 if (N1C && N1C->isNullValue())
1738 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1739 SDLoc(N), MVT::Glue));
1741 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1742 APInt LHSZero, LHSOne;
1743 APInt RHSZero, RHSOne;
1744 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1746 if (LHSZero.getBoolValue()) {
1747 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1749 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1750 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1751 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1752 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1753 DAG.getNode(ISD::CARRY_FALSE,
1754 SDLoc(N), MVT::Glue));
1760 SDValue DAGCombiner::visitADDE(SDNode *N) {
1761 SDValue N0 = N->getOperand(0);
1762 SDValue N1 = N->getOperand(1);
1763 SDValue CarryIn = N->getOperand(2);
1764 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1765 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1767 // canonicalize constant to RHS
1769 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1772 // fold (adde x, y, false) -> (addc x, y)
1773 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1774 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1779 // Since it may not be valid to emit a fold to zero for vector initializers
1780 // check if we can before folding.
1781 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1783 bool LegalOperations, bool LegalTypes) {
1785 return DAG.getConstant(0, VT);
1786 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1787 return DAG.getConstant(0, VT);
1791 SDValue DAGCombiner::visitSUB(SDNode *N) {
1792 SDValue N0 = N->getOperand(0);
1793 SDValue N1 = N->getOperand(1);
1794 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1795 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1796 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1797 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1798 EVT VT = N0.getValueType();
1801 if (VT.isVector()) {
1802 SDValue FoldedVOp = SimplifyVBinOp(N);
1803 if (FoldedVOp.getNode()) return FoldedVOp;
1805 // fold (sub x, 0) -> x, vector edition
1806 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1810 // fold (sub x, x) -> 0
1811 // FIXME: Refactor this and xor and other similar operations together.
1813 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1814 // fold (sub c1, c2) -> c1-c2
1816 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1817 // fold (sub x, c) -> (add x, -c)
1819 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1820 DAG.getConstant(-N1C->getAPIntValue(), VT));
1821 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1822 if (N0C && N0C->isAllOnesValue())
1823 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1824 // fold A-(A-B) -> B
1825 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1826 return N1.getOperand(1);
1827 // fold (A+B)-A -> B
1828 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1829 return N0.getOperand(1);
1830 // fold (A+B)-B -> A
1831 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1832 return N0.getOperand(0);
1833 // fold C2-(A+C1) -> (C2-C1)-A
1834 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1835 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1837 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1840 // fold ((A+(B+or-C))-B) -> A+or-C
1841 if (N0.getOpcode() == ISD::ADD &&
1842 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1843 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1844 N0.getOperand(1).getOperand(0) == N1)
1845 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1846 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1847 // fold ((A+(C+B))-B) -> A+C
1848 if (N0.getOpcode() == ISD::ADD &&
1849 N0.getOperand(1).getOpcode() == ISD::ADD &&
1850 N0.getOperand(1).getOperand(1) == N1)
1851 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1852 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1853 // fold ((A-(B-C))-C) -> A-B
1854 if (N0.getOpcode() == ISD::SUB &&
1855 N0.getOperand(1).getOpcode() == ISD::SUB &&
1856 N0.getOperand(1).getOperand(1) == N1)
1857 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1858 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1860 // If either operand of a sub is undef, the result is undef
1861 if (N0.getOpcode() == ISD::UNDEF)
1863 if (N1.getOpcode() == ISD::UNDEF)
1866 // If the relocation model supports it, consider symbol offsets.
1867 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1868 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1869 // fold (sub Sym, c) -> Sym-c
1870 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1871 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1873 (uint64_t)N1C->getSExtValue());
1874 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1875 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1876 if (GA->getGlobal() == GB->getGlobal())
1877 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1881 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1882 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1883 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1884 if (TN->getVT() == MVT::i1) {
1886 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1887 DAG.getConstant(1, VT));
1888 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1895 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1896 SDValue N0 = N->getOperand(0);
1897 SDValue N1 = N->getOperand(1);
1898 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1899 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1900 EVT VT = N0.getValueType();
1902 // If the flag result is dead, turn this into an SUB.
1903 if (!N->hasAnyUseOfValue(1))
1904 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1905 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1908 // fold (subc x, x) -> 0 + no borrow
1910 return CombineTo(N, DAG.getConstant(0, VT),
1911 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1914 // fold (subc x, 0) -> x + no borrow
1915 if (N1C && N1C->isNullValue())
1916 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1919 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1920 if (N0C && N0C->isAllOnesValue())
1921 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1922 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1928 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1929 SDValue N0 = N->getOperand(0);
1930 SDValue N1 = N->getOperand(1);
1931 SDValue CarryIn = N->getOperand(2);
1933 // fold (sube x, y, false) -> (subc x, y)
1934 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1935 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1940 SDValue DAGCombiner::visitMUL(SDNode *N) {
1941 SDValue N0 = N->getOperand(0);
1942 SDValue N1 = N->getOperand(1);
1943 EVT VT = N0.getValueType();
1945 // fold (mul x, undef) -> 0
1946 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1947 return DAG.getConstant(0, VT);
1949 bool N0IsConst = false;
1950 bool N1IsConst = false;
1951 APInt ConstValue0, ConstValue1;
1953 if (VT.isVector()) {
1954 SDValue FoldedVOp = SimplifyVBinOp(N);
1955 if (FoldedVOp.getNode()) return FoldedVOp;
1957 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1958 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1960 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1961 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1963 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1964 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1968 // fold (mul c1, c2) -> c1*c2
1969 if (N0IsConst && N1IsConst)
1970 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1972 // canonicalize constant to RHS
1973 if (N0IsConst && !N1IsConst)
1974 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1975 // fold (mul x, 0) -> 0
1976 if (N1IsConst && ConstValue1 == 0)
1978 // We require a splat of the entire scalar bit width for non-contiguous
1981 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1982 // fold (mul x, 1) -> x
1983 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1985 // fold (mul x, -1) -> 0-x
1986 if (N1IsConst && ConstValue1.isAllOnesValue())
1987 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1988 DAG.getConstant(0, VT), N0);
1989 // fold (mul x, (1 << c)) -> x << c
1990 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1991 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1992 DAG.getConstant(ConstValue1.logBase2(),
1993 getShiftAmountTy(N0.getValueType())));
1994 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1995 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1996 unsigned Log2Val = (-ConstValue1).logBase2();
1997 // FIXME: If the input is something that is easily negated (e.g. a
1998 // single-use add), we should put the negate there.
1999 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2000 DAG.getConstant(0, VT),
2001 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2002 DAG.getConstant(Log2Val,
2003 getShiftAmountTy(N0.getValueType()))));
2007 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2008 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2009 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2010 isa<ConstantSDNode>(N0.getOperand(1)))) {
2011 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2012 N1, N0.getOperand(1));
2013 AddToWorklist(C3.getNode());
2014 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2015 N0.getOperand(0), C3);
2018 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2021 SDValue Sh(nullptr,0), Y(nullptr,0);
2022 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2023 if (N0.getOpcode() == ISD::SHL &&
2024 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2025 isa<ConstantSDNode>(N0.getOperand(1))) &&
2026 N0.getNode()->hasOneUse()) {
2028 } else if (N1.getOpcode() == ISD::SHL &&
2029 isa<ConstantSDNode>(N1.getOperand(1)) &&
2030 N1.getNode()->hasOneUse()) {
2035 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2036 Sh.getOperand(0), Y);
2037 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2038 Mul, Sh.getOperand(1));
2042 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2043 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2044 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2045 isa<ConstantSDNode>(N0.getOperand(1))))
2046 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2047 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2048 N0.getOperand(0), N1),
2049 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2050 N0.getOperand(1), N1));
2053 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2060 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2061 SDValue N0 = N->getOperand(0);
2062 SDValue N1 = N->getOperand(1);
2063 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2064 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2065 EVT VT = N->getValueType(0);
2068 if (VT.isVector()) {
2069 SDValue FoldedVOp = SimplifyVBinOp(N);
2070 if (FoldedVOp.getNode()) return FoldedVOp;
2073 // fold (sdiv c1, c2) -> c1/c2
2074 if (N0C && N1C && !N1C->isNullValue())
2075 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2076 // fold (sdiv X, 1) -> X
2077 if (N1C && N1C->getAPIntValue() == 1LL)
2079 // fold (sdiv X, -1) -> 0-X
2080 if (N1C && N1C->isAllOnesValue())
2081 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2082 DAG.getConstant(0, VT), N0);
2083 // If we know the sign bits of both operands are zero, strength reduce to a
2084 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2085 if (!VT.isVector()) {
2086 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2087 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2091 // fold (sdiv X, pow2) -> simple ops after legalize
2092 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2093 (-N1C->getAPIntValue()).isPowerOf2())) {
2094 // If dividing by powers of two is cheap, then don't perform the following
2096 if (TLI.isPow2SDivCheap())
2099 // Target-specific implementation of sdiv x, pow2.
2100 SDValue Res = BuildSDIVPow2(N);
2104 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2106 // Splat the sign bit into the register
2108 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2109 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2110 getShiftAmountTy(N0.getValueType())));
2111 AddToWorklist(SGN.getNode());
2113 // Add (N0 < 0) ? abs2 - 1 : 0;
2115 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2116 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2117 getShiftAmountTy(SGN.getValueType())));
2118 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2119 AddToWorklist(SRL.getNode());
2120 AddToWorklist(ADD.getNode()); // Divide by pow2
2121 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2122 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2124 // If we're dividing by a positive value, we're done. Otherwise, we must
2125 // negate the result.
2126 if (N1C->getAPIntValue().isNonNegative())
2129 AddToWorklist(SRA.getNode());
2130 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2133 // if integer divide is expensive and we satisfy the requirements, emit an
2134 // alternate sequence.
2135 if (N1C && !TLI.isIntDivCheap()) {
2136 SDValue Op = BuildSDIV(N);
2137 if (Op.getNode()) return Op;
2141 if (N0.getOpcode() == ISD::UNDEF)
2142 return DAG.getConstant(0, VT);
2143 // X / undef -> undef
2144 if (N1.getOpcode() == ISD::UNDEF)
2150 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2151 SDValue N0 = N->getOperand(0);
2152 SDValue N1 = N->getOperand(1);
2153 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2154 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2155 EVT VT = N->getValueType(0);
2158 if (VT.isVector()) {
2159 SDValue FoldedVOp = SimplifyVBinOp(N);
2160 if (FoldedVOp.getNode()) return FoldedVOp;
2163 // fold (udiv c1, c2) -> c1/c2
2164 if (N0C && N1C && !N1C->isNullValue())
2165 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2166 // fold (udiv x, (1 << c)) -> x >>u c
2167 if (N1C && N1C->getAPIntValue().isPowerOf2())
2168 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2169 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2170 getShiftAmountTy(N0.getValueType())));
2171 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2172 if (N1.getOpcode() == ISD::SHL) {
2173 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2174 if (SHC->getAPIntValue().isPowerOf2()) {
2175 EVT ADDVT = N1.getOperand(1).getValueType();
2176 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2178 DAG.getConstant(SHC->getAPIntValue()
2181 AddToWorklist(Add.getNode());
2182 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2186 // fold (udiv x, c) -> alternate
2187 if (N1C && !TLI.isIntDivCheap()) {
2188 SDValue Op = BuildUDIV(N);
2189 if (Op.getNode()) return Op;
2193 if (N0.getOpcode() == ISD::UNDEF)
2194 return DAG.getConstant(0, VT);
2195 // X / undef -> undef
2196 if (N1.getOpcode() == ISD::UNDEF)
2202 SDValue DAGCombiner::visitSREM(SDNode *N) {
2203 SDValue N0 = N->getOperand(0);
2204 SDValue N1 = N->getOperand(1);
2205 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2206 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2207 EVT VT = N->getValueType(0);
2209 // fold (srem c1, c2) -> c1%c2
2210 if (N0C && N1C && !N1C->isNullValue())
2211 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2212 // If we know the sign bits of both operands are zero, strength reduce to a
2213 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2214 if (!VT.isVector()) {
2215 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2216 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2219 // If X/C can be simplified by the division-by-constant logic, lower
2220 // X%C to the equivalent of X-X/C*C.
2221 if (N1C && !N1C->isNullValue()) {
2222 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2223 AddToWorklist(Div.getNode());
2224 SDValue OptimizedDiv = combine(Div.getNode());
2225 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2226 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2228 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2229 AddToWorklist(Mul.getNode());
2235 if (N0.getOpcode() == ISD::UNDEF)
2236 return DAG.getConstant(0, VT);
2237 // X % undef -> undef
2238 if (N1.getOpcode() == ISD::UNDEF)
2244 SDValue DAGCombiner::visitUREM(SDNode *N) {
2245 SDValue N0 = N->getOperand(0);
2246 SDValue N1 = N->getOperand(1);
2247 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2248 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2249 EVT VT = N->getValueType(0);
2251 // fold (urem c1, c2) -> c1%c2
2252 if (N0C && N1C && !N1C->isNullValue())
2253 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2254 // fold (urem x, pow2) -> (and x, pow2-1)
2255 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2256 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2257 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2258 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2259 if (N1.getOpcode() == ISD::SHL) {
2260 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2261 if (SHC->getAPIntValue().isPowerOf2()) {
2263 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2264 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2266 AddToWorklist(Add.getNode());
2267 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2272 // If X/C can be simplified by the division-by-constant logic, lower
2273 // X%C to the equivalent of X-X/C*C.
2274 if (N1C && !N1C->isNullValue()) {
2275 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2276 AddToWorklist(Div.getNode());
2277 SDValue OptimizedDiv = combine(Div.getNode());
2278 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2279 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2281 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2282 AddToWorklist(Mul.getNode());
2288 if (N0.getOpcode() == ISD::UNDEF)
2289 return DAG.getConstant(0, VT);
2290 // X % undef -> undef
2291 if (N1.getOpcode() == ISD::UNDEF)
2297 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2298 SDValue N0 = N->getOperand(0);
2299 SDValue N1 = N->getOperand(1);
2300 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2301 EVT VT = N->getValueType(0);
2304 // fold (mulhs x, 0) -> 0
2305 if (N1C && N1C->isNullValue())
2307 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2308 if (N1C && N1C->getAPIntValue() == 1)
2309 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2310 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2311 getShiftAmountTy(N0.getValueType())));
2312 // fold (mulhs x, undef) -> 0
2313 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2314 return DAG.getConstant(0, VT);
2316 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2318 if (VT.isSimple() && !VT.isVector()) {
2319 MVT Simple = VT.getSimpleVT();
2320 unsigned SimpleSize = Simple.getSizeInBits();
2321 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2322 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2323 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2324 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2325 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2326 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2327 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2328 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2335 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2336 SDValue N0 = N->getOperand(0);
2337 SDValue N1 = N->getOperand(1);
2338 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2339 EVT VT = N->getValueType(0);
2342 // fold (mulhu x, 0) -> 0
2343 if (N1C && N1C->isNullValue())
2345 // fold (mulhu x, 1) -> 0
2346 if (N1C && N1C->getAPIntValue() == 1)
2347 return DAG.getConstant(0, N0.getValueType());
2348 // fold (mulhu x, undef) -> 0
2349 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2350 return DAG.getConstant(0, VT);
2352 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2354 if (VT.isSimple() && !VT.isVector()) {
2355 MVT Simple = VT.getSimpleVT();
2356 unsigned SimpleSize = Simple.getSizeInBits();
2357 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2358 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2359 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2360 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2361 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2362 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2363 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2364 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2371 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2372 /// give the opcodes for the two computations that are being performed. Return
2373 /// true if a simplification was made.
2374 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2376 // If the high half is not needed, just compute the low half.
2377 bool HiExists = N->hasAnyUseOfValue(1);
2379 (!LegalOperations ||
2380 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2381 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2382 return CombineTo(N, Res, Res);
2385 // If the low half is not needed, just compute the high half.
2386 bool LoExists = N->hasAnyUseOfValue(0);
2388 (!LegalOperations ||
2389 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2390 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2391 return CombineTo(N, Res, Res);
2394 // If both halves are used, return as it is.
2395 if (LoExists && HiExists)
2398 // If the two computed results can be simplified separately, separate them.
2400 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2401 AddToWorklist(Lo.getNode());
2402 SDValue LoOpt = combine(Lo.getNode());
2403 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2404 (!LegalOperations ||
2405 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2406 return CombineTo(N, LoOpt, LoOpt);
2410 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2411 AddToWorklist(Hi.getNode());
2412 SDValue HiOpt = combine(Hi.getNode());
2413 if (HiOpt.getNode() && HiOpt != Hi &&
2414 (!LegalOperations ||
2415 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2416 return CombineTo(N, HiOpt, HiOpt);
2422 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2423 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2424 if (Res.getNode()) return Res;
2426 EVT VT = N->getValueType(0);
2429 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2431 if (VT.isSimple() && !VT.isVector()) {
2432 MVT Simple = VT.getSimpleVT();
2433 unsigned SimpleSize = Simple.getSizeInBits();
2434 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2435 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2436 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2437 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2438 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2439 // Compute the high part as N1.
2440 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2441 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2442 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2443 // Compute the low part as N0.
2444 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2445 return CombineTo(N, Lo, Hi);
2452 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2453 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2454 if (Res.getNode()) return Res;
2456 EVT VT = N->getValueType(0);
2459 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2461 if (VT.isSimple() && !VT.isVector()) {
2462 MVT Simple = VT.getSimpleVT();
2463 unsigned SimpleSize = Simple.getSizeInBits();
2464 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2465 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2466 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2467 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2468 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2469 // Compute the high part as N1.
2470 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2471 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2472 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2473 // Compute the low part as N0.
2474 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2475 return CombineTo(N, Lo, Hi);
2482 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2483 // (smulo x, 2) -> (saddo x, x)
2484 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2485 if (C2->getAPIntValue() == 2)
2486 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2487 N->getOperand(0), N->getOperand(0));
2492 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2493 // (umulo x, 2) -> (uaddo x, x)
2494 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2495 if (C2->getAPIntValue() == 2)
2496 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2497 N->getOperand(0), N->getOperand(0));
2502 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2503 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2504 if (Res.getNode()) return Res;
2509 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2510 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2511 if (Res.getNode()) return Res;
2516 /// If this is a binary operator with two operands of the same opcode, try to
2518 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2519 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2520 EVT VT = N0.getValueType();
2521 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2523 // Bail early if none of these transforms apply.
2524 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2526 // For each of OP in AND/OR/XOR:
2527 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2528 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2529 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2530 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2531 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2533 // do not sink logical op inside of a vector extend, since it may combine
2535 EVT Op0VT = N0.getOperand(0).getValueType();
2536 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2537 N0.getOpcode() == ISD::SIGN_EXTEND ||
2538 N0.getOpcode() == ISD::BSWAP ||
2539 // Avoid infinite looping with PromoteIntBinOp.
2540 (N0.getOpcode() == ISD::ANY_EXTEND &&
2541 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2542 (N0.getOpcode() == ISD::TRUNCATE &&
2543 (!TLI.isZExtFree(VT, Op0VT) ||
2544 !TLI.isTruncateFree(Op0VT, VT)) &&
2545 TLI.isTypeLegal(Op0VT))) &&
2547 Op0VT == N1.getOperand(0).getValueType() &&
2548 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2549 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2550 N0.getOperand(0).getValueType(),
2551 N0.getOperand(0), N1.getOperand(0));
2552 AddToWorklist(ORNode.getNode());
2553 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2556 // For each of OP in SHL/SRL/SRA/AND...
2557 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2558 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2559 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2560 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2561 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2562 N0.getOperand(1) == N1.getOperand(1)) {
2563 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2564 N0.getOperand(0).getValueType(),
2565 N0.getOperand(0), N1.getOperand(0));
2566 AddToWorklist(ORNode.getNode());
2567 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2568 ORNode, N0.getOperand(1));
2571 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2572 // Only perform this optimization after type legalization and before
2573 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2574 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2575 // we don't want to undo this promotion.
2576 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2578 if ((N0.getOpcode() == ISD::BITCAST ||
2579 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2580 Level == AfterLegalizeTypes) {
2581 SDValue In0 = N0.getOperand(0);
2582 SDValue In1 = N1.getOperand(0);
2583 EVT In0Ty = In0.getValueType();
2584 EVT In1Ty = In1.getValueType();
2586 // If both incoming values are integers, and the original types are the
2588 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2589 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2590 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2591 AddToWorklist(Op.getNode());
2596 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2597 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2598 // If both shuffles use the same mask, and both shuffle within a single
2599 // vector, then it is worthwhile to move the swizzle after the operation.
2600 // The type-legalizer generates this pattern when loading illegal
2601 // vector types from memory. In many cases this allows additional shuffle
2603 // There are other cases where moving the shuffle after the xor/and/or
2604 // is profitable even if shuffles don't perform a swizzle.
2605 // If both shuffles use the same mask, and both shuffles have the same first
2606 // or second operand, then it might still be profitable to move the shuffle
2607 // after the xor/and/or operation.
2608 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2609 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2610 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2612 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2613 "Inputs to shuffles are not the same type");
2615 // Check that both shuffles use the same mask. The masks are known to be of
2616 // the same length because the result vector type is the same.
2617 // Check also that shuffles have only one use to avoid introducing extra
2619 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2620 SVN0->getMask().equals(SVN1->getMask())) {
2621 SDValue ShOp = N0->getOperand(1);
2623 // Don't try to fold this node if it requires introducing a
2624 // build vector of all zeros that might be illegal at this stage.
2625 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2627 ShOp = DAG.getConstant(0, VT);
2632 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2633 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2634 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2635 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2636 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2637 N0->getOperand(0), N1->getOperand(0));
2638 AddToWorklist(NewNode.getNode());
2639 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2640 &SVN0->getMask()[0]);
2643 // Don't try to fold this node if it requires introducing a
2644 // build vector of all zeros that might be illegal at this stage.
2645 ShOp = N0->getOperand(0);
2646 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2648 ShOp = DAG.getConstant(0, VT);
2653 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2654 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2655 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2656 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2657 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2658 N0->getOperand(1), N1->getOperand(1));
2659 AddToWorklist(NewNode.getNode());
2660 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2661 &SVN0->getMask()[0]);
2669 SDValue DAGCombiner::visitAND(SDNode *N) {
2670 SDValue N0 = N->getOperand(0);
2671 SDValue N1 = N->getOperand(1);
2672 SDValue LL, LR, RL, RR, CC0, CC1;
2673 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2674 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2675 EVT VT = N1.getValueType();
2676 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2679 if (VT.isVector()) {
2680 SDValue FoldedVOp = SimplifyVBinOp(N);
2681 if (FoldedVOp.getNode()) return FoldedVOp;
2683 // fold (and x, 0) -> 0, vector edition
2684 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2685 // do not return N0, because undef node may exist in N0
2686 return DAG.getConstant(
2687 APInt::getNullValue(
2688 N0.getValueType().getScalarType().getSizeInBits()),
2690 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2691 // do not return N1, because undef node may exist in N1
2692 return DAG.getConstant(
2693 APInt::getNullValue(
2694 N1.getValueType().getScalarType().getSizeInBits()),
2697 // fold (and x, -1) -> x, vector edition
2698 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2700 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2704 // fold (and x, undef) -> 0
2705 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2706 return DAG.getConstant(0, VT);
2707 // fold (and c1, c2) -> c1&c2
2709 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2710 // canonicalize constant to RHS
2712 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2713 // fold (and x, -1) -> x
2714 if (N1C && N1C->isAllOnesValue())
2716 // if (and x, c) is known to be zero, return 0
2717 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2718 APInt::getAllOnesValue(BitWidth)))
2719 return DAG.getConstant(0, VT);
2721 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2724 // fold (and (or x, C), D) -> D if (C & D) == D
2725 if (N1C && N0.getOpcode() == ISD::OR)
2726 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2727 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2729 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2730 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2731 SDValue N0Op0 = N0.getOperand(0);
2732 APInt Mask = ~N1C->getAPIntValue();
2733 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2734 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2735 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2736 N0.getValueType(), N0Op0);
2738 // Replace uses of the AND with uses of the Zero extend node.
2741 // We actually want to replace all uses of the any_extend with the
2742 // zero_extend, to avoid duplicating things. This will later cause this
2743 // AND to be folded.
2744 CombineTo(N0.getNode(), Zext);
2745 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2748 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2749 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2750 // already be zero by virtue of the width of the base type of the load.
2752 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2754 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2755 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2756 N0.getOpcode() == ISD::LOAD) {
2757 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2758 N0 : N0.getOperand(0) );
2760 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2761 // This can be a pure constant or a vector splat, in which case we treat the
2762 // vector as a scalar and use the splat value.
2763 APInt Constant = APInt::getNullValue(1);
2764 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2765 Constant = C->getAPIntValue();
2766 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2767 APInt SplatValue, SplatUndef;
2768 unsigned SplatBitSize;
2770 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2771 SplatBitSize, HasAnyUndefs);
2773 // Undef bits can contribute to a possible optimisation if set, so
2775 SplatValue |= SplatUndef;
2777 // The splat value may be something like "0x00FFFFFF", which means 0 for
2778 // the first vector value and FF for the rest, repeating. We need a mask
2779 // that will apply equally to all members of the vector, so AND all the
2780 // lanes of the constant together.
2781 EVT VT = Vector->getValueType(0);
2782 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2784 // If the splat value has been compressed to a bitlength lower
2785 // than the size of the vector lane, we need to re-expand it to
2787 if (BitWidth > SplatBitSize)
2788 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2789 SplatBitSize < BitWidth;
2790 SplatBitSize = SplatBitSize * 2)
2791 SplatValue |= SplatValue.shl(SplatBitSize);
2793 Constant = APInt::getAllOnesValue(BitWidth);
2794 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2795 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2799 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2800 // actually legal and isn't going to get expanded, else this is a false
2802 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2803 Load->getValueType(0),
2804 Load->getMemoryVT());
2806 // Resize the constant to the same size as the original memory access before
2807 // extension. If it is still the AllOnesValue then this AND is completely
2810 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2813 switch (Load->getExtensionType()) {
2814 default: B = false; break;
2815 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2817 case ISD::NON_EXTLOAD: B = true; break;
2820 if (B && Constant.isAllOnesValue()) {
2821 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2822 // preserve semantics once we get rid of the AND.
2823 SDValue NewLoad(Load, 0);
2824 if (Load->getExtensionType() == ISD::EXTLOAD) {
2825 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2826 Load->getValueType(0), SDLoc(Load),
2827 Load->getChain(), Load->getBasePtr(),
2828 Load->getOffset(), Load->getMemoryVT(),
2829 Load->getMemOperand());
2830 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2831 if (Load->getNumValues() == 3) {
2832 // PRE/POST_INC loads have 3 values.
2833 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2834 NewLoad.getValue(2) };
2835 CombineTo(Load, To, 3, true);
2837 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2841 // Fold the AND away, taking care not to fold to the old load node if we
2843 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2845 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2848 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2849 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2850 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2851 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2853 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2854 LL.getValueType().isInteger()) {
2855 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2856 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2857 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2858 LR.getValueType(), LL, RL);
2859 AddToWorklist(ORNode.getNode());
2860 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2862 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2863 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2864 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2865 LR.getValueType(), LL, RL);
2866 AddToWorklist(ANDNode.getNode());
2867 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2869 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2870 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2871 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2872 LR.getValueType(), LL, RL);
2873 AddToWorklist(ORNode.getNode());
2874 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2877 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2878 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2879 Op0 == Op1 && LL.getValueType().isInteger() &&
2880 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2881 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2882 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2883 cast<ConstantSDNode>(RR)->isNullValue()))) {
2884 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2885 LL, DAG.getConstant(1, LL.getValueType()));
2886 AddToWorklist(ADDNode.getNode());
2887 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2888 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2890 // canonicalize equivalent to ll == rl
2891 if (LL == RR && LR == RL) {
2892 Op1 = ISD::getSetCCSwappedOperands(Op1);
2895 if (LL == RL && LR == RR) {
2896 bool isInteger = LL.getValueType().isInteger();
2897 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2898 if (Result != ISD::SETCC_INVALID &&
2899 (!LegalOperations ||
2900 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2901 TLI.isOperationLegal(ISD::SETCC,
2902 getSetCCResultType(N0.getSimpleValueType())))))
2903 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2908 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2909 if (N0.getOpcode() == N1.getOpcode()) {
2910 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2911 if (Tmp.getNode()) return Tmp;
2914 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2915 // fold (and (sra)) -> (and (srl)) when possible.
2916 if (!VT.isVector() &&
2917 SimplifyDemandedBits(SDValue(N, 0)))
2918 return SDValue(N, 0);
2920 // fold (zext_inreg (extload x)) -> (zextload x)
2921 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2922 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2923 EVT MemVT = LN0->getMemoryVT();
2924 // If we zero all the possible extended bits, then we can turn this into
2925 // a zextload if we are running before legalize or the operation is legal.
2926 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2927 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2928 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2929 ((!LegalOperations && !LN0->isVolatile()) ||
2930 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2931 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2932 LN0->getChain(), LN0->getBasePtr(),
2933 MemVT, LN0->getMemOperand());
2935 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2936 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2939 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2940 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2942 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2943 EVT MemVT = LN0->getMemoryVT();
2944 // If we zero all the possible extended bits, then we can turn this into
2945 // a zextload if we are running before legalize or the operation is legal.
2946 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2947 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2948 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2949 ((!LegalOperations && !LN0->isVolatile()) ||
2950 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2951 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2952 LN0->getChain(), LN0->getBasePtr(),
2953 MemVT, LN0->getMemOperand());
2955 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2956 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2960 // fold (and (load x), 255) -> (zextload x, i8)
2961 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2962 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2963 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2964 (N0.getOpcode() == ISD::ANY_EXTEND &&
2965 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2966 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2967 LoadSDNode *LN0 = HasAnyExt
2968 ? cast<LoadSDNode>(N0.getOperand(0))
2969 : cast<LoadSDNode>(N0);
2970 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2971 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2972 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2973 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2974 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2975 EVT LoadedVT = LN0->getMemoryVT();
2976 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2978 if (ExtVT == LoadedVT &&
2979 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2983 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2984 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2985 LN0->getMemOperand());
2987 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2988 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2991 // Do not change the width of a volatile load.
2992 // Do not generate loads of non-round integer types since these can
2993 // be expensive (and would be wrong if the type is not byte sized).
2994 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2995 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2997 EVT PtrType = LN0->getOperand(1).getValueType();
2999 unsigned Alignment = LN0->getAlignment();
3000 SDValue NewPtr = LN0->getBasePtr();
3002 // For big endian targets, we need to add an offset to the pointer
3003 // to load the correct bytes. For little endian systems, we merely
3004 // need to read fewer bytes from the same pointer.
3005 if (TLI.isBigEndian()) {
3006 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3007 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3008 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3009 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3010 NewPtr, DAG.getConstant(PtrOff, PtrType));
3011 Alignment = MinAlign(Alignment, PtrOff);
3014 AddToWorklist(NewPtr.getNode());
3017 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3018 LN0->getChain(), NewPtr,
3019 LN0->getPointerInfo(),
3020 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3021 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3023 CombineTo(LN0, Load, Load.getValue(1));
3024 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3030 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3031 VT.getSizeInBits() <= 64) {
3032 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3033 APInt ADDC = ADDI->getAPIntValue();
3034 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3035 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3036 // immediate for an add, but it is legal if its top c2 bits are set,
3037 // transform the ADD so the immediate doesn't need to be materialized
3039 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3040 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3041 SRLI->getZExtValue());
3042 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3044 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3046 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3047 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3048 CombineTo(N0.getNode(), NewAdd);
3049 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3057 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3058 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3059 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3060 N0.getOperand(1), false);
3061 if (BSwap.getNode())
3068 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3069 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3070 bool DemandHighBits) {
3071 if (!LegalOperations)
3074 EVT VT = N->getValueType(0);
3075 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3077 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3080 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3081 bool LookPassAnd0 = false;
3082 bool LookPassAnd1 = false;
3083 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3085 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3087 if (N0.getOpcode() == ISD::AND) {
3088 if (!N0.getNode()->hasOneUse())
3090 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3091 if (!N01C || N01C->getZExtValue() != 0xFF00)
3093 N0 = N0.getOperand(0);
3094 LookPassAnd0 = true;
3097 if (N1.getOpcode() == ISD::AND) {
3098 if (!N1.getNode()->hasOneUse())
3100 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3101 if (!N11C || N11C->getZExtValue() != 0xFF)
3103 N1 = N1.getOperand(0);
3104 LookPassAnd1 = true;
3107 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3109 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3111 if (!N0.getNode()->hasOneUse() ||
3112 !N1.getNode()->hasOneUse())
3115 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3116 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3119 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3122 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3123 SDValue N00 = N0->getOperand(0);
3124 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3125 if (!N00.getNode()->hasOneUse())
3127 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3128 if (!N001C || N001C->getZExtValue() != 0xFF)
3130 N00 = N00.getOperand(0);
3131 LookPassAnd0 = true;
3134 SDValue N10 = N1->getOperand(0);
3135 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3136 if (!N10.getNode()->hasOneUse())
3138 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3139 if (!N101C || N101C->getZExtValue() != 0xFF00)
3141 N10 = N10.getOperand(0);
3142 LookPassAnd1 = true;
3148 // Make sure everything beyond the low halfword gets set to zero since the SRL
3149 // 16 will clear the top bits.
3150 unsigned OpSizeInBits = VT.getSizeInBits();
3151 if (DemandHighBits && OpSizeInBits > 16) {
3152 // If the left-shift isn't masked out then the only way this is a bswap is
3153 // if all bits beyond the low 8 are 0. In that case the entire pattern
3154 // reduces to a left shift anyway: leave it for other parts of the combiner.
3158 // However, if the right shift isn't masked out then it might be because
3159 // it's not needed. See if we can spot that too.
3160 if (!LookPassAnd1 &&
3161 !DAG.MaskedValueIsZero(
3162 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3166 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3167 if (OpSizeInBits > 16)
3168 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3169 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3173 /// Return true if the specified node is an element that makes up a 32-bit
3174 /// packed halfword byteswap.
3175 /// ((x & 0x000000ff) << 8) |
3176 /// ((x & 0x0000ff00) >> 8) |
3177 /// ((x & 0x00ff0000) << 8) |
3178 /// ((x & 0xff000000) >> 8)
3179 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3180 if (!N.getNode()->hasOneUse())
3183 unsigned Opc = N.getOpcode();
3184 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3187 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3192 switch (N1C->getZExtValue()) {
3195 case 0xFF: Num = 0; break;
3196 case 0xFF00: Num = 1; break;
3197 case 0xFF0000: Num = 2; break;
3198 case 0xFF000000: Num = 3; break;
3201 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3202 SDValue N0 = N.getOperand(0);
3203 if (Opc == ISD::AND) {
3204 if (Num == 0 || Num == 2) {
3206 // (x >> 8) & 0xff0000
3207 if (N0.getOpcode() != ISD::SRL)
3209 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3210 if (!C || C->getZExtValue() != 8)
3213 // (x << 8) & 0xff00
3214 // (x << 8) & 0xff000000
3215 if (N0.getOpcode() != ISD::SHL)
3217 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3218 if (!C || C->getZExtValue() != 8)
3221 } else if (Opc == ISD::SHL) {
3223 // (x & 0xff0000) << 8
3224 if (Num != 0 && Num != 2)
3226 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3227 if (!C || C->getZExtValue() != 8)
3229 } else { // Opc == ISD::SRL
3230 // (x & 0xff00) >> 8
3231 // (x & 0xff000000) >> 8
3232 if (Num != 1 && Num != 3)
3234 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3235 if (!C || C->getZExtValue() != 8)
3242 Parts[Num] = N0.getOperand(0).getNode();
3246 /// Match a 32-bit packed halfword bswap. That is
3247 /// ((x & 0x000000ff) << 8) |
3248 /// ((x & 0x0000ff00) >> 8) |
3249 /// ((x & 0x00ff0000) << 8) |
3250 /// ((x & 0xff000000) >> 8)
3251 /// => (rotl (bswap x), 16)
3252 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3253 if (!LegalOperations)
3256 EVT VT = N->getValueType(0);
3259 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3263 // (or (or (and), (and)), (or (and), (and)))
3264 // (or (or (or (and), (and)), (and)), (and))
3265 if (N0.getOpcode() != ISD::OR)
3267 SDValue N00 = N0.getOperand(0);
3268 SDValue N01 = N0.getOperand(1);
3269 SDNode *Parts[4] = {};
3271 if (N1.getOpcode() == ISD::OR &&
3272 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3273 // (or (or (and), (and)), (or (and), (and)))
3274 SDValue N000 = N00.getOperand(0);
3275 if (!isBSwapHWordElement(N000, Parts))
3278 SDValue N001 = N00.getOperand(1);
3279 if (!isBSwapHWordElement(N001, Parts))
3281 SDValue N010 = N01.getOperand(0);
3282 if (!isBSwapHWordElement(N010, Parts))
3284 SDValue N011 = N01.getOperand(1);
3285 if (!isBSwapHWordElement(N011, Parts))
3288 // (or (or (or (and), (and)), (and)), (and))
3289 if (!isBSwapHWordElement(N1, Parts))
3291 if (!isBSwapHWordElement(N01, Parts))
3293 if (N00.getOpcode() != ISD::OR)
3295 SDValue N000 = N00.getOperand(0);
3296 if (!isBSwapHWordElement(N000, Parts))
3298 SDValue N001 = N00.getOperand(1);
3299 if (!isBSwapHWordElement(N001, Parts))
3303 // Make sure the parts are all coming from the same node.
3304 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3307 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3308 SDValue(Parts[0],0));
3310 // Result of the bswap should be rotated by 16. If it's not legal, then
3311 // do (x << 16) | (x >> 16).
3312 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3313 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3314 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3315 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3316 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3317 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3318 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3319 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3322 SDValue DAGCombiner::visitOR(SDNode *N) {
3323 SDValue N0 = N->getOperand(0);
3324 SDValue N1 = N->getOperand(1);
3325 SDValue LL, LR, RL, RR, CC0, CC1;
3326 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3327 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3328 EVT VT = N1.getValueType();
3331 if (VT.isVector()) {
3332 SDValue FoldedVOp = SimplifyVBinOp(N);
3333 if (FoldedVOp.getNode()) return FoldedVOp;
3335 // fold (or x, 0) -> x, vector edition
3336 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3338 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3341 // fold (or x, -1) -> -1, vector edition
3342 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3343 // do not return N0, because undef node may exist in N0
3344 return DAG.getConstant(
3345 APInt::getAllOnesValue(
3346 N0.getValueType().getScalarType().getSizeInBits()),
3348 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3349 // do not return N1, because undef node may exist in N1
3350 return DAG.getConstant(
3351 APInt::getAllOnesValue(
3352 N1.getValueType().getScalarType().getSizeInBits()),
3355 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3356 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3357 // Do this only if the resulting shuffle is legal.
3358 if (isa<ShuffleVectorSDNode>(N0) &&
3359 isa<ShuffleVectorSDNode>(N1) &&
3360 // Avoid folding a node with illegal type.
3361 TLI.isTypeLegal(VT) &&
3362 N0->getOperand(1) == N1->getOperand(1) &&
3363 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3364 bool CanFold = true;
3365 unsigned NumElts = VT.getVectorNumElements();
3366 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3367 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3368 // We construct two shuffle masks:
3369 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3370 // and N1 as the second operand.
3371 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3372 // and N0 as the second operand.
3373 // We do this because OR is commutable and therefore there might be
3374 // two ways to fold this node into a shuffle.
3375 SmallVector<int,4> Mask1;
3376 SmallVector<int,4> Mask2;
3378 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3379 int M0 = SV0->getMaskElt(i);
3380 int M1 = SV1->getMaskElt(i);
3382 // Both shuffle indexes are undef. Propagate Undef.
3383 if (M0 < 0 && M1 < 0) {
3384 Mask1.push_back(M0);
3385 Mask2.push_back(M0);
3389 if (M0 < 0 || M1 < 0 ||
3390 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3391 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3396 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3397 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3401 // Fold this sequence only if the resulting shuffle is 'legal'.
3402 if (TLI.isShuffleMaskLegal(Mask1, VT))
3403 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3404 N1->getOperand(0), &Mask1[0]);
3405 if (TLI.isShuffleMaskLegal(Mask2, VT))
3406 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3407 N0->getOperand(0), &Mask2[0]);
3412 // fold (or x, undef) -> -1
3413 if (!LegalOperations &&
3414 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3415 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3416 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3418 // fold (or c1, c2) -> c1|c2
3420 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3421 // canonicalize constant to RHS
3423 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3424 // fold (or x, 0) -> x
3425 if (N1C && N1C->isNullValue())
3427 // fold (or x, -1) -> -1
3428 if (N1C && N1C->isAllOnesValue())
3430 // fold (or x, c) -> c iff (x & ~c) == 0
3431 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3434 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3435 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3436 if (BSwap.getNode())
3438 BSwap = MatchBSwapHWordLow(N, N0, N1);
3439 if (BSwap.getNode())
3443 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3446 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3447 // iff (c1 & c2) == 0.
3448 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3449 isa<ConstantSDNode>(N0.getOperand(1))) {
3450 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3451 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3452 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3455 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3456 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3457 N0.getOperand(0), N1), COR);
3460 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3461 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3462 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3463 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3465 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3466 LL.getValueType().isInteger()) {
3467 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3468 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3469 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3470 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3471 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3472 LR.getValueType(), LL, RL);
3473 AddToWorklist(ORNode.getNode());
3474 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3476 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3477 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3478 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3479 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3480 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3481 LR.getValueType(), LL, RL);
3482 AddToWorklist(ANDNode.getNode());
3483 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3486 // canonicalize equivalent to ll == rl
3487 if (LL == RR && LR == RL) {
3488 Op1 = ISD::getSetCCSwappedOperands(Op1);
3491 if (LL == RL && LR == RR) {
3492 bool isInteger = LL.getValueType().isInteger();
3493 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3494 if (Result != ISD::SETCC_INVALID &&
3495 (!LegalOperations ||
3496 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3497 TLI.isOperationLegal(ISD::SETCC,
3498 getSetCCResultType(N0.getValueType())))))
3499 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3504 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3505 if (N0.getOpcode() == N1.getOpcode()) {
3506 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3507 if (Tmp.getNode()) return Tmp;
3510 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3511 if (N0.getOpcode() == ISD::AND &&
3512 N1.getOpcode() == ISD::AND &&
3513 N0.getOperand(1).getOpcode() == ISD::Constant &&
3514 N1.getOperand(1).getOpcode() == ISD::Constant &&
3515 // Don't increase # computations.
3516 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3517 // We can only do this xform if we know that bits from X that are set in C2
3518 // but not in C1 are already zero. Likewise for Y.
3519 const APInt &LHSMask =
3520 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3521 const APInt &RHSMask =
3522 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3524 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3525 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3526 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3527 N0.getOperand(0), N1.getOperand(0));
3528 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3529 DAG.getConstant(LHSMask | RHSMask, VT));
3533 // See if this is some rotate idiom.
3534 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3535 return SDValue(Rot, 0);
3537 // Simplify the operands using demanded-bits information.
3538 if (!VT.isVector() &&
3539 SimplifyDemandedBits(SDValue(N, 0)))
3540 return SDValue(N, 0);
3545 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3546 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3547 if (Op.getOpcode() == ISD::AND) {
3548 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3549 Mask = Op.getOperand(1);
3550 Op = Op.getOperand(0);
3556 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3564 // Return true if we can prove that, whenever Neg and Pos are both in the
3565 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3566 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3568 // (or (shift1 X, Neg), (shift2 X, Pos))
3570 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3571 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3572 // to consider shift amounts with defined behavior.
3573 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3574 // If OpSize is a power of 2 then:
3576 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3577 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3579 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3580 // for the stronger condition:
3582 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3584 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3585 // we can just replace Neg with Neg' for the rest of the function.
3587 // In other cases we check for the even stronger condition:
3589 // Neg == OpSize - Pos [B]
3591 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3592 // behavior if Pos == 0 (and consequently Neg == OpSize).
3594 // We could actually use [A] whenever OpSize is a power of 2, but the
3595 // only extra cases that it would match are those uninteresting ones
3596 // where Neg and Pos are never in range at the same time. E.g. for
3597 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3598 // as well as (sub 32, Pos), but:
3600 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3602 // always invokes undefined behavior for 32-bit X.
3604 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3605 unsigned MaskLoBits = 0;
3606 if (Neg.getOpcode() == ISD::AND &&
3607 isPowerOf2_64(OpSize) &&
3608 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3609 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3610 Neg = Neg.getOperand(0);
3611 MaskLoBits = Log2_64(OpSize);
3614 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3615 if (Neg.getOpcode() != ISD::SUB)
3617 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3620 SDValue NegOp1 = Neg.getOperand(1);
3622 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3623 // Pos'. The truncation is redundant for the purpose of the equality.
3625 Pos.getOpcode() == ISD::AND &&
3626 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3627 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3628 Pos = Pos.getOperand(0);
3630 // The condition we need is now:
3632 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3634 // If NegOp1 == Pos then we need:
3636 // OpSize & Mask == NegC & Mask
3638 // (because "x & Mask" is a truncation and distributes through subtraction).
3641 Width = NegC->getAPIntValue();
3642 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3643 // Then the condition we want to prove becomes:
3645 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3647 // which, again because "x & Mask" is a truncation, becomes:
3649 // NegC & Mask == (OpSize - PosC) & Mask
3650 // OpSize & Mask == (NegC + PosC) & Mask
3651 else if (Pos.getOpcode() == ISD::ADD &&
3652 Pos.getOperand(0) == NegOp1 &&
3653 Pos.getOperand(1).getOpcode() == ISD::Constant)
3654 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3655 NegC->getAPIntValue());
3659 // Now we just need to check that OpSize & Mask == Width & Mask.
3661 // Opsize & Mask is 0 since Mask is Opsize - 1.
3662 return Width.getLoBits(MaskLoBits) == 0;
3663 return Width == OpSize;
3666 // A subroutine of MatchRotate used once we have found an OR of two opposite
3667 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3668 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3669 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3670 // Neg with outer conversions stripped away.
3671 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3672 SDValue Neg, SDValue InnerPos,
3673 SDValue InnerNeg, unsigned PosOpcode,
3674 unsigned NegOpcode, SDLoc DL) {
3675 // fold (or (shl x, (*ext y)),
3676 // (srl x, (*ext (sub 32, y)))) ->
3677 // (rotl x, y) or (rotr x, (sub 32, y))
3679 // fold (or (shl x, (*ext (sub 32, y))),
3680 // (srl x, (*ext y))) ->
3681 // (rotr x, y) or (rotl x, (sub 32, y))
3682 EVT VT = Shifted.getValueType();
3683 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3684 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3685 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3686 HasPos ? Pos : Neg).getNode();
3692 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3693 // idioms for rotate, and if the target supports rotation instructions, generate
3695 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3696 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3697 EVT VT = LHS.getValueType();
3698 if (!TLI.isTypeLegal(VT)) return nullptr;
3700 // The target must have at least one rotate flavor.
3701 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3702 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3703 if (!HasROTL && !HasROTR) return nullptr;
3705 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3706 SDValue LHSShift; // The shift.
3707 SDValue LHSMask; // AND value if any.
3708 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3709 return nullptr; // Not part of a rotate.
3711 SDValue RHSShift; // The shift.
3712 SDValue RHSMask; // AND value if any.
3713 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3714 return nullptr; // Not part of a rotate.
3716 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3717 return nullptr; // Not shifting the same value.
3719 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3720 return nullptr; // Shifts must disagree.
3722 // Canonicalize shl to left side in a shl/srl pair.
3723 if (RHSShift.getOpcode() == ISD::SHL) {
3724 std::swap(LHS, RHS);
3725 std::swap(LHSShift, RHSShift);
3726 std::swap(LHSMask , RHSMask );
3729 unsigned OpSizeInBits = VT.getSizeInBits();
3730 SDValue LHSShiftArg = LHSShift.getOperand(0);
3731 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3732 SDValue RHSShiftArg = RHSShift.getOperand(0);
3733 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3735 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3736 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3737 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3738 RHSShiftAmt.getOpcode() == ISD::Constant) {
3739 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3740 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3741 if ((LShVal + RShVal) != OpSizeInBits)
3744 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3745 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3747 // If there is an AND of either shifted operand, apply it to the result.
3748 if (LHSMask.getNode() || RHSMask.getNode()) {
3749 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3751 if (LHSMask.getNode()) {
3752 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3753 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3755 if (RHSMask.getNode()) {
3756 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3757 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3760 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3763 return Rot.getNode();
3766 // If there is a mask here, and we have a variable shift, we can't be sure
3767 // that we're masking out the right stuff.
3768 if (LHSMask.getNode() || RHSMask.getNode())
3771 // If the shift amount is sign/zext/any-extended just peel it off.
3772 SDValue LExtOp0 = LHSShiftAmt;
3773 SDValue RExtOp0 = RHSShiftAmt;
3774 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3775 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3776 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3777 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3778 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3779 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3780 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3781 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3782 LExtOp0 = LHSShiftAmt.getOperand(0);
3783 RExtOp0 = RHSShiftAmt.getOperand(0);
3786 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3787 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3791 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3792 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3799 SDValue DAGCombiner::visitXOR(SDNode *N) {
3800 SDValue N0 = N->getOperand(0);
3801 SDValue N1 = N->getOperand(1);
3802 SDValue LHS, RHS, CC;
3803 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3804 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3805 EVT VT = N0.getValueType();
3808 if (VT.isVector()) {
3809 SDValue FoldedVOp = SimplifyVBinOp(N);
3810 if (FoldedVOp.getNode()) return FoldedVOp;
3812 // fold (xor x, 0) -> x, vector edition
3813 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3815 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3819 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3820 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3821 return DAG.getConstant(0, VT);
3822 // fold (xor x, undef) -> undef
3823 if (N0.getOpcode() == ISD::UNDEF)
3825 if (N1.getOpcode() == ISD::UNDEF)
3827 // fold (xor c1, c2) -> c1^c2
3829 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3830 // canonicalize constant to RHS
3832 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3833 // fold (xor x, 0) -> x
3834 if (N1C && N1C->isNullValue())
3837 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3841 // fold !(x cc y) -> (x !cc y)
3842 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3843 bool isInt = LHS.getValueType().isInteger();
3844 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3847 if (!LegalOperations ||
3848 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3849 switch (N0.getOpcode()) {
3851 llvm_unreachable("Unhandled SetCC Equivalent!");
3853 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3854 case ISD::SELECT_CC:
3855 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3856 N0.getOperand(3), NotCC);
3861 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3862 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3863 N0.getNode()->hasOneUse() &&
3864 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3865 SDValue V = N0.getOperand(0);
3866 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3867 DAG.getConstant(1, V.getValueType()));
3868 AddToWorklist(V.getNode());
3869 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3872 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3873 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3874 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3875 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3876 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3877 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3878 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3879 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3880 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3881 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3884 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3885 if (N1C && N1C->isAllOnesValue() &&
3886 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3887 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3888 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3889 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3890 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3891 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3892 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3893 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3896 // fold (xor (and x, y), y) -> (and (not x), y)
3897 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3898 N0->getOperand(1) == N1) {
3899 SDValue X = N0->getOperand(0);
3900 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3901 AddToWorklist(NotX.getNode());
3902 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3904 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3905 if (N1C && N0.getOpcode() == ISD::XOR) {
3906 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3907 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3909 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3910 DAG.getConstant(N1C->getAPIntValue() ^
3911 N00C->getAPIntValue(), VT));
3913 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3914 DAG.getConstant(N1C->getAPIntValue() ^
3915 N01C->getAPIntValue(), VT));
3917 // fold (xor x, x) -> 0
3919 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3921 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3922 if (N0.getOpcode() == N1.getOpcode()) {
3923 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3924 if (Tmp.getNode()) return Tmp;
3927 // Simplify the expression using non-local knowledge.
3928 if (!VT.isVector() &&
3929 SimplifyDemandedBits(SDValue(N, 0)))
3930 return SDValue(N, 0);
3935 /// Handle transforms common to the three shifts, when the shift amount is a
3937 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3938 // We can't and shouldn't fold opaque constants.
3939 if (Amt->isOpaque())
3942 SDNode *LHS = N->getOperand(0).getNode();
3943 if (!LHS->hasOneUse()) return SDValue();
3945 // We want to pull some binops through shifts, so that we have (and (shift))
3946 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3947 // thing happens with address calculations, so it's important to canonicalize
3949 bool HighBitSet = false; // Can we transform this if the high bit is set?
3951 switch (LHS->getOpcode()) {
3952 default: return SDValue();
3955 HighBitSet = false; // We can only transform sra if the high bit is clear.
3958 HighBitSet = true; // We can only transform sra if the high bit is set.
3961 if (N->getOpcode() != ISD::SHL)
3962 return SDValue(); // only shl(add) not sr[al](add).
3963 HighBitSet = false; // We can only transform sra if the high bit is clear.
3967 // We require the RHS of the binop to be a constant and not opaque as well.
3968 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3969 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3971 // FIXME: disable this unless the input to the binop is a shift by a constant.
3972 // If it is not a shift, it pessimizes some common cases like:
3974 // void foo(int *X, int i) { X[i & 1235] = 1; }
3975 // int bar(int *X, int i) { return X[i & 255]; }
3976 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3977 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3978 BinOpLHSVal->getOpcode() != ISD::SRA &&
3979 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3980 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3983 EVT VT = N->getValueType(0);
3985 // If this is a signed shift right, and the high bit is modified by the
3986 // logical operation, do not perform the transformation. The highBitSet
3987 // boolean indicates the value of the high bit of the constant which would
3988 // cause it to be modified for this operation.
3989 if (N->getOpcode() == ISD::SRA) {
3990 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3991 if (BinOpRHSSignSet != HighBitSet)
3995 if (!TLI.isDesirableToCommuteWithShift(LHS))
3998 // Fold the constants, shifting the binop RHS by the shift amount.
3999 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4001 LHS->getOperand(1), N->getOperand(1));
4002 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4004 // Create the new shift.
4005 SDValue NewShift = DAG.getNode(N->getOpcode(),
4006 SDLoc(LHS->getOperand(0)),
4007 VT, LHS->getOperand(0), N->getOperand(1));
4009 // Create the new binop.
4010 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4013 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4014 assert(N->getOpcode() == ISD::TRUNCATE);
4015 assert(N->getOperand(0).getOpcode() == ISD::AND);
4017 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4018 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4019 SDValue N01 = N->getOperand(0).getOperand(1);
4021 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4022 EVT TruncVT = N->getValueType(0);
4023 SDValue N00 = N->getOperand(0).getOperand(0);
4024 APInt TruncC = N01C->getAPIntValue();
4025 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4027 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4028 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4029 DAG.getConstant(TruncC, TruncVT));
4036 SDValue DAGCombiner::visitRotate(SDNode *N) {
4037 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4038 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4039 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4040 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4041 if (NewOp1.getNode())
4042 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4043 N->getOperand(0), NewOp1);
4048 SDValue DAGCombiner::visitSHL(SDNode *N) {
4049 SDValue N0 = N->getOperand(0);
4050 SDValue N1 = N->getOperand(1);
4051 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4052 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4053 EVT VT = N0.getValueType();
4054 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4057 if (VT.isVector()) {
4058 SDValue FoldedVOp = SimplifyVBinOp(N);
4059 if (FoldedVOp.getNode()) return FoldedVOp;
4061 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4062 // If setcc produces all-one true value then:
4063 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4064 if (N1CV && N1CV->isConstant()) {
4065 if (N0.getOpcode() == ISD::AND) {
4066 SDValue N00 = N0->getOperand(0);
4067 SDValue N01 = N0->getOperand(1);
4068 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4070 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4071 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4072 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4073 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4075 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4078 N1C = isConstOrConstSplat(N1);
4083 // fold (shl c1, c2) -> c1<<c2
4085 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4086 // fold (shl 0, x) -> 0
4087 if (N0C && N0C->isNullValue())
4089 // fold (shl x, c >= size(x)) -> undef
4090 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4091 return DAG.getUNDEF(VT);
4092 // fold (shl x, 0) -> x
4093 if (N1C && N1C->isNullValue())
4095 // fold (shl undef, x) -> 0
4096 if (N0.getOpcode() == ISD::UNDEF)
4097 return DAG.getConstant(0, VT);
4098 // if (shl x, c) is known to be zero, return 0
4099 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4100 APInt::getAllOnesValue(OpSizeInBits)))
4101 return DAG.getConstant(0, VT);
4102 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4103 if (N1.getOpcode() == ISD::TRUNCATE &&
4104 N1.getOperand(0).getOpcode() == ISD::AND) {
4105 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4106 if (NewOp1.getNode())
4107 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4110 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4111 return SDValue(N, 0);
4113 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4114 if (N1C && N0.getOpcode() == ISD::SHL) {
4115 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4116 uint64_t c1 = N0C1->getZExtValue();
4117 uint64_t c2 = N1C->getZExtValue();
4118 if (c1 + c2 >= OpSizeInBits)
4119 return DAG.getConstant(0, VT);
4120 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4121 DAG.getConstant(c1 + c2, N1.getValueType()));
4125 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4126 // For this to be valid, the second form must not preserve any of the bits
4127 // that are shifted out by the inner shift in the first form. This means
4128 // the outer shift size must be >= the number of bits added by the ext.
4129 // As a corollary, we don't care what kind of ext it is.
4130 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4131 N0.getOpcode() == ISD::ANY_EXTEND ||
4132 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4133 N0.getOperand(0).getOpcode() == ISD::SHL) {
4134 SDValue N0Op0 = N0.getOperand(0);
4135 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4136 uint64_t c1 = N0Op0C1->getZExtValue();
4137 uint64_t c2 = N1C->getZExtValue();
4138 EVT InnerShiftVT = N0Op0.getValueType();
4139 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4140 if (c2 >= OpSizeInBits - InnerShiftSize) {
4141 if (c1 + c2 >= OpSizeInBits)
4142 return DAG.getConstant(0, VT);
4143 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4144 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4145 N0Op0->getOperand(0)),
4146 DAG.getConstant(c1 + c2, N1.getValueType()));
4151 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4152 // Only fold this if the inner zext has no other uses to avoid increasing
4153 // the total number of instructions.
4154 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4155 N0.getOperand(0).getOpcode() == ISD::SRL) {
4156 SDValue N0Op0 = N0.getOperand(0);
4157 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4158 uint64_t c1 = N0Op0C1->getZExtValue();
4159 if (c1 < VT.getScalarSizeInBits()) {
4160 uint64_t c2 = N1C->getZExtValue();
4162 SDValue NewOp0 = N0.getOperand(0);
4163 EVT CountVT = NewOp0.getOperand(1).getValueType();
4164 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4165 NewOp0, DAG.getConstant(c2, CountVT));
4166 AddToWorklist(NewSHL.getNode());
4167 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4173 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4174 // (and (srl x, (sub c1, c2), MASK)
4175 // Only fold this if the inner shift has no other uses -- if it does, folding
4176 // this will increase the total number of instructions.
4177 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4178 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4179 uint64_t c1 = N0C1->getZExtValue();
4180 if (c1 < OpSizeInBits) {
4181 uint64_t c2 = N1C->getZExtValue();
4182 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4185 Mask = Mask.shl(c2 - c1);
4186 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4187 DAG.getConstant(c2 - c1, N1.getValueType()));
4189 Mask = Mask.lshr(c1 - c2);
4190 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4191 DAG.getConstant(c1 - c2, N1.getValueType()));
4193 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4194 DAG.getConstant(Mask, VT));
4198 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4199 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4200 unsigned BitSize = VT.getScalarSizeInBits();
4201 SDValue HiBitsMask =
4202 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4203 BitSize - N1C->getZExtValue()), VT);
4204 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4208 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4209 // Variant of version done on multiply, except mul by a power of 2 is turned
4212 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4213 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4214 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4215 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4216 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4217 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4221 SDValue NewSHL = visitShiftByConstant(N, N1C);
4222 if (NewSHL.getNode())
4229 SDValue DAGCombiner::visitSRA(SDNode *N) {
4230 SDValue N0 = N->getOperand(0);
4231 SDValue N1 = N->getOperand(1);
4232 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4233 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4234 EVT VT = N0.getValueType();
4235 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4238 if (VT.isVector()) {
4239 SDValue FoldedVOp = SimplifyVBinOp(N);
4240 if (FoldedVOp.getNode()) return FoldedVOp;
4242 N1C = isConstOrConstSplat(N1);
4245 // fold (sra c1, c2) -> (sra c1, c2)
4247 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4248 // fold (sra 0, x) -> 0
4249 if (N0C && N0C->isNullValue())
4251 // fold (sra -1, x) -> -1
4252 if (N0C && N0C->isAllOnesValue())
4254 // fold (sra x, (setge c, size(x))) -> undef
4255 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4256 return DAG.getUNDEF(VT);
4257 // fold (sra x, 0) -> x
4258 if (N1C && N1C->isNullValue())
4260 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4262 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4263 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4264 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4266 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4267 ExtVT, VT.getVectorNumElements());
4268 if ((!LegalOperations ||
4269 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4270 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4271 N0.getOperand(0), DAG.getValueType(ExtVT));
4274 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4275 if (N1C && N0.getOpcode() == ISD::SRA) {
4276 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4277 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4278 if (Sum >= OpSizeInBits)
4279 Sum = OpSizeInBits - 1;
4280 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4281 DAG.getConstant(Sum, N1.getValueType()));
4285 // fold (sra (shl X, m), (sub result_size, n))
4286 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4287 // result_size - n != m.
4288 // If truncate is free for the target sext(shl) is likely to result in better
4290 if (N0.getOpcode() == ISD::SHL && N1C) {
4291 // Get the two constanst of the shifts, CN0 = m, CN = n.
4292 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4294 LLVMContext &Ctx = *DAG.getContext();
4295 // Determine what the truncate's result bitsize and type would be.
4296 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4299 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4301 // Determine the residual right-shift amount.
4302 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4304 // If the shift is not a no-op (in which case this should be just a sign
4305 // extend already), the truncated to type is legal, sign_extend is legal
4306 // on that type, and the truncate to that type is both legal and free,
4307 // perform the transform.
4308 if ((ShiftAmt > 0) &&
4309 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4310 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4311 TLI.isTruncateFree(VT, TruncVT)) {
4313 SDValue Amt = DAG.getConstant(ShiftAmt,
4314 getShiftAmountTy(N0.getOperand(0).getValueType()));
4315 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4316 N0.getOperand(0), Amt);
4317 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4319 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4320 N->getValueType(0), Trunc);
4325 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4326 if (N1.getOpcode() == ISD::TRUNCATE &&
4327 N1.getOperand(0).getOpcode() == ISD::AND) {
4328 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4329 if (NewOp1.getNode())
4330 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4333 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4334 // if c1 is equal to the number of bits the trunc removes
4335 if (N0.getOpcode() == ISD::TRUNCATE &&
4336 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4337 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4338 N0.getOperand(0).hasOneUse() &&
4339 N0.getOperand(0).getOperand(1).hasOneUse() &&
4341 SDValue N0Op0 = N0.getOperand(0);
4342 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4343 unsigned LargeShiftVal = LargeShift->getZExtValue();
4344 EVT LargeVT = N0Op0.getValueType();
4346 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4348 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4349 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4350 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4351 N0Op0.getOperand(0), Amt);
4352 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4357 // Simplify, based on bits shifted out of the LHS.
4358 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4359 return SDValue(N, 0);
4362 // If the sign bit is known to be zero, switch this to a SRL.
4363 if (DAG.SignBitIsZero(N0))
4364 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4367 SDValue NewSRA = visitShiftByConstant(N, N1C);
4368 if (NewSRA.getNode())
4375 SDValue DAGCombiner::visitSRL(SDNode *N) {
4376 SDValue N0 = N->getOperand(0);
4377 SDValue N1 = N->getOperand(1);
4378 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4379 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4380 EVT VT = N0.getValueType();
4381 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4384 if (VT.isVector()) {
4385 SDValue FoldedVOp = SimplifyVBinOp(N);
4386 if (FoldedVOp.getNode()) return FoldedVOp;
4388 N1C = isConstOrConstSplat(N1);
4391 // fold (srl c1, c2) -> c1 >>u c2
4393 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4394 // fold (srl 0, x) -> 0
4395 if (N0C && N0C->isNullValue())
4397 // fold (srl x, c >= size(x)) -> undef
4398 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4399 return DAG.getUNDEF(VT);
4400 // fold (srl x, 0) -> x
4401 if (N1C && N1C->isNullValue())
4403 // if (srl x, c) is known to be zero, return 0
4404 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4405 APInt::getAllOnesValue(OpSizeInBits)))
4406 return DAG.getConstant(0, VT);
4408 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4409 if (N1C && N0.getOpcode() == ISD::SRL) {
4410 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4411 uint64_t c1 = N01C->getZExtValue();
4412 uint64_t c2 = N1C->getZExtValue();
4413 if (c1 + c2 >= OpSizeInBits)
4414 return DAG.getConstant(0, VT);
4415 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4416 DAG.getConstant(c1 + c2, N1.getValueType()));
4420 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4421 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4422 N0.getOperand(0).getOpcode() == ISD::SRL &&
4423 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4425 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4426 uint64_t c2 = N1C->getZExtValue();
4427 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4428 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4429 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4430 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4431 if (c1 + OpSizeInBits == InnerShiftSize) {
4432 if (c1 + c2 >= InnerShiftSize)
4433 return DAG.getConstant(0, VT);
4434 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4435 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4436 N0.getOperand(0)->getOperand(0),
4437 DAG.getConstant(c1 + c2, ShiftCountVT)));
4441 // fold (srl (shl x, c), c) -> (and x, cst2)
4442 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4443 unsigned BitSize = N0.getScalarValueSizeInBits();
4444 if (BitSize <= 64) {
4445 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4446 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4447 DAG.getConstant(~0ULL >> ShAmt, VT));
4451 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4452 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4453 // Shifting in all undef bits?
4454 EVT SmallVT = N0.getOperand(0).getValueType();
4455 unsigned BitSize = SmallVT.getScalarSizeInBits();
4456 if (N1C->getZExtValue() >= BitSize)
4457 return DAG.getUNDEF(VT);
4459 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4460 uint64_t ShiftAmt = N1C->getZExtValue();
4461 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4463 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4464 AddToWorklist(SmallShift.getNode());
4465 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4466 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4467 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4468 DAG.getConstant(Mask, VT));
4472 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4473 // bit, which is unmodified by sra.
4474 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4475 if (N0.getOpcode() == ISD::SRA)
4476 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4479 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4480 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4481 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4482 APInt KnownZero, KnownOne;
4483 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4485 // If any of the input bits are KnownOne, then the input couldn't be all
4486 // zeros, thus the result of the srl will always be zero.
4487 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4489 // If all of the bits input the to ctlz node are known to be zero, then
4490 // the result of the ctlz is "32" and the result of the shift is one.
4491 APInt UnknownBits = ~KnownZero;
4492 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4494 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4495 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4496 // Okay, we know that only that the single bit specified by UnknownBits
4497 // could be set on input to the CTLZ node. If this bit is set, the SRL
4498 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4499 // to an SRL/XOR pair, which is likely to simplify more.
4500 unsigned ShAmt = UnknownBits.countTrailingZeros();
4501 SDValue Op = N0.getOperand(0);
4504 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4505 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4506 AddToWorklist(Op.getNode());
4509 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4510 Op, DAG.getConstant(1, VT));
4514 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4515 if (N1.getOpcode() == ISD::TRUNCATE &&
4516 N1.getOperand(0).getOpcode() == ISD::AND) {
4517 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4518 if (NewOp1.getNode())
4519 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4522 // fold operands of srl based on knowledge that the low bits are not
4524 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4525 return SDValue(N, 0);
4528 SDValue NewSRL = visitShiftByConstant(N, N1C);
4529 if (NewSRL.getNode())
4533 // Attempt to convert a srl of a load into a narrower zero-extending load.
4534 SDValue NarrowLoad = ReduceLoadWidth(N);
4535 if (NarrowLoad.getNode())
4538 // Here is a common situation. We want to optimize:
4541 // %b = and i32 %a, 2
4542 // %c = srl i32 %b, 1
4543 // brcond i32 %c ...
4549 // %c = setcc eq %b, 0
4552 // However when after the source operand of SRL is optimized into AND, the SRL
4553 // itself may not be optimized further. Look for it and add the BRCOND into
4555 if (N->hasOneUse()) {
4556 SDNode *Use = *N->use_begin();
4557 if (Use->getOpcode() == ISD::BRCOND)
4559 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4560 // Also look pass the truncate.
4561 Use = *Use->use_begin();
4562 if (Use->getOpcode() == ISD::BRCOND)
4570 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4571 SDValue N0 = N->getOperand(0);
4572 EVT VT = N->getValueType(0);
4574 // fold (ctlz c1) -> c2
4575 if (isa<ConstantSDNode>(N0))
4576 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4580 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4581 SDValue N0 = N->getOperand(0);
4582 EVT VT = N->getValueType(0);
4584 // fold (ctlz_zero_undef c1) -> c2
4585 if (isa<ConstantSDNode>(N0))
4586 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4590 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4591 SDValue N0 = N->getOperand(0);
4592 EVT VT = N->getValueType(0);
4594 // fold (cttz c1) -> c2
4595 if (isa<ConstantSDNode>(N0))
4596 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4600 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4601 SDValue N0 = N->getOperand(0);
4602 EVT VT = N->getValueType(0);
4604 // fold (cttz_zero_undef c1) -> c2
4605 if (isa<ConstantSDNode>(N0))
4606 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4610 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4611 SDValue N0 = N->getOperand(0);
4612 EVT VT = N->getValueType(0);
4614 // fold (ctpop c1) -> c2
4615 if (isa<ConstantSDNode>(N0))
4616 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4620 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4621 SDValue N0 = N->getOperand(0);
4622 SDValue N1 = N->getOperand(1);
4623 SDValue N2 = N->getOperand(2);
4624 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4625 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4626 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4627 EVT VT = N->getValueType(0);
4628 EVT VT0 = N0.getValueType();
4630 // fold (select C, X, X) -> X
4633 // fold (select true, X, Y) -> X
4634 if (N0C && !N0C->isNullValue())
4636 // fold (select false, X, Y) -> Y
4637 if (N0C && N0C->isNullValue())
4639 // fold (select C, 1, X) -> (or C, X)
4640 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4641 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4642 // fold (select C, 0, 1) -> (xor C, 1)
4643 // We can't do this reliably if integer based booleans have different contents
4644 // to floating point based booleans. This is because we can't tell whether we
4645 // have an integer-based boolean or a floating-point-based boolean unless we
4646 // can find the SETCC that produced it and inspect its operands. This is
4647 // fairly easy if C is the SETCC node, but it can potentially be
4648 // undiscoverable (or not reasonably discoverable). For example, it could be
4649 // in another basic block or it could require searching a complicated
4651 if (VT.isInteger() &&
4652 (VT0 == MVT::i1 || (VT0.isInteger() &&
4653 TLI.getBooleanContents(false, false) ==
4654 TLI.getBooleanContents(false, true) &&
4655 TLI.getBooleanContents(false, false) ==
4656 TargetLowering::ZeroOrOneBooleanContent)) &&
4657 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4660 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4661 N0, DAG.getConstant(1, VT0));
4662 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4663 N0, DAG.getConstant(1, VT0));
4664 AddToWorklist(XORNode.getNode());
4666 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4667 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4669 // fold (select C, 0, X) -> (and (not C), X)
4670 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4671 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4672 AddToWorklist(NOTNode.getNode());
4673 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4675 // fold (select C, X, 1) -> (or (not C), X)
4676 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4677 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4678 AddToWorklist(NOTNode.getNode());
4679 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4681 // fold (select C, X, 0) -> (and C, X)
4682 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4683 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4684 // fold (select X, X, Y) -> (or X, Y)
4685 // fold (select X, 1, Y) -> (or X, Y)
4686 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4687 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4688 // fold (select X, Y, X) -> (and X, Y)
4689 // fold (select X, Y, 0) -> (and X, Y)
4690 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4691 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4693 // If we can fold this based on the true/false value, do so.
4694 if (SimplifySelectOps(N, N1, N2))
4695 return SDValue(N, 0); // Don't revisit N.
4697 // fold selects based on a setcc into other things, such as min/max/abs
4698 if (N0.getOpcode() == ISD::SETCC) {
4699 if ((!LegalOperations &&
4700 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4701 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4702 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4703 N0.getOperand(0), N0.getOperand(1),
4704 N1, N2, N0.getOperand(2));
4705 return SimplifySelect(SDLoc(N), N0, N1, N2);
4712 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4715 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4717 // Split the inputs.
4718 SDValue Lo, Hi, LL, LH, RL, RH;
4719 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4720 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4722 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4723 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4725 return std::make_pair(Lo, Hi);
4728 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4729 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4730 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4732 SDValue Cond = N->getOperand(0);
4733 SDValue LHS = N->getOperand(1);
4734 SDValue RHS = N->getOperand(2);
4735 EVT VT = N->getValueType(0);
4736 int NumElems = VT.getVectorNumElements();
4737 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4738 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4739 Cond.getOpcode() == ISD::BUILD_VECTOR);
4741 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4742 // binary ones here.
4743 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4746 // We're sure we have an even number of elements due to the
4747 // concat_vectors we have as arguments to vselect.
4748 // Skip BV elements until we find one that's not an UNDEF
4749 // After we find an UNDEF element, keep looping until we get to half the
4750 // length of the BV and see if all the non-undef nodes are the same.
4751 ConstantSDNode *BottomHalf = nullptr;
4752 for (int i = 0; i < NumElems / 2; ++i) {
4753 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4756 if (BottomHalf == nullptr)
4757 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4758 else if (Cond->getOperand(i).getNode() != BottomHalf)
4762 // Do the same for the second half of the BuildVector
4763 ConstantSDNode *TopHalf = nullptr;
4764 for (int i = NumElems / 2; i < NumElems; ++i) {
4765 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4768 if (TopHalf == nullptr)
4769 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4770 else if (Cond->getOperand(i).getNode() != TopHalf)
4774 assert(TopHalf && BottomHalf &&
4775 "One half of the selector was all UNDEFs and the other was all the "
4776 "same value. This should have been addressed before this function.");
4778 ISD::CONCAT_VECTORS, dl, VT,
4779 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4780 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4783 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4785 if (Level >= AfterLegalizeTypes)
4788 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4789 SDValue Mask = MST->getMask();
4790 SDValue Data = MST->getData();
4793 // If the MSTORE data type requires splitting and the mask is provided by a
4794 // SETCC, then split both nodes and its operands before legalization. This
4795 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4796 // and enables future optimizations (e.g. min/max pattern matching on X86).
4797 if (Mask.getOpcode() == ISD::SETCC) {
4799 // Check if any splitting is required.
4800 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4801 TargetLowering::TypeSplitVector)
4804 SDValue MaskLo, MaskHi, Lo, Hi;
4805 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4808 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4810 SDValue Chain = MST->getChain();
4811 SDValue Ptr = MST->getBasePtr();
4813 EVT MemoryVT = MST->getMemoryVT();
4814 unsigned Alignment = MST->getOriginalAlignment();
4816 // if Alignment is equal to the vector size,
4817 // take the half of it for the second part
4818 unsigned SecondHalfAlignment =
4819 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4820 Alignment/2 : Alignment;
4822 EVT LoMemVT, HiMemVT;
4823 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4825 SDValue DataLo, DataHi;
4826 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4828 MachineMemOperand *MMO = DAG.getMachineFunction().
4829 getMachineMemOperand(MST->getPointerInfo(),
4830 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
4831 Alignment, MST->getAAInfo(), MST->getRanges());
4833 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4835 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4836 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4837 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4839 MMO = DAG.getMachineFunction().
4840 getMachineMemOperand(MST->getPointerInfo(),
4841 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
4842 SecondHalfAlignment, MST->getAAInfo(),
4845 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4847 AddToWorklist(Lo.getNode());
4848 AddToWorklist(Hi.getNode());
4850 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4855 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4857 if (Level >= AfterLegalizeTypes)
4860 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4861 SDValue Mask = MLD->getMask();
4864 // If the MLOAD result requires splitting and the mask is provided by a
4865 // SETCC, then split both nodes and its operands before legalization. This
4866 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4867 // and enables future optimizations (e.g. min/max pattern matching on X86).
4869 if (Mask.getOpcode() == ISD::SETCC) {
4870 EVT VT = N->getValueType(0);
4872 // Check if any splitting is required.
4873 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4874 TargetLowering::TypeSplitVector)
4877 SDValue MaskLo, MaskHi, Lo, Hi;
4878 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4880 SDValue Src0 = MLD->getSrc0();
4881 SDValue Src0Lo, Src0Hi;
4882 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4885 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4887 SDValue Chain = MLD->getChain();
4888 SDValue Ptr = MLD->getBasePtr();
4889 EVT MemoryVT = MLD->getMemoryVT();
4890 unsigned Alignment = MLD->getOriginalAlignment();
4892 // if Alignment is equal to the vector size,
4893 // take the half of it for the second part
4894 unsigned SecondHalfAlignment =
4895 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4896 Alignment/2 : Alignment;
4898 EVT LoMemVT, HiMemVT;
4899 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4901 MachineMemOperand *MMO = DAG.getMachineFunction().
4902 getMachineMemOperand(MLD->getPointerInfo(),
4903 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
4904 Alignment, MLD->getAAInfo(), MLD->getRanges());
4906 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4908 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4909 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4910 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4912 MMO = DAG.getMachineFunction().
4913 getMachineMemOperand(MLD->getPointerInfo(),
4914 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
4915 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4917 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4919 AddToWorklist(Lo.getNode());
4920 AddToWorklist(Hi.getNode());
4922 // Build a factor node to remember that this load is independent of the
4924 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4927 // Legalized the chain result - switch anything that used the old chain to
4929 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4931 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4933 SDValue RetOps[] = { LoadRes, Chain };
4934 return DAG.getMergeValues(RetOps, DL);
4939 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4940 SDValue N0 = N->getOperand(0);
4941 SDValue N1 = N->getOperand(1);
4942 SDValue N2 = N->getOperand(2);
4945 // Canonicalize integer abs.
4946 // vselect (setg[te] X, 0), X, -X ->
4947 // vselect (setgt X, -1), X, -X ->
4948 // vselect (setl[te] X, 0), -X, X ->
4949 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4950 if (N0.getOpcode() == ISD::SETCC) {
4951 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4952 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4954 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4956 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4957 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4958 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4959 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4960 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4961 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4962 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4965 EVT VT = LHS.getValueType();
4966 SDValue Shift = DAG.getNode(
4967 ISD::SRA, DL, VT, LHS,
4968 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4969 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4970 AddToWorklist(Shift.getNode());
4971 AddToWorklist(Add.getNode());
4972 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4976 // If the VSELECT result requires splitting and the mask is provided by a
4977 // SETCC, then split both nodes and its operands before legalization. This
4978 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4979 // and enables future optimizations (e.g. min/max pattern matching on X86).
4980 if (N0.getOpcode() == ISD::SETCC) {
4981 EVT VT = N->getValueType(0);
4983 // Check if any splitting is required.
4984 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4985 TargetLowering::TypeSplitVector)
4988 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4989 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4990 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4991 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4993 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4994 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4996 // Add the new VSELECT nodes to the work list in case they need to be split
4998 AddToWorklist(Lo.getNode());
4999 AddToWorklist(Hi.getNode());
5001 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5004 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5005 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5007 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5008 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5011 // The ConvertSelectToConcatVector function is assuming both the above
5012 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5014 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5015 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5016 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5017 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5025 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5026 SDValue N0 = N->getOperand(0);
5027 SDValue N1 = N->getOperand(1);
5028 SDValue N2 = N->getOperand(2);
5029 SDValue N3 = N->getOperand(3);
5030 SDValue N4 = N->getOperand(4);
5031 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5033 // fold select_cc lhs, rhs, x, x, cc -> x
5037 // Determine if the condition we're dealing with is constant
5038 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5039 N0, N1, CC, SDLoc(N), false);
5040 if (SCC.getNode()) {
5041 AddToWorklist(SCC.getNode());
5043 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5044 if (!SCCC->isNullValue())
5045 return N2; // cond always true -> true val
5047 return N3; // cond always false -> false val
5050 // Fold to a simpler select_cc
5051 if (SCC.getOpcode() == ISD::SETCC)
5052 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5053 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5057 // If we can fold this based on the true/false value, do so.
5058 if (SimplifySelectOps(N, N2, N3))
5059 return SDValue(N, 0); // Don't revisit N.
5061 // fold select_cc into other things, such as min/max/abs
5062 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5065 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5066 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5067 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5071 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5072 // dag node into a ConstantSDNode or a build_vector of constants.
5073 // This function is called by the DAGCombiner when visiting sext/zext/aext
5074 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5075 // Vector extends are not folded if operations are legal; this is to
5076 // avoid introducing illegal build_vector dag nodes.
5077 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5078 SelectionDAG &DAG, bool LegalTypes,
5079 bool LegalOperations) {
5080 unsigned Opcode = N->getOpcode();
5081 SDValue N0 = N->getOperand(0);
5082 EVT VT = N->getValueType(0);
5084 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5085 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5087 // fold (sext c1) -> c1
5088 // fold (zext c1) -> c1
5089 // fold (aext c1) -> c1
5090 if (isa<ConstantSDNode>(N0))
5091 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5093 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5094 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5095 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5096 EVT SVT = VT.getScalarType();
5097 if (!(VT.isVector() &&
5098 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5099 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5102 // We can fold this node into a build_vector.
5103 unsigned VTBits = SVT.getSizeInBits();
5104 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5105 unsigned ShAmt = VTBits - EVTBits;
5106 SmallVector<SDValue, 8> Elts;
5107 unsigned NumElts = N0->getNumOperands();
5110 for (unsigned i=0; i != NumElts; ++i) {
5111 SDValue Op = N0->getOperand(i);
5112 if (Op->getOpcode() == ISD::UNDEF) {
5113 Elts.push_back(DAG.getUNDEF(SVT));
5117 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5118 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5119 if (Opcode == ISD::SIGN_EXTEND)
5120 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5123 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5127 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5130 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5131 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5132 // transformation. Returns true if extension are possible and the above
5133 // mentioned transformation is profitable.
5134 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5136 SmallVectorImpl<SDNode *> &ExtendNodes,
5137 const TargetLowering &TLI) {
5138 bool HasCopyToRegUses = false;
5139 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5140 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5141 UE = N0.getNode()->use_end();
5146 if (UI.getUse().getResNo() != N0.getResNo())
5148 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5149 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5150 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5151 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5152 // Sign bits will be lost after a zext.
5155 for (unsigned i = 0; i != 2; ++i) {
5156 SDValue UseOp = User->getOperand(i);
5159 if (!isa<ConstantSDNode>(UseOp))
5164 ExtendNodes.push_back(User);
5167 // If truncates aren't free and there are users we can't
5168 // extend, it isn't worthwhile.
5171 // Remember if this value is live-out.
5172 if (User->getOpcode() == ISD::CopyToReg)
5173 HasCopyToRegUses = true;
5176 if (HasCopyToRegUses) {
5177 bool BothLiveOut = false;
5178 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5180 SDUse &Use = UI.getUse();
5181 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5187 // Both unextended and extended values are live out. There had better be
5188 // a good reason for the transformation.
5189 return ExtendNodes.size();
5194 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5195 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5196 ISD::NodeType ExtType) {
5197 // Extend SetCC uses if necessary.
5198 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5199 SDNode *SetCC = SetCCs[i];
5200 SmallVector<SDValue, 4> Ops;
5202 for (unsigned j = 0; j != 2; ++j) {
5203 SDValue SOp = SetCC->getOperand(j);
5205 Ops.push_back(ExtLoad);
5207 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5210 Ops.push_back(SetCC->getOperand(2));
5211 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5215 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5216 SDValue N0 = N->getOperand(0);
5217 EVT VT = N->getValueType(0);
5219 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5221 return SDValue(Res, 0);
5223 // fold (sext (sext x)) -> (sext x)
5224 // fold (sext (aext x)) -> (sext x)
5225 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5226 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5229 if (N0.getOpcode() == ISD::TRUNCATE) {
5230 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5231 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5232 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5233 if (NarrowLoad.getNode()) {
5234 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5235 if (NarrowLoad.getNode() != N0.getNode()) {
5236 CombineTo(N0.getNode(), NarrowLoad);
5237 // CombineTo deleted the truncate, if needed, but not what's under it.
5240 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5243 // See if the value being truncated is already sign extended. If so, just
5244 // eliminate the trunc/sext pair.
5245 SDValue Op = N0.getOperand(0);
5246 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5247 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5248 unsigned DestBits = VT.getScalarType().getSizeInBits();
5249 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5251 if (OpBits == DestBits) {
5252 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5253 // bits, it is already ready.
5254 if (NumSignBits > DestBits-MidBits)
5256 } else if (OpBits < DestBits) {
5257 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5258 // bits, just sext from i32.
5259 if (NumSignBits > OpBits-MidBits)
5260 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5262 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5263 // bits, just truncate to i32.
5264 if (NumSignBits > OpBits-MidBits)
5265 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5268 // fold (sext (truncate x)) -> (sextinreg x).
5269 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5270 N0.getValueType())) {
5271 if (OpBits < DestBits)
5272 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5273 else if (OpBits > DestBits)
5274 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5275 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5276 DAG.getValueType(N0.getValueType()));
5280 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5281 // None of the supported targets knows how to perform load and sign extend
5282 // on vectors in one instruction. We only perform this transformation on
5284 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5285 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5286 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5287 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5288 bool DoXform = true;
5289 SmallVector<SDNode*, 4> SetCCs;
5290 if (!N0.hasOneUse())
5291 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5293 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5294 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5296 LN0->getBasePtr(), N0.getValueType(),
5297 LN0->getMemOperand());
5298 CombineTo(N, ExtLoad);
5299 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5300 N0.getValueType(), ExtLoad);
5301 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5302 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5304 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5308 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5309 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5310 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5311 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5312 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5313 EVT MemVT = LN0->getMemoryVT();
5314 if ((!LegalOperations && !LN0->isVolatile()) ||
5315 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5316 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5318 LN0->getBasePtr(), MemVT,
5319 LN0->getMemOperand());
5320 CombineTo(N, ExtLoad);
5321 CombineTo(N0.getNode(),
5322 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5323 N0.getValueType(), ExtLoad),
5324 ExtLoad.getValue(1));
5325 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5329 // fold (sext (and/or/xor (load x), cst)) ->
5330 // (and/or/xor (sextload x), (sext cst))
5331 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5332 N0.getOpcode() == ISD::XOR) &&
5333 isa<LoadSDNode>(N0.getOperand(0)) &&
5334 N0.getOperand(1).getOpcode() == ISD::Constant &&
5335 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5336 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5337 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5338 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5339 bool DoXform = true;
5340 SmallVector<SDNode*, 4> SetCCs;
5341 if (!N0.hasOneUse())
5342 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5345 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5346 LN0->getChain(), LN0->getBasePtr(),
5348 LN0->getMemOperand());
5349 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5350 Mask = Mask.sext(VT.getSizeInBits());
5351 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5352 ExtLoad, DAG.getConstant(Mask, VT));
5353 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5354 SDLoc(N0.getOperand(0)),
5355 N0.getOperand(0).getValueType(), ExtLoad);
5357 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5358 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5360 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5365 if (N0.getOpcode() == ISD::SETCC) {
5366 EVT N0VT = N0.getOperand(0).getValueType();
5367 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5368 // Only do this before legalize for now.
5369 if (VT.isVector() && !LegalOperations &&
5370 TLI.getBooleanContents(N0VT) ==
5371 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5372 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5373 // of the same size as the compared operands. Only optimize sext(setcc())
5374 // if this is the case.
5375 EVT SVT = getSetCCResultType(N0VT);
5377 // We know that the # elements of the results is the same as the
5378 // # elements of the compare (and the # elements of the compare result
5379 // for that matter). Check to see that they are the same size. If so,
5380 // we know that the element size of the sext'd result matches the
5381 // element size of the compare operands.
5382 if (VT.getSizeInBits() == SVT.getSizeInBits())
5383 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5385 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5387 // If the desired elements are smaller or larger than the source
5388 // elements we can use a matching integer vector type and then
5389 // truncate/sign extend
5390 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5391 if (SVT == MatchingVectorType) {
5392 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5393 N0.getOperand(0), N0.getOperand(1),
5394 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5395 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5399 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5400 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5402 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5404 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5405 NegOne, DAG.getConstant(0, VT),
5406 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5407 if (SCC.getNode()) return SCC;
5409 if (!VT.isVector()) {
5410 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5411 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5413 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5414 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5415 N0.getOperand(0), N0.getOperand(1), CC);
5416 return DAG.getSelect(DL, VT, SetCC,
5417 NegOne, DAG.getConstant(0, VT));
5422 // fold (sext x) -> (zext x) if the sign bit is known zero.
5423 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5424 DAG.SignBitIsZero(N0))
5425 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5430 // isTruncateOf - If N is a truncate of some other value, return true, record
5431 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5432 // This function computes KnownZero to avoid a duplicated call to
5433 // computeKnownBits in the caller.
5434 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5437 if (N->getOpcode() == ISD::TRUNCATE) {
5438 Op = N->getOperand(0);
5439 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5443 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5444 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5447 SDValue Op0 = N->getOperand(0);
5448 SDValue Op1 = N->getOperand(1);
5449 assert(Op0.getValueType() == Op1.getValueType());
5451 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5452 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5453 if (COp0 && COp0->isNullValue())
5455 else if (COp1 && COp1->isNullValue())
5460 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5462 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5468 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5469 SDValue N0 = N->getOperand(0);
5470 EVT VT = N->getValueType(0);
5472 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5474 return SDValue(Res, 0);
5476 // fold (zext (zext x)) -> (zext x)
5477 // fold (zext (aext x)) -> (zext x)
5478 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5479 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5482 // fold (zext (truncate x)) -> (zext x) or
5483 // (zext (truncate x)) -> (truncate x)
5484 // This is valid when the truncated bits of x are already zero.
5485 // FIXME: We should extend this to work for vectors too.
5488 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5489 APInt TruncatedBits =
5490 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5491 APInt(Op.getValueSizeInBits(), 0) :
5492 APInt::getBitsSet(Op.getValueSizeInBits(),
5493 N0.getValueSizeInBits(),
5494 std::min(Op.getValueSizeInBits(),
5495 VT.getSizeInBits()));
5496 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5497 if (VT.bitsGT(Op.getValueType()))
5498 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5499 if (VT.bitsLT(Op.getValueType()))
5500 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5506 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5507 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5508 if (N0.getOpcode() == ISD::TRUNCATE) {
5509 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5510 if (NarrowLoad.getNode()) {
5511 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5512 if (NarrowLoad.getNode() != N0.getNode()) {
5513 CombineTo(N0.getNode(), NarrowLoad);
5514 // CombineTo deleted the truncate, if needed, but not what's under it.
5517 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5521 // fold (zext (truncate x)) -> (and x, mask)
5522 if (N0.getOpcode() == ISD::TRUNCATE &&
5523 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5525 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5526 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5527 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5528 if (NarrowLoad.getNode()) {
5529 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5530 if (NarrowLoad.getNode() != N0.getNode()) {
5531 CombineTo(N0.getNode(), NarrowLoad);
5532 // CombineTo deleted the truncate, if needed, but not what's under it.
5535 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5538 SDValue Op = N0.getOperand(0);
5539 if (Op.getValueType().bitsLT(VT)) {
5540 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5541 AddToWorklist(Op.getNode());
5542 } else if (Op.getValueType().bitsGT(VT)) {
5543 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5544 AddToWorklist(Op.getNode());
5546 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5547 N0.getValueType().getScalarType());
5550 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5551 // if either of the casts is not free.
5552 if (N0.getOpcode() == ISD::AND &&
5553 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5554 N0.getOperand(1).getOpcode() == ISD::Constant &&
5555 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5556 N0.getValueType()) ||
5557 !TLI.isZExtFree(N0.getValueType(), VT))) {
5558 SDValue X = N0.getOperand(0).getOperand(0);
5559 if (X.getValueType().bitsLT(VT)) {
5560 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5561 } else if (X.getValueType().bitsGT(VT)) {
5562 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5564 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5565 Mask = Mask.zext(VT.getSizeInBits());
5566 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5567 X, DAG.getConstant(Mask, VT));
5570 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5571 // None of the supported targets knows how to perform load and vector_zext
5572 // on vectors in one instruction. We only perform this transformation on
5574 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5575 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5576 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5577 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5578 bool DoXform = true;
5579 SmallVector<SDNode*, 4> SetCCs;
5580 if (!N0.hasOneUse())
5581 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5583 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5584 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5586 LN0->getBasePtr(), N0.getValueType(),
5587 LN0->getMemOperand());
5588 CombineTo(N, ExtLoad);
5589 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5590 N0.getValueType(), ExtLoad);
5591 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5593 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5595 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5599 // fold (zext (and/or/xor (load x), cst)) ->
5600 // (and/or/xor (zextload x), (zext cst))
5601 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5602 N0.getOpcode() == ISD::XOR) &&
5603 isa<LoadSDNode>(N0.getOperand(0)) &&
5604 N0.getOperand(1).getOpcode() == ISD::Constant &&
5605 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5606 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5607 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5608 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5609 bool DoXform = true;
5610 SmallVector<SDNode*, 4> SetCCs;
5611 if (!N0.hasOneUse())
5612 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5615 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5616 LN0->getChain(), LN0->getBasePtr(),
5618 LN0->getMemOperand());
5619 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5620 Mask = Mask.zext(VT.getSizeInBits());
5621 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5622 ExtLoad, DAG.getConstant(Mask, VT));
5623 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5624 SDLoc(N0.getOperand(0)),
5625 N0.getOperand(0).getValueType(), ExtLoad);
5627 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5628 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5630 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5635 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5636 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5637 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5638 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5639 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5640 EVT MemVT = LN0->getMemoryVT();
5641 if ((!LegalOperations && !LN0->isVolatile()) ||
5642 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5643 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5645 LN0->getBasePtr(), MemVT,
5646 LN0->getMemOperand());
5647 CombineTo(N, ExtLoad);
5648 CombineTo(N0.getNode(),
5649 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5651 ExtLoad.getValue(1));
5652 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5656 if (N0.getOpcode() == ISD::SETCC) {
5657 if (!LegalOperations && VT.isVector() &&
5658 N0.getValueType().getVectorElementType() == MVT::i1) {
5659 EVT N0VT = N0.getOperand(0).getValueType();
5660 if (getSetCCResultType(N0VT) == N0.getValueType())
5663 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5664 // Only do this before legalize for now.
5665 EVT EltVT = VT.getVectorElementType();
5666 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5667 DAG.getConstant(1, EltVT));
5668 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5669 // We know that the # elements of the results is the same as the
5670 // # elements of the compare (and the # elements of the compare result
5671 // for that matter). Check to see that they are the same size. If so,
5672 // we know that the element size of the sext'd result matches the
5673 // element size of the compare operands.
5674 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5675 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5677 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5678 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5681 // If the desired elements are smaller or larger than the source
5682 // elements we can use a matching integer vector type and then
5683 // truncate/sign extend
5684 EVT MatchingElementType =
5685 EVT::getIntegerVT(*DAG.getContext(),
5686 N0VT.getScalarType().getSizeInBits());
5687 EVT MatchingVectorType =
5688 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5689 N0VT.getVectorNumElements());
5691 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5693 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5694 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5695 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5696 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5699 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5701 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5702 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5703 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5704 if (SCC.getNode()) return SCC;
5707 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5708 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5709 isa<ConstantSDNode>(N0.getOperand(1)) &&
5710 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5712 SDValue ShAmt = N0.getOperand(1);
5713 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5714 if (N0.getOpcode() == ISD::SHL) {
5715 SDValue InnerZExt = N0.getOperand(0);
5716 // If the original shl may be shifting out bits, do not perform this
5718 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5719 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5720 if (ShAmtVal > KnownZeroBits)
5726 // Ensure that the shift amount is wide enough for the shifted value.
5727 if (VT.getSizeInBits() >= 256)
5728 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5730 return DAG.getNode(N0.getOpcode(), DL, VT,
5731 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5738 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5739 SDValue N0 = N->getOperand(0);
5740 EVT VT = N->getValueType(0);
5742 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5744 return SDValue(Res, 0);
5746 // fold (aext (aext x)) -> (aext x)
5747 // fold (aext (zext x)) -> (zext x)
5748 // fold (aext (sext x)) -> (sext x)
5749 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5750 N0.getOpcode() == ISD::ZERO_EXTEND ||
5751 N0.getOpcode() == ISD::SIGN_EXTEND)
5752 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5754 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5755 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5756 if (N0.getOpcode() == ISD::TRUNCATE) {
5757 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5758 if (NarrowLoad.getNode()) {
5759 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5760 if (NarrowLoad.getNode() != N0.getNode()) {
5761 CombineTo(N0.getNode(), NarrowLoad);
5762 // CombineTo deleted the truncate, if needed, but not what's under it.
5765 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5769 // fold (aext (truncate x))
5770 if (N0.getOpcode() == ISD::TRUNCATE) {
5771 SDValue TruncOp = N0.getOperand(0);
5772 if (TruncOp.getValueType() == VT)
5773 return TruncOp; // x iff x size == zext size.
5774 if (TruncOp.getValueType().bitsGT(VT))
5775 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5776 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5779 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5780 // if the trunc is not free.
5781 if (N0.getOpcode() == ISD::AND &&
5782 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5783 N0.getOperand(1).getOpcode() == ISD::Constant &&
5784 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5785 N0.getValueType())) {
5786 SDValue X = N0.getOperand(0).getOperand(0);
5787 if (X.getValueType().bitsLT(VT)) {
5788 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5789 } else if (X.getValueType().bitsGT(VT)) {
5790 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5792 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5793 Mask = Mask.zext(VT.getSizeInBits());
5794 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5795 X, DAG.getConstant(Mask, VT));
5798 // fold (aext (load x)) -> (aext (truncate (extload x)))
5799 // None of the supported targets knows how to perform load and any_ext
5800 // on vectors in one instruction. We only perform this transformation on
5802 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5803 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5804 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
5805 bool DoXform = true;
5806 SmallVector<SDNode*, 4> SetCCs;
5807 if (!N0.hasOneUse())
5808 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5810 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5811 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5813 LN0->getBasePtr(), N0.getValueType(),
5814 LN0->getMemOperand());
5815 CombineTo(N, ExtLoad);
5816 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5817 N0.getValueType(), ExtLoad);
5818 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5819 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5821 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5825 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5826 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5827 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5828 if (N0.getOpcode() == ISD::LOAD &&
5829 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5831 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5832 ISD::LoadExtType ExtType = LN0->getExtensionType();
5833 EVT MemVT = LN0->getMemoryVT();
5834 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
5835 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5836 VT, LN0->getChain(), LN0->getBasePtr(),
5837 MemVT, LN0->getMemOperand());
5838 CombineTo(N, ExtLoad);
5839 CombineTo(N0.getNode(),
5840 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5841 N0.getValueType(), ExtLoad),
5842 ExtLoad.getValue(1));
5843 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5847 if (N0.getOpcode() == ISD::SETCC) {
5849 // aext(setcc) -> vsetcc
5850 // aext(setcc) -> truncate(vsetcc)
5851 // aext(setcc) -> aext(vsetcc)
5852 // Only do this before legalize for now.
5853 if (VT.isVector() && !LegalOperations) {
5854 EVT N0VT = N0.getOperand(0).getValueType();
5855 // We know that the # elements of the results is the same as the
5856 // # elements of the compare (and the # elements of the compare result
5857 // for that matter). Check to see that they are the same size. If so,
5858 // we know that the element size of the sext'd result matches the
5859 // element size of the compare operands.
5860 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5861 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5863 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5864 // If the desired elements are smaller or larger than the source
5865 // elements we can use a matching integer vector type and then
5866 // truncate/any extend
5868 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5870 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5872 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5873 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5877 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5879 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5880 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5881 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5889 /// See if the specified operand can be simplified with the knowledge that only
5890 /// the bits specified by Mask are used. If so, return the simpler operand,
5891 /// otherwise return a null SDValue.
5892 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5893 switch (V.getOpcode()) {
5895 case ISD::Constant: {
5896 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5897 assert(CV && "Const value should be ConstSDNode.");
5898 const APInt &CVal = CV->getAPIntValue();
5899 APInt NewVal = CVal & Mask;
5901 return DAG.getConstant(NewVal, V.getValueType());
5906 // If the LHS or RHS don't contribute bits to the or, drop them.
5907 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5908 return V.getOperand(1);
5909 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5910 return V.getOperand(0);
5913 // Only look at single-use SRLs.
5914 if (!V.getNode()->hasOneUse())
5916 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5917 // See if we can recursively simplify the LHS.
5918 unsigned Amt = RHSC->getZExtValue();
5920 // Watch out for shift count overflow though.
5921 if (Amt >= Mask.getBitWidth()) break;
5922 APInt NewMask = Mask << Amt;
5923 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5924 if (SimplifyLHS.getNode())
5925 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5926 SimplifyLHS, V.getOperand(1));
5932 /// If the result of a wider load is shifted to right of N bits and then
5933 /// truncated to a narrower type and where N is a multiple of number of bits of
5934 /// the narrower type, transform it to a narrower load from address + N / num of
5935 /// bits of new type. If the result is to be extended, also fold the extension
5936 /// to form a extending load.
5937 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5938 unsigned Opc = N->getOpcode();
5940 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5941 SDValue N0 = N->getOperand(0);
5942 EVT VT = N->getValueType(0);
5945 // This transformation isn't valid for vector loads.
5949 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5951 if (Opc == ISD::SIGN_EXTEND_INREG) {
5952 ExtType = ISD::SEXTLOAD;
5953 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5954 } else if (Opc == ISD::SRL) {
5955 // Another special-case: SRL is basically zero-extending a narrower value.
5956 ExtType = ISD::ZEXTLOAD;
5958 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5959 if (!N01) return SDValue();
5960 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5961 VT.getSizeInBits() - N01->getZExtValue());
5963 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
5966 unsigned EVTBits = ExtVT.getSizeInBits();
5968 // Do not generate loads of non-round integer types since these can
5969 // be expensive (and would be wrong if the type is not byte sized).
5970 if (!ExtVT.isRound())
5974 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5975 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5976 ShAmt = N01->getZExtValue();
5977 // Is the shift amount a multiple of size of VT?
5978 if ((ShAmt & (EVTBits-1)) == 0) {
5979 N0 = N0.getOperand(0);
5980 // Is the load width a multiple of size of VT?
5981 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5985 // At this point, we must have a load or else we can't do the transform.
5986 if (!isa<LoadSDNode>(N0)) return SDValue();
5988 // Because a SRL must be assumed to *need* to zero-extend the high bits
5989 // (as opposed to anyext the high bits), we can't combine the zextload
5990 // lowering of SRL and an sextload.
5991 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5994 // If the shift amount is larger than the input type then we're not
5995 // accessing any of the loaded bytes. If the load was a zextload/extload
5996 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5997 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6002 // If the load is shifted left (and the result isn't shifted back right),
6003 // we can fold the truncate through the shift.
6004 unsigned ShLeftAmt = 0;
6005 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6006 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6007 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6008 ShLeftAmt = N01->getZExtValue();
6009 N0 = N0.getOperand(0);
6013 // If we haven't found a load, we can't narrow it. Don't transform one with
6014 // multiple uses, this would require adding a new load.
6015 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6018 // Don't change the width of a volatile load.
6019 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6020 if (LN0->isVolatile())
6023 // Verify that we are actually reducing a load width here.
6024 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6027 // For the transform to be legal, the load must produce only two values
6028 // (the value loaded and the chain). Don't transform a pre-increment
6029 // load, for example, which produces an extra value. Otherwise the
6030 // transformation is not equivalent, and the downstream logic to replace
6031 // uses gets things wrong.
6032 if (LN0->getNumValues() > 2)
6035 // If the load that we're shrinking is an extload and we're not just
6036 // discarding the extension we can't simply shrink the load. Bail.
6037 // TODO: It would be possible to merge the extensions in some cases.
6038 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6039 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6042 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6045 EVT PtrType = N0.getOperand(1).getValueType();
6047 if (PtrType == MVT::Untyped || PtrType.isExtended())
6048 // It's not possible to generate a constant of extended or untyped type.
6051 // For big endian targets, we need to adjust the offset to the pointer to
6052 // load the correct bytes.
6053 if (TLI.isBigEndian()) {
6054 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6055 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6056 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6059 uint64_t PtrOff = ShAmt / 8;
6060 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6061 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6062 PtrType, LN0->getBasePtr(),
6063 DAG.getConstant(PtrOff, PtrType));
6064 AddToWorklist(NewPtr.getNode());
6067 if (ExtType == ISD::NON_EXTLOAD)
6068 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6069 LN0->getPointerInfo().getWithOffset(PtrOff),
6070 LN0->isVolatile(), LN0->isNonTemporal(),
6071 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6073 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6074 LN0->getPointerInfo().getWithOffset(PtrOff),
6075 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6076 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6078 // Replace the old load's chain with the new load's chain.
6079 WorklistRemover DeadNodes(*this);
6080 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6082 // Shift the result left, if we've swallowed a left shift.
6083 SDValue Result = Load;
6084 if (ShLeftAmt != 0) {
6085 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6086 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6088 // If the shift amount is as large as the result size (but, presumably,
6089 // no larger than the source) then the useful bits of the result are
6090 // zero; we can't simply return the shortened shift, because the result
6091 // of that operation is undefined.
6092 if (ShLeftAmt >= VT.getSizeInBits())
6093 Result = DAG.getConstant(0, VT);
6095 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6096 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6099 // Return the new loaded value.
6103 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6104 SDValue N0 = N->getOperand(0);
6105 SDValue N1 = N->getOperand(1);
6106 EVT VT = N->getValueType(0);
6107 EVT EVT = cast<VTSDNode>(N1)->getVT();
6108 unsigned VTBits = VT.getScalarType().getSizeInBits();
6109 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6111 // fold (sext_in_reg c1) -> c1
6112 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6113 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6115 // If the input is already sign extended, just drop the extension.
6116 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6119 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6120 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6121 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6122 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6123 N0.getOperand(0), N1);
6125 // fold (sext_in_reg (sext x)) -> (sext x)
6126 // fold (sext_in_reg (aext x)) -> (sext x)
6127 // if x is small enough.
6128 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6129 SDValue N00 = N0.getOperand(0);
6130 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6131 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6132 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6135 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6136 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6137 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6139 // fold operands of sext_in_reg based on knowledge that the top bits are not
6141 if (SimplifyDemandedBits(SDValue(N, 0)))
6142 return SDValue(N, 0);
6144 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6145 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6146 SDValue NarrowLoad = ReduceLoadWidth(N);
6147 if (NarrowLoad.getNode())
6150 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6151 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6152 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6153 if (N0.getOpcode() == ISD::SRL) {
6154 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6155 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6156 // We can turn this into an SRA iff the input to the SRL is already sign
6158 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6159 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6160 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6161 N0.getOperand(0), N0.getOperand(1));
6165 // fold (sext_inreg (extload x)) -> (sextload x)
6166 if (ISD::isEXTLoad(N0.getNode()) &&
6167 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6168 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6169 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6170 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6171 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6172 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6174 LN0->getBasePtr(), EVT,
6175 LN0->getMemOperand());
6176 CombineTo(N, ExtLoad);
6177 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6178 AddToWorklist(ExtLoad.getNode());
6179 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6181 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6182 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6184 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6185 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6186 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6187 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6188 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6190 LN0->getBasePtr(), EVT,
6191 LN0->getMemOperand());
6192 CombineTo(N, ExtLoad);
6193 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6194 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6197 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6198 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6199 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6200 N0.getOperand(1), false);
6201 if (BSwap.getNode())
6202 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6206 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6207 // into a build_vector.
6208 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6209 SmallVector<SDValue, 8> Elts;
6210 unsigned NumElts = N0->getNumOperands();
6211 unsigned ShAmt = VTBits - EVTBits;
6213 for (unsigned i = 0; i != NumElts; ++i) {
6214 SDValue Op = N0->getOperand(i);
6215 if (Op->getOpcode() == ISD::UNDEF) {
6220 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6221 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6222 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6223 Op.getValueType()));
6226 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6232 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6233 SDValue N0 = N->getOperand(0);
6234 EVT VT = N->getValueType(0);
6235 bool isLE = TLI.isLittleEndian();
6238 if (N0.getValueType() == N->getValueType(0))
6240 // fold (truncate c1) -> c1
6241 if (isa<ConstantSDNode>(N0))
6242 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6243 // fold (truncate (truncate x)) -> (truncate x)
6244 if (N0.getOpcode() == ISD::TRUNCATE)
6245 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6246 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6247 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6248 N0.getOpcode() == ISD::SIGN_EXTEND ||
6249 N0.getOpcode() == ISD::ANY_EXTEND) {
6250 if (N0.getOperand(0).getValueType().bitsLT(VT))
6251 // if the source is smaller than the dest, we still need an extend
6252 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6254 if (N0.getOperand(0).getValueType().bitsGT(VT))
6255 // if the source is larger than the dest, than we just need the truncate
6256 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6257 // if the source and dest are the same type, we can drop both the extend
6258 // and the truncate.
6259 return N0.getOperand(0);
6262 // Fold extract-and-trunc into a narrow extract. For example:
6263 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6264 // i32 y = TRUNCATE(i64 x)
6266 // v16i8 b = BITCAST (v2i64 val)
6267 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6269 // Note: We only run this optimization after type legalization (which often
6270 // creates this pattern) and before operation legalization after which
6271 // we need to be more careful about the vector instructions that we generate.
6272 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6273 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6275 EVT VecTy = N0.getOperand(0).getValueType();
6276 EVT ExTy = N0.getValueType();
6277 EVT TrTy = N->getValueType(0);
6279 unsigned NumElem = VecTy.getVectorNumElements();
6280 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6282 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6283 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6285 SDValue EltNo = N0->getOperand(1);
6286 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6287 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6288 EVT IndexTy = TLI.getVectorIdxTy();
6289 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6291 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6292 NVT, N0.getOperand(0));
6294 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6296 DAG.getConstant(Index, IndexTy));
6300 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6301 if (N0.getOpcode() == ISD::SELECT) {
6302 EVT SrcVT = N0.getValueType();
6303 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6304 TLI.isTruncateFree(SrcVT, VT)) {
6306 SDValue Cond = N0.getOperand(0);
6307 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6308 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6309 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6313 // Fold a series of buildvector, bitcast, and truncate if possible.
6315 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6316 // (2xi32 (buildvector x, y)).
6317 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6318 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6319 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6320 N0.getOperand(0).hasOneUse()) {
6322 SDValue BuildVect = N0.getOperand(0);
6323 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6324 EVT TruncVecEltTy = VT.getVectorElementType();
6326 // Check that the element types match.
6327 if (BuildVectEltTy == TruncVecEltTy) {
6328 // Now we only need to compute the offset of the truncated elements.
6329 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6330 unsigned TruncVecNumElts = VT.getVectorNumElements();
6331 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6333 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6334 "Invalid number of elements");
6336 SmallVector<SDValue, 8> Opnds;
6337 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6338 Opnds.push_back(BuildVect.getOperand(i));
6340 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6344 // See if we can simplify the input to this truncate through knowledge that
6345 // only the low bits are being used.
6346 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6347 // Currently we only perform this optimization on scalars because vectors
6348 // may have different active low bits.
6349 if (!VT.isVector()) {
6351 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6352 VT.getSizeInBits()));
6353 if (Shorter.getNode())
6354 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6356 // fold (truncate (load x)) -> (smaller load x)
6357 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6358 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6359 SDValue Reduced = ReduceLoadWidth(N);
6360 if (Reduced.getNode())
6362 // Handle the case where the load remains an extending load even
6363 // after truncation.
6364 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6365 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6366 if (!LN0->isVolatile() &&
6367 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6368 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6369 VT, LN0->getChain(), LN0->getBasePtr(),
6371 LN0->getMemOperand());
6372 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6377 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6378 // where ... are all 'undef'.
6379 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6380 SmallVector<EVT, 8> VTs;
6383 unsigned NumDefs = 0;
6385 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6386 SDValue X = N0.getOperand(i);
6387 if (X.getOpcode() != ISD::UNDEF) {
6392 // Stop if more than one members are non-undef.
6395 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6396 VT.getVectorElementType(),
6397 X.getValueType().getVectorNumElements()));
6401 return DAG.getUNDEF(VT);
6404 assert(V.getNode() && "The single defined operand is empty!");
6405 SmallVector<SDValue, 8> Opnds;
6406 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6408 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6411 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6412 AddToWorklist(NV.getNode());
6413 Opnds.push_back(NV);
6415 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6419 // Simplify the operands using demanded-bits information.
6420 if (!VT.isVector() &&
6421 SimplifyDemandedBits(SDValue(N, 0)))
6422 return SDValue(N, 0);
6427 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6428 SDValue Elt = N->getOperand(i);
6429 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6430 return Elt.getNode();
6431 return Elt.getOperand(Elt.getResNo()).getNode();
6434 /// build_pair (load, load) -> load
6435 /// if load locations are consecutive.
6436 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6437 assert(N->getOpcode() == ISD::BUILD_PAIR);
6439 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6440 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6441 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6442 LD1->getAddressSpace() != LD2->getAddressSpace())
6444 EVT LD1VT = LD1->getValueType(0);
6446 if (ISD::isNON_EXTLoad(LD2) &&
6448 // If both are volatile this would reduce the number of volatile loads.
6449 // If one is volatile it might be ok, but play conservative and bail out.
6450 !LD1->isVolatile() &&
6451 !LD2->isVolatile() &&
6452 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6453 unsigned Align = LD1->getAlignment();
6454 unsigned NewAlign = TLI.getDataLayout()->
6455 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6457 if (NewAlign <= Align &&
6458 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6459 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6460 LD1->getBasePtr(), LD1->getPointerInfo(),
6461 false, false, false, Align);
6467 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6468 SDValue N0 = N->getOperand(0);
6469 EVT VT = N->getValueType(0);
6471 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6472 // Only do this before legalize, since afterward the target may be depending
6473 // on the bitconvert.
6474 // First check to see if this is all constant.
6476 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6478 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6480 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6481 assert(!DestEltVT.isVector() &&
6482 "Element type of vector ValueType must not be vector!");
6484 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6487 // If the input is a constant, let getNode fold it.
6488 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6489 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6490 if (Res.getNode() != N) {
6491 if (!LegalOperations ||
6492 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6495 // Folding it resulted in an illegal node, and it's too late to
6496 // do that. Clean up the old node and forego the transformation.
6497 // Ideally this won't happen very often, because instcombine
6498 // and the earlier dagcombine runs (where illegal nodes are
6499 // permitted) should have folded most of them already.
6500 deleteAndRecombine(Res.getNode());
6504 // (conv (conv x, t1), t2) -> (conv x, t2)
6505 if (N0.getOpcode() == ISD::BITCAST)
6506 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6509 // fold (conv (load x)) -> (load (conv*)x)
6510 // If the resultant load doesn't need a higher alignment than the original!
6511 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6512 // Do not change the width of a volatile load.
6513 !cast<LoadSDNode>(N0)->isVolatile() &&
6514 // Do not remove the cast if the types differ in endian layout.
6515 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6516 TLI.hasBigEndianPartOrdering(VT) &&
6517 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6518 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6519 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6520 unsigned Align = TLI.getDataLayout()->
6521 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6522 unsigned OrigAlign = LN0->getAlignment();
6524 if (Align <= OrigAlign) {
6525 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6526 LN0->getBasePtr(), LN0->getPointerInfo(),
6527 LN0->isVolatile(), LN0->isNonTemporal(),
6528 LN0->isInvariant(), OrigAlign,
6530 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6535 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6536 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6537 // This often reduces constant pool loads.
6538 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6539 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6540 N0.getNode()->hasOneUse() && VT.isInteger() &&
6541 !VT.isVector() && !N0.getValueType().isVector()) {
6542 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6544 AddToWorklist(NewConv.getNode());
6546 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6547 if (N0.getOpcode() == ISD::FNEG)
6548 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6549 NewConv, DAG.getConstant(SignBit, VT));
6550 assert(N0.getOpcode() == ISD::FABS);
6551 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6552 NewConv, DAG.getConstant(~SignBit, VT));
6555 // fold (bitconvert (fcopysign cst, x)) ->
6556 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6557 // Note that we don't handle (copysign x, cst) because this can always be
6558 // folded to an fneg or fabs.
6559 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6560 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6561 VT.isInteger() && !VT.isVector()) {
6562 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6563 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6564 if (isTypeLegal(IntXVT)) {
6565 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6566 IntXVT, N0.getOperand(1));
6567 AddToWorklist(X.getNode());
6569 // If X has a different width than the result/lhs, sext it or truncate it.
6570 unsigned VTWidth = VT.getSizeInBits();
6571 if (OrigXWidth < VTWidth) {
6572 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6573 AddToWorklist(X.getNode());
6574 } else if (OrigXWidth > VTWidth) {
6575 // To get the sign bit in the right place, we have to shift it right
6576 // before truncating.
6577 X = DAG.getNode(ISD::SRL, SDLoc(X),
6578 X.getValueType(), X,
6579 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6580 AddToWorklist(X.getNode());
6581 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6582 AddToWorklist(X.getNode());
6585 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6586 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6587 X, DAG.getConstant(SignBit, VT));
6588 AddToWorklist(X.getNode());
6590 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6591 VT, N0.getOperand(0));
6592 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6593 Cst, DAG.getConstant(~SignBit, VT));
6594 AddToWorklist(Cst.getNode());
6596 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6600 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6601 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6602 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6603 if (CombineLD.getNode())
6610 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6611 EVT VT = N->getValueType(0);
6612 return CombineConsecutiveLoads(N, VT);
6615 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6616 /// operands. DstEltVT indicates the destination element value type.
6617 SDValue DAGCombiner::
6618 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6619 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6621 // If this is already the right type, we're done.
6622 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6624 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6625 unsigned DstBitSize = DstEltVT.getSizeInBits();
6627 // If this is a conversion of N elements of one type to N elements of another
6628 // type, convert each element. This handles FP<->INT cases.
6629 if (SrcBitSize == DstBitSize) {
6630 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6631 BV->getValueType(0).getVectorNumElements());
6633 // Due to the FP element handling below calling this routine recursively,
6634 // we can end up with a scalar-to-vector node here.
6635 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6636 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6637 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6638 DstEltVT, BV->getOperand(0)));
6640 SmallVector<SDValue, 8> Ops;
6641 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6642 SDValue Op = BV->getOperand(i);
6643 // If the vector element type is not legal, the BUILD_VECTOR operands
6644 // are promoted and implicitly truncated. Make that explicit here.
6645 if (Op.getValueType() != SrcEltVT)
6646 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6647 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6649 AddToWorklist(Ops.back().getNode());
6651 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6654 // Otherwise, we're growing or shrinking the elements. To avoid having to
6655 // handle annoying details of growing/shrinking FP values, we convert them to
6657 if (SrcEltVT.isFloatingPoint()) {
6658 // Convert the input float vector to a int vector where the elements are the
6660 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6661 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6665 // Now we know the input is an integer vector. If the output is a FP type,
6666 // convert to integer first, then to FP of the right size.
6667 if (DstEltVT.isFloatingPoint()) {
6668 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6669 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6671 // Next, convert to FP elements of the same size.
6672 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6675 // Okay, we know the src/dst types are both integers of differing types.
6676 // Handling growing first.
6677 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6678 if (SrcBitSize < DstBitSize) {
6679 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6681 SmallVector<SDValue, 8> Ops;
6682 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6683 i += NumInputsPerOutput) {
6684 bool isLE = TLI.isLittleEndian();
6685 APInt NewBits = APInt(DstBitSize, 0);
6686 bool EltIsUndef = true;
6687 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6688 // Shift the previously computed bits over.
6689 NewBits <<= SrcBitSize;
6690 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6691 if (Op.getOpcode() == ISD::UNDEF) continue;
6694 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6695 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6699 Ops.push_back(DAG.getUNDEF(DstEltVT));
6701 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6704 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6705 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6708 // Finally, this must be the case where we are shrinking elements: each input
6709 // turns into multiple outputs.
6710 bool isS2V = ISD::isScalarToVector(BV);
6711 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6712 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6713 NumOutputsPerInput*BV->getNumOperands());
6714 SmallVector<SDValue, 8> Ops;
6716 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6717 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6718 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6719 Ops.push_back(DAG.getUNDEF(DstEltVT));
6723 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6724 getAPIntValue().zextOrTrunc(SrcBitSize);
6726 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6727 APInt ThisVal = OpVal.trunc(DstBitSize);
6728 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6729 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6730 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6731 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6733 OpVal = OpVal.lshr(DstBitSize);
6736 // For big endian targets, swap the order of the pieces of each element.
6737 if (TLI.isBigEndian())
6738 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6741 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6744 SDValue DAGCombiner::visitFADD(SDNode *N) {
6745 SDValue N0 = N->getOperand(0);
6746 SDValue N1 = N->getOperand(1);
6747 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6748 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6749 EVT VT = N->getValueType(0);
6750 const TargetOptions &Options = DAG.getTarget().Options;
6753 if (VT.isVector()) {
6754 SDValue FoldedVOp = SimplifyVBinOp(N);
6755 if (FoldedVOp.getNode()) return FoldedVOp;
6758 // fold (fadd c1, c2) -> c1 + c2
6760 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6762 // canonicalize constant to RHS
6763 if (N0CFP && !N1CFP)
6764 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6766 // fold (fadd A, (fneg B)) -> (fsub A, B)
6767 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6768 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6769 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6770 GetNegatedExpression(N1, DAG, LegalOperations));
6772 // fold (fadd (fneg A), B) -> (fsub B, A)
6773 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6774 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6775 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6776 GetNegatedExpression(N0, DAG, LegalOperations));
6778 // If 'unsafe math' is enabled, fold lots of things.
6779 if (Options.UnsafeFPMath) {
6780 // No FP constant should be created after legalization as Instruction
6781 // Selection pass has a hard time dealing with FP constants.
6782 bool AllowNewConst = (Level < AfterLegalizeDAG);
6784 // fold (fadd A, 0) -> A
6785 if (N1CFP && N1CFP->getValueAPF().isZero())
6788 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6789 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6790 isa<ConstantFPSDNode>(N0.getOperand(1)))
6791 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6792 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6793 N0.getOperand(1), N1));
6795 // If allowed, fold (fadd (fneg x), x) -> 0.0
6796 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6797 return DAG.getConstantFP(0.0, VT);
6799 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6800 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6801 return DAG.getConstantFP(0.0, VT);
6803 // We can fold chains of FADD's of the same value into multiplications.
6804 // This transform is not safe in general because we are reducing the number
6805 // of rounding steps.
6806 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6807 if (N0.getOpcode() == ISD::FMUL) {
6808 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6809 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6811 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6812 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6813 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6815 DAG.getConstantFP(1.0, VT));
6816 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6819 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6820 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6821 N1.getOperand(0) == N1.getOperand(1) &&
6822 N0.getOperand(0) == N1.getOperand(0)) {
6823 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6825 DAG.getConstantFP(2.0, VT));
6826 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6827 N0.getOperand(0), NewCFP);
6831 if (N1.getOpcode() == ISD::FMUL) {
6832 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6833 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6835 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6836 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6837 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6839 DAG.getConstantFP(1.0, VT));
6840 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6843 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6844 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6845 N0.getOperand(0) == N0.getOperand(1) &&
6846 N1.getOperand(0) == N0.getOperand(0)) {
6847 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6849 DAG.getConstantFP(2.0, VT));
6850 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6854 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6855 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6856 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6857 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6858 (N0.getOperand(0) == N1))
6859 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6860 N1, DAG.getConstantFP(3.0, VT));
6863 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6864 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6865 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6866 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6867 N1.getOperand(0) == N0)
6868 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6869 N0, DAG.getConstantFP(3.0, VT));
6872 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6873 if (AllowNewConst &&
6874 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6875 N0.getOperand(0) == N0.getOperand(1) &&
6876 N1.getOperand(0) == N1.getOperand(1) &&
6877 N0.getOperand(0) == N1.getOperand(0))
6878 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6879 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6881 } // enable-unsafe-fp-math
6883 // FADD -> FMA combines:
6884 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6885 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6886 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6888 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6889 if (N0.getOpcode() == ISD::FMUL &&
6890 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6891 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6892 N0.getOperand(0), N0.getOperand(1), N1);
6894 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6895 // Note: Commutes FADD operands.
6896 if (N1.getOpcode() == ISD::FMUL &&
6897 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6898 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6899 N1.getOperand(0), N1.getOperand(1), N0);
6901 // Remove FP_EXTEND when there is an opportunity to combine. This is
6902 // legal here since extra precision is allowed.
6904 // fold (fadd (fpext (fmul x, y)), z) -> (fma x, y, z)
6905 if (N0.getOpcode() == ISD::FP_EXTEND) {
6906 SDValue N00 = N0.getOperand(0);
6907 if (N00.getOpcode() == ISD::FMUL)
6908 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6909 N00.getOperand(0), N00.getOperand(1), N1);
6912 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma y, z, x)
6913 // Note: Commutes FADD operands.
6914 if (N1.getOpcode() == ISD::FP_EXTEND) {
6915 SDValue N10 = N1.getOperand(0);
6916 if (N10.getOpcode() == ISD::FMUL)
6917 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6918 N10.getOperand(0), N10.getOperand(1), N0);
6922 // More folding opportunities when target permits.
6923 if (TLI.enableAggressiveFMAFusion(VT)) {
6925 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
6926 if (N0.getOpcode() == ISD::FMA &&
6927 N0.getOperand(2).getOpcode() == ISD::FMUL)
6928 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6929 N0.getOperand(0), N0.getOperand(1),
6930 DAG.getNode(ISD::FMA, SDLoc(N), VT,
6931 N0.getOperand(2).getOperand(0),
6932 N0.getOperand(2).getOperand(1),
6935 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
6936 if (N1->getOpcode() == ISD::FMA &&
6937 N1.getOperand(2).getOpcode() == ISD::FMUL)
6938 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6939 N1.getOperand(0), N1.getOperand(1),
6940 DAG.getNode(ISD::FMA, SDLoc(N), VT,
6941 N1.getOperand(2).getOperand(0),
6942 N1.getOperand(2).getOperand(1),
6949 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6950 SDValue N0 = N->getOperand(0);
6951 SDValue N1 = N->getOperand(1);
6952 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6953 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6954 EVT VT = N->getValueType(0);
6956 const TargetOptions &Options = DAG.getTarget().Options;
6959 if (VT.isVector()) {
6960 SDValue FoldedVOp = SimplifyVBinOp(N);
6961 if (FoldedVOp.getNode()) return FoldedVOp;
6964 // fold (fsub c1, c2) -> c1-c2
6966 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6968 // fold (fsub A, (fneg B)) -> (fadd A, B)
6969 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6970 return DAG.getNode(ISD::FADD, dl, VT, N0,
6971 GetNegatedExpression(N1, DAG, LegalOperations));
6973 // If 'unsafe math' is enabled, fold lots of things.
6974 if (Options.UnsafeFPMath) {
6976 if (N1CFP && N1CFP->getValueAPF().isZero())
6979 // (fsub 0, B) -> -B
6980 if (N0CFP && N0CFP->getValueAPF().isZero()) {
6981 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6982 return GetNegatedExpression(N1, DAG, LegalOperations);
6983 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6984 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6987 // (fsub x, x) -> 0.0
6989 return DAG.getConstantFP(0.0f, VT);
6991 // (fsub x, (fadd x, y)) -> (fneg y)
6992 // (fsub x, (fadd y, x)) -> (fneg y)
6993 if (N1.getOpcode() == ISD::FADD) {
6994 SDValue N10 = N1->getOperand(0);
6995 SDValue N11 = N1->getOperand(1);
6997 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6998 return GetNegatedExpression(N11, DAG, LegalOperations);
7000 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7001 return GetNegatedExpression(N10, DAG, LegalOperations);
7005 // FSUB -> FMA combines:
7006 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7007 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7008 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7010 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7011 if (N0.getOpcode() == ISD::FMUL &&
7012 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7013 return DAG.getNode(ISD::FMA, dl, VT,
7014 N0.getOperand(0), N0.getOperand(1),
7015 DAG.getNode(ISD::FNEG, dl, VT, N1));
7017 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7018 // Note: Commutes FSUB operands.
7019 if (N1.getOpcode() == ISD::FMUL &&
7020 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7021 return DAG.getNode(ISD::FMA, dl, VT,
7022 DAG.getNode(ISD::FNEG, dl, VT,
7024 N1.getOperand(1), N0);
7026 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7027 if (N0.getOpcode() == ISD::FNEG &&
7028 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7029 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
7030 TLI.enableAggressiveFMAFusion(VT))) {
7031 SDValue N00 = N0.getOperand(0).getOperand(0);
7032 SDValue N01 = N0.getOperand(0).getOperand(1);
7033 return DAG.getNode(ISD::FMA, dl, VT,
7034 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
7035 DAG.getNode(ISD::FNEG, dl, VT, N1));
7038 // Remove FP_EXTEND when there is an opportunity to combine. This is
7039 // legal here since extra precision is allowed.
7041 // fold (fsub (fpext (fmul x, y)), z) -> (fma x, y, (fneg z))
7042 if (N0.getOpcode() == ISD::FP_EXTEND) {
7043 SDValue N00 = N0.getOperand(0);
7044 if (N00.getOpcode() == ISD::FMUL)
7045 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7048 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7051 // fold (fsub x, (fpext (fmul y, z))) -> (fma (fneg y), z, x)
7052 // Note: Commutes FSUB operands.
7053 if (N1.getOpcode() == ISD::FP_EXTEND) {
7054 SDValue N10 = N1.getOperand(0);
7055 if (N10.getOpcode() == ISD::FMUL)
7056 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7057 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7063 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7064 // -> (fma (fneg x), y, (fneg z))
7065 if (N0.getOpcode() == ISD::FP_EXTEND) {
7066 SDValue N00 = N0.getOperand(0);
7067 if (N00.getOpcode() == ISD::FNEG) {
7068 SDValue N000 = N00.getOperand(0);
7069 if (N000.getOpcode() == ISD::FMUL) {
7070 return DAG.getNode(ISD::FMA, dl, VT,
7071 DAG.getNode(ISD::FNEG, dl, VT,
7072 N000.getOperand(0)),
7074 DAG.getNode(ISD::FNEG, dl, VT, N1));
7079 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7080 // -> (fma (fneg x), y, (fneg z))
7081 if (N0.getOpcode() == ISD::FNEG) {
7082 SDValue N00 = N0.getOperand(0);
7083 if (N00.getOpcode() == ISD::FP_EXTEND) {
7084 SDValue N000 = N00.getOperand(0);
7085 if (N000.getOpcode() == ISD::FMUL) {
7086 return DAG.getNode(ISD::FMA, dl, VT,
7087 DAG.getNode(ISD::FNEG, dl, VT,
7088 N000.getOperand(0)),
7090 DAG.getNode(ISD::FNEG, dl, VT, N1));
7095 // More folding opportunities when target permits.
7096 if (TLI.enableAggressiveFMAFusion(VT)) {
7098 // fold (fsub (fma x, y, (fmul u, v)), z)
7099 // -> (fma x, y (fma u, v, (fneg z)))
7100 if (N0.getOpcode() == ISD::FMA &&
7101 N0.getOperand(2).getOpcode() == ISD::FMUL)
7102 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7103 N0.getOperand(0), N0.getOperand(1),
7104 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7105 N0.getOperand(2).getOperand(0),
7106 N0.getOperand(2).getOperand(1),
7107 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7110 // fold (fsub x, (fma y, z, (fmul u, v)))
7111 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7112 if (N1.getOpcode() == ISD::FMA &&
7113 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7114 SDValue N20 = N1.getOperand(2).getOperand(0);
7115 SDValue N21 = N1.getOperand(2).getOperand(1);
7116 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7117 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7120 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7121 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7131 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7132 SDValue N0 = N->getOperand(0);
7133 SDValue N1 = N->getOperand(1);
7134 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7135 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7136 EVT VT = N->getValueType(0);
7137 const TargetOptions &Options = DAG.getTarget().Options;
7140 if (VT.isVector()) {
7141 // This just handles C1 * C2 for vectors. Other vector folds are below.
7142 SDValue FoldedVOp = SimplifyVBinOp(N);
7143 if (FoldedVOp.getNode())
7145 // Canonicalize vector constant to RHS.
7146 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7147 N1.getOpcode() != ISD::BUILD_VECTOR)
7148 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7149 if (BV0->isConstant())
7150 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7153 // fold (fmul c1, c2) -> c1*c2
7155 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7157 // canonicalize constant to RHS
7158 if (N0CFP && !N1CFP)
7159 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7161 // fold (fmul A, 1.0) -> A
7162 if (N1CFP && N1CFP->isExactlyValue(1.0))
7165 if (Options.UnsafeFPMath) {
7166 // fold (fmul A, 0) -> 0
7167 if (N1CFP && N1CFP->getValueAPF().isZero())
7170 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7171 if (N0.getOpcode() == ISD::FMUL) {
7172 // Fold scalars or any vector constants (not just splats).
7173 // This fold is done in general by InstCombine, but extra fmul insts
7174 // may have been generated during lowering.
7175 SDValue N01 = N0.getOperand(1);
7176 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7177 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7178 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7179 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7181 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7182 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7186 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7187 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7188 // during an early run of DAGCombiner can prevent folding with fmuls
7189 // inserted during lowering.
7190 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7192 const SDValue Two = DAG.getConstantFP(2.0, VT);
7193 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7194 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7198 // fold (fmul X, 2.0) -> (fadd X, X)
7199 if (N1CFP && N1CFP->isExactlyValue(+2.0))
7200 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7202 // fold (fmul X, -1.0) -> (fneg X)
7203 if (N1CFP && N1CFP->isExactlyValue(-1.0))
7204 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7205 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7207 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7208 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7209 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7210 // Both can be negated for free, check to see if at least one is cheaper
7212 if (LHSNeg == 2 || RHSNeg == 2)
7213 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7214 GetNegatedExpression(N0, DAG, LegalOperations),
7215 GetNegatedExpression(N1, DAG, LegalOperations));
7222 SDValue DAGCombiner::visitFMA(SDNode *N) {
7223 SDValue N0 = N->getOperand(0);
7224 SDValue N1 = N->getOperand(1);
7225 SDValue N2 = N->getOperand(2);
7226 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7227 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7228 EVT VT = N->getValueType(0);
7230 const TargetOptions &Options = DAG.getTarget().Options;
7232 // Constant fold FMA.
7233 if (isa<ConstantFPSDNode>(N0) &&
7234 isa<ConstantFPSDNode>(N1) &&
7235 isa<ConstantFPSDNode>(N2)) {
7236 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7239 if (Options.UnsafeFPMath) {
7240 if (N0CFP && N0CFP->isZero())
7242 if (N1CFP && N1CFP->isZero())
7245 if (N0CFP && N0CFP->isExactlyValue(1.0))
7246 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7247 if (N1CFP && N1CFP->isExactlyValue(1.0))
7248 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7250 // Canonicalize (fma c, x, y) -> (fma x, c, y)
7251 if (N0CFP && !N1CFP)
7252 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7254 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7255 if (Options.UnsafeFPMath && N1CFP &&
7256 N2.getOpcode() == ISD::FMUL &&
7257 N0 == N2.getOperand(0) &&
7258 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7259 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7260 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7264 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7265 if (Options.UnsafeFPMath &&
7266 N0.getOpcode() == ISD::FMUL && N1CFP &&
7267 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7268 return DAG.getNode(ISD::FMA, dl, VT,
7270 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7274 // (fma x, 1, y) -> (fadd x, y)
7275 // (fma x, -1, y) -> (fadd (fneg x), y)
7277 if (N1CFP->isExactlyValue(1.0))
7278 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7280 if (N1CFP->isExactlyValue(-1.0) &&
7281 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7282 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7283 AddToWorklist(RHSNeg.getNode());
7284 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7288 // (fma x, c, x) -> (fmul x, (c+1))
7289 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7290 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7291 DAG.getNode(ISD::FADD, dl, VT,
7292 N1, DAG.getConstantFP(1.0, VT)));
7294 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7295 if (Options.UnsafeFPMath && N1CFP &&
7296 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7297 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7298 DAG.getNode(ISD::FADD, dl, VT,
7299 N1, DAG.getConstantFP(-1.0, VT)));
7305 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7306 SDValue N0 = N->getOperand(0);
7307 SDValue N1 = N->getOperand(1);
7308 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7309 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7310 EVT VT = N->getValueType(0);
7312 const TargetOptions &Options = DAG.getTarget().Options;
7315 if (VT.isVector()) {
7316 SDValue FoldedVOp = SimplifyVBinOp(N);
7317 if (FoldedVOp.getNode()) return FoldedVOp;
7320 // fold (fdiv c1, c2) -> c1/c2
7322 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7324 if (Options.UnsafeFPMath) {
7325 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7327 // Compute the reciprocal 1.0 / c2.
7328 APFloat N1APF = N1CFP->getValueAPF();
7329 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7330 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7331 // Only do the transform if the reciprocal is a legal fp immediate that
7332 // isn't too nasty (eg NaN, denormal, ...).
7333 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7334 (!LegalOperations ||
7335 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7336 // backend)... we should handle this gracefully after Legalize.
7337 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7338 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7339 TLI.isFPImmLegal(Recip, VT)))
7340 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7341 DAG.getConstantFP(Recip, VT));
7344 // If this FDIV is part of a reciprocal square root, it may be folded
7345 // into a target-specific square root estimate instruction.
7346 if (N1.getOpcode() == ISD::FSQRT) {
7347 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7348 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7350 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7351 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7352 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7353 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7354 AddToWorklist(RV.getNode());
7355 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7357 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7358 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7359 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7360 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7361 AddToWorklist(RV.getNode());
7362 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7364 } else if (N1.getOpcode() == ISD::FMUL) {
7365 // Look through an FMUL. Even though this won't remove the FDIV directly,
7366 // it's still worthwhile to get rid of the FSQRT if possible.
7369 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7370 SqrtOp = N1.getOperand(0);
7371 OtherOp = N1.getOperand(1);
7372 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7373 SqrtOp = N1.getOperand(1);
7374 OtherOp = N1.getOperand(0);
7376 if (SqrtOp.getNode()) {
7377 // We found a FSQRT, so try to make this fold:
7378 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7379 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7380 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7381 AddToWorklist(RV.getNode());
7382 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7387 // Fold into a reciprocal estimate and multiply instead of a real divide.
7388 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7389 AddToWorklist(RV.getNode());
7390 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7394 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7395 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7396 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7397 // Both can be negated for free, check to see if at least one is cheaper
7399 if (LHSNeg == 2 || RHSNeg == 2)
7400 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7401 GetNegatedExpression(N0, DAG, LegalOperations),
7402 GetNegatedExpression(N1, DAG, LegalOperations));
7406 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7408 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7409 // Notice that this is not always beneficial. One reason is different target
7410 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7411 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7412 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7413 if (Options.UnsafeFPMath) {
7414 // Skip if current node is a reciprocal.
7415 if (N0CFP && N0CFP->isExactlyValue(1.0))
7418 SmallVector<SDNode *, 4> Users;
7419 // Find all FDIV users of the same divisor.
7420 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7421 UE = N1.getNode()->use_end();
7423 SDNode *User = UI.getUse().getUser();
7424 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7425 Users.push_back(User);
7428 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7429 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7430 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7432 // Dividend / Divisor -> Dividend * Reciprocal
7433 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7434 if ((*I)->getOperand(0) != FPOne) {
7435 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7436 (*I)->getOperand(0), Reciprocal);
7437 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7447 SDValue DAGCombiner::visitFREM(SDNode *N) {
7448 SDValue N0 = N->getOperand(0);
7449 SDValue N1 = N->getOperand(1);
7450 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7451 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7452 EVT VT = N->getValueType(0);
7454 // fold (frem c1, c2) -> fmod(c1,c2)
7456 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7461 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7462 if (DAG.getTarget().Options.UnsafeFPMath) {
7463 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7464 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7465 EVT VT = RV.getValueType();
7466 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7467 AddToWorklist(RV.getNode());
7469 // Unfortunately, RV is now NaN if the input was exactly 0.
7470 // Select out this case and force the answer to 0.
7471 SDValue Zero = DAG.getConstantFP(0.0, VT);
7473 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7474 N->getOperand(0), Zero, ISD::SETEQ);
7475 AddToWorklist(ZeroCmp.getNode());
7476 AddToWorklist(RV.getNode());
7478 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7479 SDLoc(N), VT, ZeroCmp, Zero, RV);
7486 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7487 SDValue N0 = N->getOperand(0);
7488 SDValue N1 = N->getOperand(1);
7489 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7490 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7491 EVT VT = N->getValueType(0);
7493 if (N0CFP && N1CFP) // Constant fold
7494 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7497 const APFloat& V = N1CFP->getValueAPF();
7498 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7499 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7500 if (!V.isNegative()) {
7501 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7502 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7504 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7505 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7506 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7510 // copysign(fabs(x), y) -> copysign(x, y)
7511 // copysign(fneg(x), y) -> copysign(x, y)
7512 // copysign(copysign(x,z), y) -> copysign(x, y)
7513 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7514 N0.getOpcode() == ISD::FCOPYSIGN)
7515 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7516 N0.getOperand(0), N1);
7518 // copysign(x, abs(y)) -> abs(x)
7519 if (N1.getOpcode() == ISD::FABS)
7520 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7522 // copysign(x, copysign(y,z)) -> copysign(x, z)
7523 if (N1.getOpcode() == ISD::FCOPYSIGN)
7524 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7525 N0, N1.getOperand(1));
7527 // copysign(x, fp_extend(y)) -> copysign(x, y)
7528 // copysign(x, fp_round(y)) -> copysign(x, y)
7529 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7530 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7531 N0, N1.getOperand(0));
7536 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7537 SDValue N0 = N->getOperand(0);
7538 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7539 EVT VT = N->getValueType(0);
7540 EVT OpVT = N0.getValueType();
7542 // fold (sint_to_fp c1) -> c1fp
7544 // ...but only if the target supports immediate floating-point values
7545 (!LegalOperations ||
7546 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7547 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7549 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7550 // but UINT_TO_FP is legal on this target, try to convert.
7551 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7552 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7553 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7554 if (DAG.SignBitIsZero(N0))
7555 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7558 // The next optimizations are desirable only if SELECT_CC can be lowered.
7559 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7560 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7561 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7563 (!LegalOperations ||
7564 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7566 { N0.getOperand(0), N0.getOperand(1),
7567 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7569 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7572 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7573 // (select_cc x, y, 1.0, 0.0,, cc)
7574 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7575 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7576 (!LegalOperations ||
7577 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7579 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7580 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7581 N0.getOperand(0).getOperand(2) };
7582 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7589 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7590 SDValue N0 = N->getOperand(0);
7591 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7592 EVT VT = N->getValueType(0);
7593 EVT OpVT = N0.getValueType();
7595 // fold (uint_to_fp c1) -> c1fp
7597 // ...but only if the target supports immediate floating-point values
7598 (!LegalOperations ||
7599 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7600 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7602 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7603 // but SINT_TO_FP is legal on this target, try to convert.
7604 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7605 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7606 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7607 if (DAG.SignBitIsZero(N0))
7608 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7611 // The next optimizations are desirable only if SELECT_CC can be lowered.
7612 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7613 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7615 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7616 (!LegalOperations ||
7617 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7619 { N0.getOperand(0), N0.getOperand(1),
7620 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7622 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7629 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7630 SDValue N0 = N->getOperand(0);
7631 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7632 EVT VT = N->getValueType(0);
7634 // fold (fp_to_sint c1fp) -> c1
7636 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7641 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7642 SDValue N0 = N->getOperand(0);
7643 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7644 EVT VT = N->getValueType(0);
7646 // fold (fp_to_uint c1fp) -> c1
7648 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7653 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7654 SDValue N0 = N->getOperand(0);
7655 SDValue N1 = N->getOperand(1);
7656 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7657 EVT VT = N->getValueType(0);
7659 // fold (fp_round c1fp) -> c1fp
7661 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7663 // fold (fp_round (fp_extend x)) -> x
7664 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7665 return N0.getOperand(0);
7667 // fold (fp_round (fp_round x)) -> (fp_round x)
7668 if (N0.getOpcode() == ISD::FP_ROUND) {
7669 // This is a value preserving truncation if both round's are.
7670 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7671 N0.getNode()->getConstantOperandVal(1) == 1;
7672 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7673 DAG.getIntPtrConstant(IsTrunc));
7676 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7677 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7678 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7679 N0.getOperand(0), N1);
7680 AddToWorklist(Tmp.getNode());
7681 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7682 Tmp, N0.getOperand(1));
7688 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7689 SDValue N0 = N->getOperand(0);
7690 EVT VT = N->getValueType(0);
7691 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7692 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7694 // fold (fp_round_inreg c1fp) -> c1fp
7695 if (N0CFP && isTypeLegal(EVT)) {
7696 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7697 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7703 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7704 SDValue N0 = N->getOperand(0);
7705 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7706 EVT VT = N->getValueType(0);
7708 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7709 if (N->hasOneUse() &&
7710 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7713 // fold (fp_extend c1fp) -> c1fp
7715 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7717 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7719 if (N0.getOpcode() == ISD::FP_ROUND
7720 && N0.getNode()->getConstantOperandVal(1) == 1) {
7721 SDValue In = N0.getOperand(0);
7722 if (In.getValueType() == VT) return In;
7723 if (VT.bitsLT(In.getValueType()))
7724 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7725 In, N0.getOperand(1));
7726 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7729 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7730 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7731 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7732 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7733 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7735 LN0->getBasePtr(), N0.getValueType(),
7736 LN0->getMemOperand());
7737 CombineTo(N, ExtLoad);
7738 CombineTo(N0.getNode(),
7739 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7740 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7741 ExtLoad.getValue(1));
7742 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7748 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7749 SDValue N0 = N->getOperand(0);
7750 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7751 EVT VT = N->getValueType(0);
7753 // fold (fceil c1) -> fceil(c1)
7755 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7760 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7761 SDValue N0 = N->getOperand(0);
7762 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7763 EVT VT = N->getValueType(0);
7765 // fold (ftrunc c1) -> ftrunc(c1)
7767 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7772 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7773 SDValue N0 = N->getOperand(0);
7774 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7775 EVT VT = N->getValueType(0);
7777 // fold (ffloor c1) -> ffloor(c1)
7779 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7784 // FIXME: FNEG and FABS have a lot in common; refactor.
7785 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7786 SDValue N0 = N->getOperand(0);
7787 EVT VT = N->getValueType(0);
7789 if (VT.isVector()) {
7790 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7791 if (FoldedVOp.getNode()) return FoldedVOp;
7794 // Constant fold FNEG.
7795 if (isa<ConstantFPSDNode>(N0))
7796 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7798 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7799 &DAG.getTarget().Options))
7800 return GetNegatedExpression(N0, DAG, LegalOperations);
7802 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7803 // constant pool values.
7804 if (!TLI.isFNegFree(VT) &&
7805 N0.getOpcode() == ISD::BITCAST &&
7806 N0.getNode()->hasOneUse()) {
7807 SDValue Int = N0.getOperand(0);
7808 EVT IntVT = Int.getValueType();
7809 if (IntVT.isInteger() && !IntVT.isVector()) {
7811 if (N0.getValueType().isVector()) {
7812 // For a vector, get a mask such as 0x80... per scalar element
7814 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7815 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7817 // For a scalar, just generate 0x80...
7818 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7820 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7821 DAG.getConstant(SignMask, IntVT));
7822 AddToWorklist(Int.getNode());
7823 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7827 // (fneg (fmul c, x)) -> (fmul -c, x)
7828 if (N0.getOpcode() == ISD::FMUL) {
7829 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7831 APFloat CVal = CFP1->getValueAPF();
7833 if (Level >= AfterLegalizeDAG &&
7834 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7835 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7837 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7838 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7845 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7846 SDValue N0 = N->getOperand(0);
7847 SDValue N1 = N->getOperand(1);
7848 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7849 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7851 if (N0CFP && N1CFP) {
7852 const APFloat &C0 = N0CFP->getValueAPF();
7853 const APFloat &C1 = N1CFP->getValueAPF();
7854 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7858 EVT VT = N->getValueType(0);
7859 // Canonicalize to constant on RHS.
7860 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7866 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7867 SDValue N0 = N->getOperand(0);
7868 SDValue N1 = N->getOperand(1);
7869 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7870 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7872 if (N0CFP && N1CFP) {
7873 const APFloat &C0 = N0CFP->getValueAPF();
7874 const APFloat &C1 = N1CFP->getValueAPF();
7875 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7879 EVT VT = N->getValueType(0);
7880 // Canonicalize to constant on RHS.
7881 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7887 SDValue DAGCombiner::visitFABS(SDNode *N) {
7888 SDValue N0 = N->getOperand(0);
7889 EVT VT = N->getValueType(0);
7891 if (VT.isVector()) {
7892 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7893 if (FoldedVOp.getNode()) return FoldedVOp;
7896 // fold (fabs c1) -> fabs(c1)
7897 if (isa<ConstantFPSDNode>(N0))
7898 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7900 // fold (fabs (fabs x)) -> (fabs x)
7901 if (N0.getOpcode() == ISD::FABS)
7902 return N->getOperand(0);
7904 // fold (fabs (fneg x)) -> (fabs x)
7905 // fold (fabs (fcopysign x, y)) -> (fabs x)
7906 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7907 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7909 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7910 // constant pool values.
7911 if (!TLI.isFAbsFree(VT) &&
7912 N0.getOpcode() == ISD::BITCAST &&
7913 N0.getNode()->hasOneUse()) {
7914 SDValue Int = N0.getOperand(0);
7915 EVT IntVT = Int.getValueType();
7916 if (IntVT.isInteger() && !IntVT.isVector()) {
7918 if (N0.getValueType().isVector()) {
7919 // For a vector, get a mask such as 0x7f... per scalar element
7921 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7922 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7924 // For a scalar, just generate 0x7f...
7925 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7927 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7928 DAG.getConstant(SignMask, IntVT));
7929 AddToWorklist(Int.getNode());
7930 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7937 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7938 SDValue Chain = N->getOperand(0);
7939 SDValue N1 = N->getOperand(1);
7940 SDValue N2 = N->getOperand(2);
7942 // If N is a constant we could fold this into a fallthrough or unconditional
7943 // branch. However that doesn't happen very often in normal code, because
7944 // Instcombine/SimplifyCFG should have handled the available opportunities.
7945 // If we did this folding here, it would be necessary to update the
7946 // MachineBasicBlock CFG, which is awkward.
7948 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7950 if (N1.getOpcode() == ISD::SETCC &&
7951 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7952 N1.getOperand(0).getValueType())) {
7953 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7954 Chain, N1.getOperand(2),
7955 N1.getOperand(0), N1.getOperand(1), N2);
7958 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7959 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7960 (N1.getOperand(0).hasOneUse() &&
7961 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7962 SDNode *Trunc = nullptr;
7963 if (N1.getOpcode() == ISD::TRUNCATE) {
7964 // Look pass the truncate.
7965 Trunc = N1.getNode();
7966 N1 = N1.getOperand(0);
7969 // Match this pattern so that we can generate simpler code:
7972 // %b = and i32 %a, 2
7973 // %c = srl i32 %b, 1
7974 // brcond i32 %c ...
7979 // %b = and i32 %a, 2
7980 // %c = setcc eq %b, 0
7983 // This applies only when the AND constant value has one bit set and the
7984 // SRL constant is equal to the log2 of the AND constant. The back-end is
7985 // smart enough to convert the result into a TEST/JMP sequence.
7986 SDValue Op0 = N1.getOperand(0);
7987 SDValue Op1 = N1.getOperand(1);
7989 if (Op0.getOpcode() == ISD::AND &&
7990 Op1.getOpcode() == ISD::Constant) {
7991 SDValue AndOp1 = Op0.getOperand(1);
7993 if (AndOp1.getOpcode() == ISD::Constant) {
7994 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7996 if (AndConst.isPowerOf2() &&
7997 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7999 DAG.getSetCC(SDLoc(N),
8000 getSetCCResultType(Op0.getValueType()),
8001 Op0, DAG.getConstant(0, Op0.getValueType()),
8004 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8005 MVT::Other, Chain, SetCC, N2);
8006 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8007 // will convert it back to (X & C1) >> C2.
8008 CombineTo(N, NewBRCond, false);
8009 // Truncate is dead.
8011 deleteAndRecombine(Trunc);
8012 // Replace the uses of SRL with SETCC
8013 WorklistRemover DeadNodes(*this);
8014 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8015 deleteAndRecombine(N1.getNode());
8016 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8022 // Restore N1 if the above transformation doesn't match.
8023 N1 = N->getOperand(1);
8026 // Transform br(xor(x, y)) -> br(x != y)
8027 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8028 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8029 SDNode *TheXor = N1.getNode();
8030 SDValue Op0 = TheXor->getOperand(0);
8031 SDValue Op1 = TheXor->getOperand(1);
8032 if (Op0.getOpcode() == Op1.getOpcode()) {
8033 // Avoid missing important xor optimizations.
8034 SDValue Tmp = visitXOR(TheXor);
8035 if (Tmp.getNode()) {
8036 if (Tmp.getNode() != TheXor) {
8037 DEBUG(dbgs() << "\nReplacing.8 ";
8039 dbgs() << "\nWith: ";
8040 Tmp.getNode()->dump(&DAG);
8042 WorklistRemover DeadNodes(*this);
8043 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8044 deleteAndRecombine(TheXor);
8045 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8046 MVT::Other, Chain, Tmp, N2);
8049 // visitXOR has changed XOR's operands or replaced the XOR completely,
8051 return SDValue(N, 0);
8055 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8057 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8058 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8059 Op0.getOpcode() == ISD::XOR) {
8060 TheXor = Op0.getNode();
8064 EVT SetCCVT = N1.getValueType();
8066 SetCCVT = getSetCCResultType(SetCCVT);
8067 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8070 Equal ? ISD::SETEQ : ISD::SETNE);
8071 // Replace the uses of XOR with SETCC
8072 WorklistRemover DeadNodes(*this);
8073 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8074 deleteAndRecombine(N1.getNode());
8075 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8076 MVT::Other, Chain, SetCC, N2);
8083 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8085 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8086 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8087 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8089 // If N is a constant we could fold this into a fallthrough or unconditional
8090 // branch. However that doesn't happen very often in normal code, because
8091 // Instcombine/SimplifyCFG should have handled the available opportunities.
8092 // If we did this folding here, it would be necessary to update the
8093 // MachineBasicBlock CFG, which is awkward.
8095 // Use SimplifySetCC to simplify SETCC's.
8096 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8097 CondLHS, CondRHS, CC->get(), SDLoc(N),
8099 if (Simp.getNode()) AddToWorklist(Simp.getNode());
8101 // fold to a simpler setcc
8102 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8103 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8104 N->getOperand(0), Simp.getOperand(2),
8105 Simp.getOperand(0), Simp.getOperand(1),
8111 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8112 /// and that N may be folded in the load / store addressing mode.
8113 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8115 const TargetLowering &TLI) {
8117 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8118 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8120 VT = Use->getValueType(0);
8121 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8122 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8124 VT = ST->getValue().getValueType();
8128 TargetLowering::AddrMode AM;
8129 if (N->getOpcode() == ISD::ADD) {
8130 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8133 AM.BaseOffs = Offset->getSExtValue();
8137 } else if (N->getOpcode() == ISD::SUB) {
8138 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8141 AM.BaseOffs = -Offset->getSExtValue();
8148 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8151 /// Try turning a load/store into a pre-indexed load/store when the base
8152 /// pointer is an add or subtract and it has other uses besides the load/store.
8153 /// After the transformation, the new indexed load/store has effectively folded
8154 /// the add/subtract in and all of its other uses are redirected to the
8156 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8157 if (Level < AfterLegalizeDAG)
8163 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8164 if (LD->isIndexed())
8166 VT = LD->getMemoryVT();
8167 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8168 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8170 Ptr = LD->getBasePtr();
8171 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8172 if (ST->isIndexed())
8174 VT = ST->getMemoryVT();
8175 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8176 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8178 Ptr = ST->getBasePtr();
8184 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8185 // out. There is no reason to make this a preinc/predec.
8186 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8187 Ptr.getNode()->hasOneUse())
8190 // Ask the target to do addressing mode selection.
8193 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8194 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8197 // Backends without true r+i pre-indexed forms may need to pass a
8198 // constant base with a variable offset so that constant coercion
8199 // will work with the patterns in canonical form.
8200 bool Swapped = false;
8201 if (isa<ConstantSDNode>(BasePtr)) {
8202 std::swap(BasePtr, Offset);
8206 // Don't create a indexed load / store with zero offset.
8207 if (isa<ConstantSDNode>(Offset) &&
8208 cast<ConstantSDNode>(Offset)->isNullValue())
8211 // Try turning it into a pre-indexed load / store except when:
8212 // 1) The new base ptr is a frame index.
8213 // 2) If N is a store and the new base ptr is either the same as or is a
8214 // predecessor of the value being stored.
8215 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8216 // that would create a cycle.
8217 // 4) All uses are load / store ops that use it as old base ptr.
8219 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8220 // (plus the implicit offset) to a register to preinc anyway.
8221 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8226 SDValue Val = cast<StoreSDNode>(N)->getValue();
8227 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8231 // If the offset is a constant, there may be other adds of constants that
8232 // can be folded with this one. We should do this to avoid having to keep
8233 // a copy of the original base pointer.
8234 SmallVector<SDNode *, 16> OtherUses;
8235 if (isa<ConstantSDNode>(Offset))
8236 for (SDNode *Use : BasePtr.getNode()->uses()) {
8237 if (Use == Ptr.getNode())
8240 if (Use->isPredecessorOf(N))
8243 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8248 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8249 if (Op1.getNode() == BasePtr.getNode())
8250 std::swap(Op0, Op1);
8251 assert(Op0.getNode() == BasePtr.getNode() &&
8252 "Use of ADD/SUB but not an operand");
8254 if (!isa<ConstantSDNode>(Op1)) {
8259 // FIXME: In some cases, we can be smarter about this.
8260 if (Op1.getValueType() != Offset.getValueType()) {
8265 OtherUses.push_back(Use);
8269 std::swap(BasePtr, Offset);
8271 // Now check for #3 and #4.
8272 bool RealUse = false;
8274 // Caches for hasPredecessorHelper
8275 SmallPtrSet<const SDNode *, 32> Visited;
8276 SmallVector<const SDNode *, 16> Worklist;
8278 for (SDNode *Use : Ptr.getNode()->uses()) {
8281 if (N->hasPredecessorHelper(Use, Visited, Worklist))
8284 // If Ptr may be folded in addressing mode of other use, then it's
8285 // not profitable to do this transformation.
8286 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8295 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8296 BasePtr, Offset, AM);
8298 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8299 BasePtr, Offset, AM);
8302 DEBUG(dbgs() << "\nReplacing.4 ";
8304 dbgs() << "\nWith: ";
8305 Result.getNode()->dump(&DAG);
8307 WorklistRemover DeadNodes(*this);
8309 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8310 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8312 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8315 // Finally, since the node is now dead, remove it from the graph.
8316 deleteAndRecombine(N);
8319 std::swap(BasePtr, Offset);
8321 // Replace other uses of BasePtr that can be updated to use Ptr
8322 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8323 unsigned OffsetIdx = 1;
8324 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8326 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8327 BasePtr.getNode() && "Expected BasePtr operand");
8329 // We need to replace ptr0 in the following expression:
8330 // x0 * offset0 + y0 * ptr0 = t0
8332 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8334 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8335 // indexed load/store and the expresion that needs to be re-written.
8337 // Therefore, we have:
8338 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8340 ConstantSDNode *CN =
8341 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8343 APInt Offset0 = CN->getAPIntValue();
8344 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8346 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8347 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8348 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8349 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8351 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8353 APInt CNV = Offset0;
8354 if (X0 < 0) CNV = -CNV;
8355 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8356 else CNV = CNV - Offset1;
8358 // We can now generate the new expression.
8359 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8360 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8362 SDValue NewUse = DAG.getNode(Opcode,
8363 SDLoc(OtherUses[i]),
8364 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8365 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8366 deleteAndRecombine(OtherUses[i]);
8369 // Replace the uses of Ptr with uses of the updated base value.
8370 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8371 deleteAndRecombine(Ptr.getNode());
8376 /// Try to combine a load/store with a add/sub of the base pointer node into a
8377 /// post-indexed load/store. The transformation folded the add/subtract into the
8378 /// new indexed load/store effectively and all of its uses are redirected to the
8380 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8381 if (Level < AfterLegalizeDAG)
8387 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8388 if (LD->isIndexed())
8390 VT = LD->getMemoryVT();
8391 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8392 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8394 Ptr = LD->getBasePtr();
8395 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8396 if (ST->isIndexed())
8398 VT = ST->getMemoryVT();
8399 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8400 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8402 Ptr = ST->getBasePtr();
8408 if (Ptr.getNode()->hasOneUse())
8411 for (SDNode *Op : Ptr.getNode()->uses()) {
8413 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8418 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8419 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8420 // Don't create a indexed load / store with zero offset.
8421 if (isa<ConstantSDNode>(Offset) &&
8422 cast<ConstantSDNode>(Offset)->isNullValue())
8425 // Try turning it into a post-indexed load / store except when
8426 // 1) All uses are load / store ops that use it as base ptr (and
8427 // it may be folded as addressing mmode).
8428 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8429 // nor a successor of N. Otherwise, if Op is folded that would
8432 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8436 bool TryNext = false;
8437 for (SDNode *Use : BasePtr.getNode()->uses()) {
8438 if (Use == Ptr.getNode())
8441 // If all the uses are load / store addresses, then don't do the
8443 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8444 bool RealUse = false;
8445 for (SDNode *UseUse : Use->uses()) {
8446 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8461 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8462 SDValue Result = isLoad
8463 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8464 BasePtr, Offset, AM)
8465 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8466 BasePtr, Offset, AM);
8469 DEBUG(dbgs() << "\nReplacing.5 ";
8471 dbgs() << "\nWith: ";
8472 Result.getNode()->dump(&DAG);
8474 WorklistRemover DeadNodes(*this);
8476 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8477 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8479 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8482 // Finally, since the node is now dead, remove it from the graph.
8483 deleteAndRecombine(N);
8485 // Replace the uses of Use with uses of the updated base value.
8486 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8487 Result.getValue(isLoad ? 1 : 0));
8488 deleteAndRecombine(Op);
8497 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8498 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8499 ISD::MemIndexedMode AM = LD->getAddressingMode();
8500 assert(AM != ISD::UNINDEXED);
8501 SDValue BP = LD->getOperand(1);
8502 SDValue Inc = LD->getOperand(2);
8504 // Some backends use TargetConstants for load offsets, but don't expect
8505 // TargetConstants in general ADD nodes. We can convert these constants into
8506 // regular Constants (if the constant is not opaque).
8507 assert((Inc.getOpcode() != ISD::TargetConstant ||
8508 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8509 "Cannot split out indexing using opaque target constants");
8510 if (Inc.getOpcode() == ISD::TargetConstant) {
8511 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8512 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8513 ConstInc->getValueType(0));
8517 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8518 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8521 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8522 LoadSDNode *LD = cast<LoadSDNode>(N);
8523 SDValue Chain = LD->getChain();
8524 SDValue Ptr = LD->getBasePtr();
8526 // If load is not volatile and there are no uses of the loaded value (and
8527 // the updated indexed value in case of indexed loads), change uses of the
8528 // chain value into uses of the chain input (i.e. delete the dead load).
8529 if (!LD->isVolatile()) {
8530 if (N->getValueType(1) == MVT::Other) {
8532 if (!N->hasAnyUseOfValue(0)) {
8533 // It's not safe to use the two value CombineTo variant here. e.g.
8534 // v1, chain2 = load chain1, loc
8535 // v2, chain3 = load chain2, loc
8537 // Now we replace use of chain2 with chain1. This makes the second load
8538 // isomorphic to the one we are deleting, and thus makes this load live.
8539 DEBUG(dbgs() << "\nReplacing.6 ";
8541 dbgs() << "\nWith chain: ";
8542 Chain.getNode()->dump(&DAG);
8544 WorklistRemover DeadNodes(*this);
8545 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8548 deleteAndRecombine(N);
8550 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8554 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8556 // If this load has an opaque TargetConstant offset, then we cannot split
8557 // the indexing into an add/sub directly (that TargetConstant may not be
8558 // valid for a different type of node, and we cannot convert an opaque
8559 // target constant into a regular constant).
8560 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8561 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8563 if (!N->hasAnyUseOfValue(0) &&
8564 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8565 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8567 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8568 Index = SplitIndexingFromLoad(LD);
8569 // Try to fold the base pointer arithmetic into subsequent loads and
8571 AddUsersToWorklist(N);
8573 Index = DAG.getUNDEF(N->getValueType(1));
8574 DEBUG(dbgs() << "\nReplacing.7 ";
8576 dbgs() << "\nWith: ";
8577 Undef.getNode()->dump(&DAG);
8578 dbgs() << " and 2 other values\n");
8579 WorklistRemover DeadNodes(*this);
8580 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8581 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8582 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8583 deleteAndRecombine(N);
8584 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8589 // If this load is directly stored, replace the load value with the stored
8591 // TODO: Handle store large -> read small portion.
8592 // TODO: Handle TRUNCSTORE/LOADEXT
8593 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8594 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8595 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8596 if (PrevST->getBasePtr() == Ptr &&
8597 PrevST->getValue().getValueType() == N->getValueType(0))
8598 return CombineTo(N, Chain.getOperand(1), Chain);
8602 // Try to infer better alignment information than the load already has.
8603 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8604 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8605 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8607 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8608 LD->getValueType(0),
8609 Chain, Ptr, LD->getPointerInfo(),
8611 LD->isVolatile(), LD->isNonTemporal(),
8612 LD->isInvariant(), Align, LD->getAAInfo());
8613 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8618 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8619 : DAG.getSubtarget().useAA();
8621 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8622 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8625 if (UseAA && LD->isUnindexed()) {
8626 // Walk up chain skipping non-aliasing memory nodes.
8627 SDValue BetterChain = FindBetterChain(N, Chain);
8629 // If there is a better chain.
8630 if (Chain != BetterChain) {
8633 // Replace the chain to void dependency.
8634 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8635 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8636 BetterChain, Ptr, LD->getMemOperand());
8638 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8639 LD->getValueType(0),
8640 BetterChain, Ptr, LD->getMemoryVT(),
8641 LD->getMemOperand());
8644 // Create token factor to keep old chain connected.
8645 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8646 MVT::Other, Chain, ReplLoad.getValue(1));
8648 // Make sure the new and old chains are cleaned up.
8649 AddToWorklist(Token.getNode());
8651 // Replace uses with load result and token factor. Don't add users
8653 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8657 // Try transforming N to an indexed load.
8658 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8659 return SDValue(N, 0);
8661 // Try to slice up N to more direct loads if the slices are mapped to
8662 // different register banks or pairing can take place.
8664 return SDValue(N, 0);
8670 /// \brief Helper structure used to slice a load in smaller loads.
8671 /// Basically a slice is obtained from the following sequence:
8672 /// Origin = load Ty1, Base
8673 /// Shift = srl Ty1 Origin, CstTy Amount
8674 /// Inst = trunc Shift to Ty2
8676 /// Then, it will be rewriten into:
8677 /// Slice = load SliceTy, Base + SliceOffset
8678 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8680 /// SliceTy is deduced from the number of bits that are actually used to
8682 struct LoadedSlice {
8683 /// \brief Helper structure used to compute the cost of a slice.
8685 /// Are we optimizing for code size.
8690 unsigned CrossRegisterBanksCopies;
8694 Cost(bool ForCodeSize = false)
8695 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8696 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8698 /// \brief Get the cost of one isolated slice.
8699 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8700 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8701 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8702 EVT TruncType = LS.Inst->getValueType(0);
8703 EVT LoadedType = LS.getLoadedType();
8704 if (TruncType != LoadedType &&
8705 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8709 /// \brief Account for slicing gain in the current cost.
8710 /// Slicing provide a few gains like removing a shift or a
8711 /// truncate. This method allows to grow the cost of the original
8712 /// load with the gain from this slice.
8713 void addSliceGain(const LoadedSlice &LS) {
8714 // Each slice saves a truncate.
8715 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8716 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8717 LS.Inst->getOperand(0).getValueType()))
8719 // If there is a shift amount, this slice gets rid of it.
8722 // If this slice can merge a cross register bank copy, account for it.
8723 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8724 ++CrossRegisterBanksCopies;
8727 Cost &operator+=(const Cost &RHS) {
8729 Truncates += RHS.Truncates;
8730 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8736 bool operator==(const Cost &RHS) const {
8737 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8738 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8739 ZExts == RHS.ZExts && Shift == RHS.Shift;
8742 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8744 bool operator<(const Cost &RHS) const {
8745 // Assume cross register banks copies are as expensive as loads.
8746 // FIXME: Do we want some more target hooks?
8747 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8748 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8749 // Unless we are optimizing for code size, consider the
8750 // expensive operation first.
8751 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8752 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8753 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8754 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8757 bool operator>(const Cost &RHS) const { return RHS < *this; }
8759 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8761 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8763 // The last instruction that represent the slice. This should be a
8764 // truncate instruction.
8766 // The original load instruction.
8768 // The right shift amount in bits from the original load.
8770 // The DAG from which Origin came from.
8771 // This is used to get some contextual information about legal types, etc.
8774 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8775 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8776 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8778 LoadedSlice(const LoadedSlice &LS)
8779 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8781 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8782 /// \return Result is \p BitWidth and has used bits set to 1 and
8783 /// not used bits set to 0.
8784 APInt getUsedBits() const {
8785 // Reproduce the trunc(lshr) sequence:
8786 // - Start from the truncated value.
8787 // - Zero extend to the desired bit width.
8789 assert(Origin && "No original load to compare against.");
8790 unsigned BitWidth = Origin->getValueSizeInBits(0);
8791 assert(Inst && "This slice is not bound to an instruction");
8792 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8793 "Extracted slice is bigger than the whole type!");
8794 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8795 UsedBits.setAllBits();
8796 UsedBits = UsedBits.zext(BitWidth);
8801 /// \brief Get the size of the slice to be loaded in bytes.
8802 unsigned getLoadedSize() const {
8803 unsigned SliceSize = getUsedBits().countPopulation();
8804 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8805 return SliceSize / 8;
8808 /// \brief Get the type that will be loaded for this slice.
8809 /// Note: This may not be the final type for the slice.
8810 EVT getLoadedType() const {
8811 assert(DAG && "Missing context");
8812 LLVMContext &Ctxt = *DAG->getContext();
8813 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8816 /// \brief Get the alignment of the load used for this slice.
8817 unsigned getAlignment() const {
8818 unsigned Alignment = Origin->getAlignment();
8819 unsigned Offset = getOffsetFromBase();
8821 Alignment = MinAlign(Alignment, Alignment + Offset);
8825 /// \brief Check if this slice can be rewritten with legal operations.
8826 bool isLegal() const {
8827 // An invalid slice is not legal.
8828 if (!Origin || !Inst || !DAG)
8831 // Offsets are for indexed load only, we do not handle that.
8832 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8835 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8837 // Check that the type is legal.
8838 EVT SliceType = getLoadedType();
8839 if (!TLI.isTypeLegal(SliceType))
8842 // Check that the load is legal for this type.
8843 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8846 // Check that the offset can be computed.
8847 // 1. Check its type.
8848 EVT PtrType = Origin->getBasePtr().getValueType();
8849 if (PtrType == MVT::Untyped || PtrType.isExtended())
8852 // 2. Check that it fits in the immediate.
8853 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8856 // 3. Check that the computation is legal.
8857 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8860 // Check that the zext is legal if it needs one.
8861 EVT TruncateType = Inst->getValueType(0);
8862 if (TruncateType != SliceType &&
8863 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8869 /// \brief Get the offset in bytes of this slice in the original chunk of
8871 /// \pre DAG != nullptr.
8872 uint64_t getOffsetFromBase() const {
8873 assert(DAG && "Missing context.");
8875 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8876 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8877 uint64_t Offset = Shift / 8;
8878 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8879 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8880 "The size of the original loaded type is not a multiple of a"
8882 // If Offset is bigger than TySizeInBytes, it means we are loading all
8883 // zeros. This should have been optimized before in the process.
8884 assert(TySizeInBytes > Offset &&
8885 "Invalid shift amount for given loaded size");
8887 Offset = TySizeInBytes - Offset - getLoadedSize();
8891 /// \brief Generate the sequence of instructions to load the slice
8892 /// represented by this object and redirect the uses of this slice to
8893 /// this new sequence of instructions.
8894 /// \pre this->Inst && this->Origin are valid Instructions and this
8895 /// object passed the legal check: LoadedSlice::isLegal returned true.
8896 /// \return The last instruction of the sequence used to load the slice.
8897 SDValue loadSlice() const {
8898 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8899 const SDValue &OldBaseAddr = Origin->getBasePtr();
8900 SDValue BaseAddr = OldBaseAddr;
8901 // Get the offset in that chunk of bytes w.r.t. the endianess.
8902 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8903 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8905 // BaseAddr = BaseAddr + Offset.
8906 EVT ArithType = BaseAddr.getValueType();
8907 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8908 DAG->getConstant(Offset, ArithType));
8911 // Create the type of the loaded slice according to its size.
8912 EVT SliceType = getLoadedType();
8914 // Create the load for the slice.
8915 SDValue LastInst = DAG->getLoad(
8916 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8917 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8918 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8919 // If the final type is not the same as the loaded type, this means that
8920 // we have to pad with zero. Create a zero extend for that.
8921 EVT FinalType = Inst->getValueType(0);
8922 if (SliceType != FinalType)
8924 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8928 /// \brief Check if this slice can be merged with an expensive cross register
8929 /// bank copy. E.g.,
8931 /// f = bitcast i32 i to float
8932 bool canMergeExpensiveCrossRegisterBankCopy() const {
8933 if (!Inst || !Inst->hasOneUse())
8935 SDNode *Use = *Inst->use_begin();
8936 if (Use->getOpcode() != ISD::BITCAST)
8938 assert(DAG && "Missing context");
8939 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8940 EVT ResVT = Use->getValueType(0);
8941 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8942 const TargetRegisterClass *ArgRC =
8943 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8944 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8947 // At this point, we know that we perform a cross-register-bank copy.
8948 // Check if it is expensive.
8949 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8950 // Assume bitcasts are cheap, unless both register classes do not
8951 // explicitly share a common sub class.
8952 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8955 // Check if it will be merged with the load.
8956 // 1. Check the alignment constraint.
8957 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8958 ResVT.getTypeForEVT(*DAG->getContext()));
8960 if (RequiredAlignment > getAlignment())
8963 // 2. Check that the load is a legal operation for that type.
8964 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8967 // 3. Check that we do not have a zext in the way.
8968 if (Inst->getValueType(0) != getLoadedType())
8976 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8977 /// \p UsedBits looks like 0..0 1..1 0..0.
8978 static bool areUsedBitsDense(const APInt &UsedBits) {
8979 // If all the bits are one, this is dense!
8980 if (UsedBits.isAllOnesValue())
8983 // Get rid of the unused bits on the right.
8984 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8985 // Get rid of the unused bits on the left.
8986 if (NarrowedUsedBits.countLeadingZeros())
8987 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8988 // Check that the chunk of bits is completely used.
8989 return NarrowedUsedBits.isAllOnesValue();
8992 /// \brief Check whether or not \p First and \p Second are next to each other
8993 /// in memory. This means that there is no hole between the bits loaded
8994 /// by \p First and the bits loaded by \p Second.
8995 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8996 const LoadedSlice &Second) {
8997 assert(First.Origin == Second.Origin && First.Origin &&
8998 "Unable to match different memory origins.");
8999 APInt UsedBits = First.getUsedBits();
9000 assert((UsedBits & Second.getUsedBits()) == 0 &&
9001 "Slices are not supposed to overlap.");
9002 UsedBits |= Second.getUsedBits();
9003 return areUsedBitsDense(UsedBits);
9006 /// \brief Adjust the \p GlobalLSCost according to the target
9007 /// paring capabilities and the layout of the slices.
9008 /// \pre \p GlobalLSCost should account for at least as many loads as
9009 /// there is in the slices in \p LoadedSlices.
9010 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9011 LoadedSlice::Cost &GlobalLSCost) {
9012 unsigned NumberOfSlices = LoadedSlices.size();
9013 // If there is less than 2 elements, no pairing is possible.
9014 if (NumberOfSlices < 2)
9017 // Sort the slices so that elements that are likely to be next to each
9018 // other in memory are next to each other in the list.
9019 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9020 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9021 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9022 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9024 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9025 // First (resp. Second) is the first (resp. Second) potentially candidate
9026 // to be placed in a paired load.
9027 const LoadedSlice *First = nullptr;
9028 const LoadedSlice *Second = nullptr;
9029 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9030 // Set the beginning of the pair.
9033 Second = &LoadedSlices[CurrSlice];
9035 // If First is NULL, it means we start a new pair.
9036 // Get to the next slice.
9040 EVT LoadedType = First->getLoadedType();
9042 // If the types of the slices are different, we cannot pair them.
9043 if (LoadedType != Second->getLoadedType())
9046 // Check if the target supplies paired loads for this type.
9047 unsigned RequiredAlignment = 0;
9048 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9049 // move to the next pair, this type is hopeless.
9053 // Check if we meet the alignment requirement.
9054 if (RequiredAlignment > First->getAlignment())
9057 // Check that both loads are next to each other in memory.
9058 if (!areSlicesNextToEachOther(*First, *Second))
9061 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9062 --GlobalLSCost.Loads;
9063 // Move to the next pair.
9068 /// \brief Check the profitability of all involved LoadedSlice.
9069 /// Currently, it is considered profitable if there is exactly two
9070 /// involved slices (1) which are (2) next to each other in memory, and
9071 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9073 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9074 /// the elements themselves.
9076 /// FIXME: When the cost model will be mature enough, we can relax
9077 /// constraints (1) and (2).
9078 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9079 const APInt &UsedBits, bool ForCodeSize) {
9080 unsigned NumberOfSlices = LoadedSlices.size();
9081 if (StressLoadSlicing)
9082 return NumberOfSlices > 1;
9085 if (NumberOfSlices != 2)
9089 if (!areUsedBitsDense(UsedBits))
9093 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9094 // The original code has one big load.
9096 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9097 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9098 // Accumulate the cost of all the slices.
9099 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9100 GlobalSlicingCost += SliceCost;
9102 // Account as cost in the original configuration the gain obtained
9103 // with the current slices.
9104 OrigCost.addSliceGain(LS);
9107 // If the target supports paired load, adjust the cost accordingly.
9108 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9109 return OrigCost > GlobalSlicingCost;
9112 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9113 /// operations, split it in the various pieces being extracted.
9115 /// This sort of thing is introduced by SROA.
9116 /// This slicing takes care not to insert overlapping loads.
9117 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9118 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9119 if (Level < AfterLegalizeDAG)
9122 LoadSDNode *LD = cast<LoadSDNode>(N);
9123 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9124 !LD->getValueType(0).isInteger())
9127 // Keep track of already used bits to detect overlapping values.
9128 // In that case, we will just abort the transformation.
9129 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9131 SmallVector<LoadedSlice, 4> LoadedSlices;
9133 // Check if this load is used as several smaller chunks of bits.
9134 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9135 // of computation for each trunc.
9136 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9137 UI != UIEnd; ++UI) {
9138 // Skip the uses of the chain.
9139 if (UI.getUse().getResNo() != 0)
9145 // Check if this is a trunc(lshr).
9146 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9147 isa<ConstantSDNode>(User->getOperand(1))) {
9148 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9149 User = *User->use_begin();
9152 // At this point, User is a Truncate, iff we encountered, trunc or
9154 if (User->getOpcode() != ISD::TRUNCATE)
9157 // The width of the type must be a power of 2 and greater than 8-bits.
9158 // Otherwise the load cannot be represented in LLVM IR.
9159 // Moreover, if we shifted with a non-8-bits multiple, the slice
9160 // will be across several bytes. We do not support that.
9161 unsigned Width = User->getValueSizeInBits(0);
9162 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9165 // Build the slice for this chain of computations.
9166 LoadedSlice LS(User, LD, Shift, &DAG);
9167 APInt CurrentUsedBits = LS.getUsedBits();
9169 // Check if this slice overlaps with another.
9170 if ((CurrentUsedBits & UsedBits) != 0)
9172 // Update the bits used globally.
9173 UsedBits |= CurrentUsedBits;
9175 // Check if the new slice would be legal.
9179 // Record the slice.
9180 LoadedSlices.push_back(LS);
9183 // Abort slicing if it does not seem to be profitable.
9184 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9189 // Rewrite each chain to use an independent load.
9190 // By construction, each chain can be represented by a unique load.
9192 // Prepare the argument for the new token factor for all the slices.
9193 SmallVector<SDValue, 8> ArgChains;
9194 for (SmallVectorImpl<LoadedSlice>::const_iterator
9195 LSIt = LoadedSlices.begin(),
9196 LSItEnd = LoadedSlices.end();
9197 LSIt != LSItEnd; ++LSIt) {
9198 SDValue SliceInst = LSIt->loadSlice();
9199 CombineTo(LSIt->Inst, SliceInst, true);
9200 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9201 SliceInst = SliceInst.getOperand(0);
9202 assert(SliceInst->getOpcode() == ISD::LOAD &&
9203 "It takes more than a zext to get to the loaded slice!!");
9204 ArgChains.push_back(SliceInst.getValue(1));
9207 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9209 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9213 /// Check to see if V is (and load (ptr), imm), where the load is having
9214 /// specific bytes cleared out. If so, return the byte size being masked out
9215 /// and the shift amount.
9216 static std::pair<unsigned, unsigned>
9217 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9218 std::pair<unsigned, unsigned> Result(0, 0);
9220 // Check for the structure we're looking for.
9221 if (V->getOpcode() != ISD::AND ||
9222 !isa<ConstantSDNode>(V->getOperand(1)) ||
9223 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9226 // Check the chain and pointer.
9227 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9228 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
9230 // The store should be chained directly to the load or be an operand of a
9232 if (LD == Chain.getNode())
9234 else if (Chain->getOpcode() != ISD::TokenFactor)
9235 return Result; // Fail.
9238 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9239 if (Chain->getOperand(i).getNode() == LD) {
9243 if (!isOk) return Result;
9246 // This only handles simple types.
9247 if (V.getValueType() != MVT::i16 &&
9248 V.getValueType() != MVT::i32 &&
9249 V.getValueType() != MVT::i64)
9252 // Check the constant mask. Invert it so that the bits being masked out are
9253 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9254 // follow the sign bit for uniformity.
9255 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9256 unsigned NotMaskLZ = countLeadingZeros(NotMask);
9257 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
9258 unsigned NotMaskTZ = countTrailingZeros(NotMask);
9259 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9260 if (NotMaskLZ == 64) return Result; // All zero mask.
9262 // See if we have a continuous run of bits. If so, we have 0*1+0*
9263 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9266 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9267 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9268 NotMaskLZ -= 64-V.getValueSizeInBits();
9270 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9271 switch (MaskedBytes) {
9275 default: return Result; // All one mask, or 5-byte mask.
9278 // Verify that the first bit starts at a multiple of mask so that the access
9279 // is aligned the same as the access width.
9280 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9282 Result.first = MaskedBytes;
9283 Result.second = NotMaskTZ/8;
9288 /// Check to see if IVal is something that provides a value as specified by
9289 /// MaskInfo. If so, replace the specified store with a narrower store of
9292 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9293 SDValue IVal, StoreSDNode *St,
9295 unsigned NumBytes = MaskInfo.first;
9296 unsigned ByteShift = MaskInfo.second;
9297 SelectionDAG &DAG = DC->getDAG();
9299 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9300 // that uses this. If not, this is not a replacement.
9301 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9302 ByteShift*8, (ByteShift+NumBytes)*8);
9303 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9305 // Check that it is legal on the target to do this. It is legal if the new
9306 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9308 MVT VT = MVT::getIntegerVT(NumBytes*8);
9309 if (!DC->isTypeLegal(VT))
9312 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9313 // shifted by ByteShift and truncated down to NumBytes.
9315 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9316 DAG.getConstant(ByteShift*8,
9317 DC->getShiftAmountTy(IVal.getValueType())));
9319 // Figure out the offset for the store and the alignment of the access.
9321 unsigned NewAlign = St->getAlignment();
9323 if (DAG.getTargetLoweringInfo().isLittleEndian())
9324 StOffset = ByteShift;
9326 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9328 SDValue Ptr = St->getBasePtr();
9330 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9331 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9332 NewAlign = MinAlign(NewAlign, StOffset);
9335 // Truncate down to the new size.
9336 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9339 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9340 St->getPointerInfo().getWithOffset(StOffset),
9341 false, false, NewAlign).getNode();
9345 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9346 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9347 /// narrowing the load and store if it would end up being a win for performance
9349 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9350 StoreSDNode *ST = cast<StoreSDNode>(N);
9351 if (ST->isVolatile())
9354 SDValue Chain = ST->getChain();
9355 SDValue Value = ST->getValue();
9356 SDValue Ptr = ST->getBasePtr();
9357 EVT VT = Value.getValueType();
9359 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9362 unsigned Opc = Value.getOpcode();
9364 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9365 // is a byte mask indicating a consecutive number of bytes, check to see if
9366 // Y is known to provide just those bytes. If so, we try to replace the
9367 // load + replace + store sequence with a single (narrower) store, which makes
9369 if (Opc == ISD::OR) {
9370 std::pair<unsigned, unsigned> MaskedLoad;
9371 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9372 if (MaskedLoad.first)
9373 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9374 Value.getOperand(1), ST,this))
9375 return SDValue(NewST, 0);
9377 // Or is commutative, so try swapping X and Y.
9378 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9379 if (MaskedLoad.first)
9380 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9381 Value.getOperand(0), ST,this))
9382 return SDValue(NewST, 0);
9385 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9386 Value.getOperand(1).getOpcode() != ISD::Constant)
9389 SDValue N0 = Value.getOperand(0);
9390 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9391 Chain == SDValue(N0.getNode(), 1)) {
9392 LoadSDNode *LD = cast<LoadSDNode>(N0);
9393 if (LD->getBasePtr() != Ptr ||
9394 LD->getPointerInfo().getAddrSpace() !=
9395 ST->getPointerInfo().getAddrSpace())
9398 // Find the type to narrow it the load / op / store to.
9399 SDValue N1 = Value.getOperand(1);
9400 unsigned BitWidth = N1.getValueSizeInBits();
9401 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9402 if (Opc == ISD::AND)
9403 Imm ^= APInt::getAllOnesValue(BitWidth);
9404 if (Imm == 0 || Imm.isAllOnesValue())
9406 unsigned ShAmt = Imm.countTrailingZeros();
9407 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9408 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9409 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9410 while (NewBW < BitWidth &&
9411 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9412 TLI.isNarrowingProfitable(VT, NewVT))) {
9413 NewBW = NextPowerOf2(NewBW);
9414 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9416 if (NewBW >= BitWidth)
9419 // If the lsb changed does not start at the type bitwidth boundary,
9420 // start at the previous one.
9422 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9423 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9424 std::min(BitWidth, ShAmt + NewBW));
9425 if ((Imm & Mask) == Imm) {
9426 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9427 if (Opc == ISD::AND)
9428 NewImm ^= APInt::getAllOnesValue(NewBW);
9429 uint64_t PtrOff = ShAmt / 8;
9430 // For big endian targets, we need to adjust the offset to the pointer to
9431 // load the correct bytes.
9432 if (TLI.isBigEndian())
9433 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9435 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9436 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9437 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9440 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9441 Ptr.getValueType(), Ptr,
9442 DAG.getConstant(PtrOff, Ptr.getValueType()));
9443 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9444 LD->getChain(), NewPtr,
9445 LD->getPointerInfo().getWithOffset(PtrOff),
9446 LD->isVolatile(), LD->isNonTemporal(),
9447 LD->isInvariant(), NewAlign,
9449 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9450 DAG.getConstant(NewImm, NewVT));
9451 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9453 ST->getPointerInfo().getWithOffset(PtrOff),
9454 false, false, NewAlign);
9456 AddToWorklist(NewPtr.getNode());
9457 AddToWorklist(NewLD.getNode());
9458 AddToWorklist(NewVal.getNode());
9459 WorklistRemover DeadNodes(*this);
9460 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9469 /// For a given floating point load / store pair, if the load value isn't used
9470 /// by any other operations, then consider transforming the pair to integer
9471 /// load / store operations if the target deems the transformation profitable.
9472 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9473 StoreSDNode *ST = cast<StoreSDNode>(N);
9474 SDValue Chain = ST->getChain();
9475 SDValue Value = ST->getValue();
9476 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9477 Value.hasOneUse() &&
9478 Chain == SDValue(Value.getNode(), 1)) {
9479 LoadSDNode *LD = cast<LoadSDNode>(Value);
9480 EVT VT = LD->getMemoryVT();
9481 if (!VT.isFloatingPoint() ||
9482 VT != ST->getMemoryVT() ||
9483 LD->isNonTemporal() ||
9484 ST->isNonTemporal() ||
9485 LD->getPointerInfo().getAddrSpace() != 0 ||
9486 ST->getPointerInfo().getAddrSpace() != 0)
9489 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9490 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9491 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9492 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9493 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9496 unsigned LDAlign = LD->getAlignment();
9497 unsigned STAlign = ST->getAlignment();
9498 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9499 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9500 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9503 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9504 LD->getChain(), LD->getBasePtr(),
9505 LD->getPointerInfo(),
9506 false, false, false, LDAlign);
9508 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9509 NewLD, ST->getBasePtr(),
9510 ST->getPointerInfo(),
9511 false, false, STAlign);
9513 AddToWorklist(NewLD.getNode());
9514 AddToWorklist(NewST.getNode());
9515 WorklistRemover DeadNodes(*this);
9516 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9524 /// Helper struct to parse and store a memory address as base + index + offset.
9525 /// We ignore sign extensions when it is safe to do so.
9526 /// The following two expressions are not equivalent. To differentiate we need
9527 /// to store whether there was a sign extension involved in the index
9529 /// (load (i64 add (i64 copyfromreg %c)
9530 /// (i64 signextend (add (i8 load %index)
9534 /// (load (i64 add (i64 copyfromreg %c)
9535 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9537 struct BaseIndexOffset {
9541 bool IsIndexSignExt;
9543 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9545 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9546 bool IsIndexSignExt) :
9547 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9549 bool equalBaseIndex(const BaseIndexOffset &Other) {
9550 return Other.Base == Base && Other.Index == Index &&
9551 Other.IsIndexSignExt == IsIndexSignExt;
9554 /// Parses tree in Ptr for base, index, offset addresses.
9555 static BaseIndexOffset match(SDValue Ptr) {
9556 bool IsIndexSignExt = false;
9558 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9559 // instruction, then it could be just the BASE or everything else we don't
9560 // know how to handle. Just use Ptr as BASE and give up.
9561 if (Ptr->getOpcode() != ISD::ADD)
9562 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9564 // We know that we have at least an ADD instruction. Try to pattern match
9565 // the simple case of BASE + OFFSET.
9566 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9567 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9568 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9572 // Inside a loop the current BASE pointer is calculated using an ADD and a
9573 // MUL instruction. In this case Ptr is the actual BASE pointer.
9574 // (i64 add (i64 %array_ptr)
9575 // (i64 mul (i64 %induction_var)
9576 // (i64 %element_size)))
9577 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9578 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9580 // Look at Base + Index + Offset cases.
9581 SDValue Base = Ptr->getOperand(0);
9582 SDValue IndexOffset = Ptr->getOperand(1);
9584 // Skip signextends.
9585 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9586 IndexOffset = IndexOffset->getOperand(0);
9587 IsIndexSignExt = true;
9590 // Either the case of Base + Index (no offset) or something else.
9591 if (IndexOffset->getOpcode() != ISD::ADD)
9592 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9594 // Now we have the case of Base + Index + offset.
9595 SDValue Index = IndexOffset->getOperand(0);
9596 SDValue Offset = IndexOffset->getOperand(1);
9598 if (!isa<ConstantSDNode>(Offset))
9599 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9601 // Ignore signextends.
9602 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9603 Index = Index->getOperand(0);
9604 IsIndexSignExt = true;
9605 } else IsIndexSignExt = false;
9607 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9608 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9612 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9613 /// is located in a sequence of memory operations connected by a chain.
9615 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9616 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9617 // Ptr to the mem node.
9618 LSBaseSDNode *MemNode;
9619 // Offset from the base ptr.
9620 int64_t OffsetFromBase;
9621 // What is the sequence number of this mem node.
9622 // Lowest mem operand in the DAG starts at zero.
9623 unsigned SequenceNum;
9626 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9627 EVT MemVT = St->getMemoryVT();
9628 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9629 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9630 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9632 // Don't merge vectors into wider inputs.
9633 if (MemVT.isVector() || !MemVT.isSimple())
9636 // Perform an early exit check. Do not bother looking at stored values that
9637 // are not constants or loads.
9638 SDValue StoredVal = St->getValue();
9639 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9640 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9644 // Only look at ends of store sequences.
9645 SDValue Chain = SDValue(St, 0);
9646 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9649 // This holds the base pointer, index, and the offset in bytes from the base
9651 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9653 // We must have a base and an offset.
9654 if (!BasePtr.Base.getNode())
9657 // Do not handle stores to undef base pointers.
9658 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9661 // Save the LoadSDNodes that we find in the chain.
9662 // We need to make sure that these nodes do not interfere with
9663 // any of the store nodes.
9664 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9666 // Save the StoreSDNodes that we find in the chain.
9667 SmallVector<MemOpLink, 8> StoreNodes;
9669 // Walk up the chain and look for nodes with offsets from the same
9670 // base pointer. Stop when reaching an instruction with a different kind
9671 // or instruction which has a different base pointer.
9673 StoreSDNode *Index = St;
9675 // If the chain has more than one use, then we can't reorder the mem ops.
9676 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9679 // Find the base pointer and offset for this memory node.
9680 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9682 // Check that the base pointer is the same as the original one.
9683 if (!Ptr.equalBaseIndex(BasePtr))
9686 // Check that the alignment is the same.
9687 if (Index->getAlignment() != St->getAlignment())
9690 // The memory operands must not be volatile.
9691 if (Index->isVolatile() || Index->isIndexed())
9695 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9696 if (St->isTruncatingStore())
9699 // The stored memory type must be the same.
9700 if (Index->getMemoryVT() != MemVT)
9703 // We do not allow unaligned stores because we want to prevent overriding
9705 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9708 // We found a potential memory operand to merge.
9709 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9711 // Find the next memory operand in the chain. If the next operand in the
9712 // chain is a store then move up and continue the scan with the next
9713 // memory operand. If the next operand is a load save it and use alias
9714 // information to check if it interferes with anything.
9715 SDNode *NextInChain = Index->getChain().getNode();
9717 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9718 // We found a store node. Use it for the next iteration.
9721 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9722 if (Ldn->isVolatile()) {
9727 // Save the load node for later. Continue the scan.
9728 AliasLoadNodes.push_back(Ldn);
9729 NextInChain = Ldn->getChain().getNode();
9738 // Check if there is anything to merge.
9739 if (StoreNodes.size() < 2)
9742 // Sort the memory operands according to their distance from the base pointer.
9743 std::sort(StoreNodes.begin(), StoreNodes.end(),
9744 [](MemOpLink LHS, MemOpLink RHS) {
9745 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9746 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9747 LHS.SequenceNum > RHS.SequenceNum);
9750 // Scan the memory operations on the chain and find the first non-consecutive
9751 // store memory address.
9752 unsigned LastConsecutiveStore = 0;
9753 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9754 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9756 // Check that the addresses are consecutive starting from the second
9757 // element in the list of stores.
9759 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9760 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9765 // Check if this store interferes with any of the loads that we found.
9766 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9767 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9771 // We found a load that alias with this store. Stop the sequence.
9775 // Mark this node as useful.
9776 LastConsecutiveStore = i;
9779 // The node with the lowest store address.
9780 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9782 // Store the constants into memory as one consecutive store.
9784 unsigned LastLegalType = 0;
9785 unsigned LastLegalVectorType = 0;
9786 bool NonZero = false;
9787 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9788 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9789 SDValue StoredVal = St->getValue();
9791 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9792 NonZero |= !C->isNullValue();
9793 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9794 NonZero |= !C->getConstantFPValue()->isNullValue();
9800 // Find a legal type for the constant store.
9801 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9802 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9803 if (TLI.isTypeLegal(StoreTy))
9804 LastLegalType = i+1;
9805 // Or check whether a truncstore is legal.
9806 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9807 TargetLowering::TypePromoteInteger) {
9808 EVT LegalizedStoredValueTy =
9809 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9810 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9811 LastLegalType = i+1;
9814 // Find a legal type for the vector store.
9815 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9816 if (TLI.isTypeLegal(Ty))
9817 LastLegalVectorType = i + 1;
9820 // We only use vectors if the constant is known to be zero and the
9821 // function is not marked with the noimplicitfloat attribute.
9822 if (NonZero || NoVectors)
9823 LastLegalVectorType = 0;
9825 // Check if we found a legal integer type to store.
9826 if (LastLegalType == 0 && LastLegalVectorType == 0)
9829 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9830 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9832 // Make sure we have something to merge.
9836 unsigned EarliestNodeUsed = 0;
9837 for (unsigned i=0; i < NumElem; ++i) {
9838 // Find a chain for the new wide-store operand. Notice that some
9839 // of the store nodes that we found may not be selected for inclusion
9840 // in the wide store. The chain we use needs to be the chain of the
9841 // earliest store node which is *used* and replaced by the wide store.
9842 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9843 EarliestNodeUsed = i;
9846 // The earliest Node in the DAG.
9847 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9848 SDLoc DL(StoreNodes[0].MemNode);
9852 // Find a legal type for the vector store.
9853 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9854 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9855 StoredVal = DAG.getConstant(0, Ty);
9857 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9858 APInt StoreInt(StoreBW, 0);
9860 // Construct a single integer constant which is made of the smaller
9862 bool IsLE = TLI.isLittleEndian();
9863 for (unsigned i = 0; i < NumElem ; ++i) {
9864 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9865 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9866 SDValue Val = St->getValue();
9867 StoreInt<<=ElementSizeBytes*8;
9868 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9869 StoreInt|=C->getAPIntValue().zext(StoreBW);
9870 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9871 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9873 llvm_unreachable("Invalid constant element type");
9877 // Create the new Load and Store operations.
9878 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9879 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9882 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9883 FirstInChain->getBasePtr(),
9884 FirstInChain->getPointerInfo(),
9886 FirstInChain->getAlignment());
9888 // Replace the first store with the new store
9889 CombineTo(EarliestOp, NewStore);
9890 // Erase all other stores.
9891 for (unsigned i = 0; i < NumElem ; ++i) {
9892 if (StoreNodes[i].MemNode == EarliestOp)
9894 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9895 // ReplaceAllUsesWith will replace all uses that existed when it was
9896 // called, but graph optimizations may cause new ones to appear. For
9897 // example, the case in pr14333 looks like
9899 // St's chain -> St -> another store -> X
9901 // And the only difference from St to the other store is the chain.
9902 // When we change it's chain to be St's chain they become identical,
9903 // get CSEed and the net result is that X is now a use of St.
9904 // Since we know that St is redundant, just iterate.
9905 while (!St->use_empty())
9906 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9907 deleteAndRecombine(St);
9913 // Below we handle the case of multiple consecutive stores that
9914 // come from multiple consecutive loads. We merge them into a single
9915 // wide load and a single wide store.
9917 // Look for load nodes which are used by the stored values.
9918 SmallVector<MemOpLink, 8> LoadNodes;
9920 // Find acceptable loads. Loads need to have the same chain (token factor),
9921 // must not be zext, volatile, indexed, and they must be consecutive.
9922 BaseIndexOffset LdBasePtr;
9923 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9924 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9925 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9928 // Loads must only have one use.
9929 if (!Ld->hasNUsesOfValue(1, 0))
9932 // Check that the alignment is the same as the stores.
9933 if (Ld->getAlignment() != St->getAlignment())
9936 // The memory operands must not be volatile.
9937 if (Ld->isVolatile() || Ld->isIndexed())
9940 // We do not accept ext loads.
9941 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9944 // The stored memory type must be the same.
9945 if (Ld->getMemoryVT() != MemVT)
9948 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9949 // If this is not the first ptr that we check.
9950 if (LdBasePtr.Base.getNode()) {
9951 // The base ptr must be the same.
9952 if (!LdPtr.equalBaseIndex(LdBasePtr))
9955 // Check that all other base pointers are the same as this one.
9959 // We found a potential memory operand to merge.
9960 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9963 if (LoadNodes.size() < 2)
9966 // If we have load/store pair instructions and we only have two values,
9968 unsigned RequiredAlignment;
9969 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9970 St->getAlignment() >= RequiredAlignment)
9973 // Scan the memory operations on the chain and find the first non-consecutive
9974 // load memory address. These variables hold the index in the store node
9976 unsigned LastConsecutiveLoad = 0;
9977 // This variable refers to the size and not index in the array.
9978 unsigned LastLegalVectorType = 0;
9979 unsigned LastLegalIntegerType = 0;
9980 StartAddress = LoadNodes[0].OffsetFromBase;
9981 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9982 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9983 // All loads much share the same chain.
9984 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9987 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9988 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9990 LastConsecutiveLoad = i;
9992 // Find a legal type for the vector store.
9993 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9994 if (TLI.isTypeLegal(StoreTy))
9995 LastLegalVectorType = i + 1;
9997 // Find a legal type for the integer store.
9998 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9999 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10000 if (TLI.isTypeLegal(StoreTy))
10001 LastLegalIntegerType = i + 1;
10002 // Or check whether a truncstore and extload is legal.
10003 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10004 TargetLowering::TypePromoteInteger) {
10005 EVT LegalizedStoredValueTy =
10006 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10007 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10008 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10009 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10010 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10011 LastLegalIntegerType = i+1;
10015 // Only use vector types if the vector type is larger than the integer type.
10016 // If they are the same, use integers.
10017 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10018 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10020 // We add +1 here because the LastXXX variables refer to location while
10021 // the NumElem refers to array/index size.
10022 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10023 NumElem = std::min(LastLegalType, NumElem);
10028 // The earliest Node in the DAG.
10029 unsigned EarliestNodeUsed = 0;
10030 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10031 for (unsigned i=1; i<NumElem; ++i) {
10032 // Find a chain for the new wide-store operand. Notice that some
10033 // of the store nodes that we found may not be selected for inclusion
10034 // in the wide store. The chain we use needs to be the chain of the
10035 // earliest store node which is *used* and replaced by the wide store.
10036 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10037 EarliestNodeUsed = i;
10040 // Find if it is better to use vectors or integers to load and store
10044 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10046 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10047 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10050 SDLoc LoadDL(LoadNodes[0].MemNode);
10051 SDLoc StoreDL(StoreNodes[0].MemNode);
10053 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10054 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10055 FirstLoad->getChain(),
10056 FirstLoad->getBasePtr(),
10057 FirstLoad->getPointerInfo(),
10058 false, false, false,
10059 FirstLoad->getAlignment());
10061 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10062 FirstInChain->getBasePtr(),
10063 FirstInChain->getPointerInfo(), false, false,
10064 FirstInChain->getAlignment());
10066 // Replace one of the loads with the new load.
10067 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10068 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10069 SDValue(NewLoad.getNode(), 1));
10071 // Remove the rest of the load chains.
10072 for (unsigned i = 1; i < NumElem ; ++i) {
10073 // Replace all chain users of the old load nodes with the chain of the new
10075 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10076 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10079 // Replace the first store with the new store.
10080 CombineTo(EarliestOp, NewStore);
10081 // Erase all other stores.
10082 for (unsigned i = 0; i < NumElem ; ++i) {
10083 // Remove all Store nodes.
10084 if (StoreNodes[i].MemNode == EarliestOp)
10086 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10087 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10088 deleteAndRecombine(St);
10094 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10095 StoreSDNode *ST = cast<StoreSDNode>(N);
10096 SDValue Chain = ST->getChain();
10097 SDValue Value = ST->getValue();
10098 SDValue Ptr = ST->getBasePtr();
10100 // If this is a store of a bit convert, store the input value if the
10101 // resultant store does not need a higher alignment than the original.
10102 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10103 ST->isUnindexed()) {
10104 unsigned OrigAlign = ST->getAlignment();
10105 EVT SVT = Value.getOperand(0).getValueType();
10106 unsigned Align = TLI.getDataLayout()->
10107 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10108 if (Align <= OrigAlign &&
10109 ((!LegalOperations && !ST->isVolatile()) ||
10110 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10111 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10112 Ptr, ST->getPointerInfo(), ST->isVolatile(),
10113 ST->isNonTemporal(), OrigAlign,
10117 // Turn 'store undef, Ptr' -> nothing.
10118 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10121 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10122 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10123 // NOTE: If the original store is volatile, this transform must not increase
10124 // the number of stores. For example, on x86-32 an f64 can be stored in one
10125 // processor operation but an i64 (which is not legal) requires two. So the
10126 // transform should not be done in this case.
10127 if (Value.getOpcode() != ISD::TargetConstantFP) {
10129 switch (CFP->getSimpleValueType(0).SimpleTy) {
10130 default: llvm_unreachable("Unknown FP type");
10131 case MVT::f16: // We don't do this for these yet.
10137 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10138 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10139 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10140 bitcastToAPInt().getZExtValue(), MVT::i32);
10141 return DAG.getStore(Chain, SDLoc(N), Tmp,
10142 Ptr, ST->getMemOperand());
10146 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10147 !ST->isVolatile()) ||
10148 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10149 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10150 getZExtValue(), MVT::i64);
10151 return DAG.getStore(Chain, SDLoc(N), Tmp,
10152 Ptr, ST->getMemOperand());
10155 if (!ST->isVolatile() &&
10156 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10157 // Many FP stores are not made apparent until after legalize, e.g. for
10158 // argument passing. Since this is so common, custom legalize the
10159 // 64-bit integer store into two 32-bit stores.
10160 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10161 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10162 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10163 if (TLI.isBigEndian()) std::swap(Lo, Hi);
10165 unsigned Alignment = ST->getAlignment();
10166 bool isVolatile = ST->isVolatile();
10167 bool isNonTemporal = ST->isNonTemporal();
10168 AAMDNodes AAInfo = ST->getAAInfo();
10170 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10171 Ptr, ST->getPointerInfo(),
10172 isVolatile, isNonTemporal,
10173 ST->getAlignment(), AAInfo);
10174 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10175 DAG.getConstant(4, Ptr.getValueType()));
10176 Alignment = MinAlign(Alignment, 4U);
10177 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10178 Ptr, ST->getPointerInfo().getWithOffset(4),
10179 isVolatile, isNonTemporal,
10180 Alignment, AAInfo);
10181 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10190 // Try to infer better alignment information than the store already has.
10191 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10192 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10193 if (Align > ST->getAlignment())
10194 return DAG.getTruncStore(Chain, SDLoc(N), Value,
10195 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10196 ST->isVolatile(), ST->isNonTemporal(), Align,
10201 // Try transforming a pair floating point load / store ops to integer
10202 // load / store ops.
10203 SDValue NewST = TransformFPLoadStorePair(N);
10204 if (NewST.getNode())
10207 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10208 : DAG.getSubtarget().useAA();
10210 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10211 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10214 if (UseAA && ST->isUnindexed()) {
10215 // Walk up chain skipping non-aliasing memory nodes.
10216 SDValue BetterChain = FindBetterChain(N, Chain);
10218 // If there is a better chain.
10219 if (Chain != BetterChain) {
10222 // Replace the chain to avoid dependency.
10223 if (ST->isTruncatingStore()) {
10224 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10225 ST->getMemoryVT(), ST->getMemOperand());
10227 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10228 ST->getMemOperand());
10231 // Create token to keep both nodes around.
10232 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10233 MVT::Other, Chain, ReplStore);
10235 // Make sure the new and old chains are cleaned up.
10236 AddToWorklist(Token.getNode());
10238 // Don't add users to work list.
10239 return CombineTo(N, Token, false);
10243 // Try transforming N to an indexed store.
10244 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10245 return SDValue(N, 0);
10247 // FIXME: is there such a thing as a truncating indexed store?
10248 if (ST->isTruncatingStore() && ST->isUnindexed() &&
10249 Value.getValueType().isInteger()) {
10250 // See if we can simplify the input to this truncstore with knowledge that
10251 // only the low bits are being used. For example:
10252 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
10254 GetDemandedBits(Value,
10255 APInt::getLowBitsSet(
10256 Value.getValueType().getScalarType().getSizeInBits(),
10257 ST->getMemoryVT().getScalarType().getSizeInBits()));
10258 AddToWorklist(Value.getNode());
10259 if (Shorter.getNode())
10260 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10261 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10263 // Otherwise, see if we can simplify the operation with
10264 // SimplifyDemandedBits, which only works if the value has a single use.
10265 if (SimplifyDemandedBits(Value,
10266 APInt::getLowBitsSet(
10267 Value.getValueType().getScalarType().getSizeInBits(),
10268 ST->getMemoryVT().getScalarType().getSizeInBits())))
10269 return SDValue(N, 0);
10272 // If this is a load followed by a store to the same location, then the store
10274 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10275 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10276 ST->isUnindexed() && !ST->isVolatile() &&
10277 // There can't be any side effects between the load and store, such as
10278 // a call or store.
10279 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10280 // The store is dead, remove it.
10285 // If this is a store followed by a store with the same value to the same
10286 // location, then the store is dead/noop.
10287 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10288 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10289 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10290 ST1->isUnindexed() && !ST1->isVolatile()) {
10291 // The store is dead, remove it.
10296 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10297 // truncating store. We can do this even if this is already a truncstore.
10298 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10299 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10300 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10301 ST->getMemoryVT())) {
10302 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10303 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10306 // Only perform this optimization before the types are legal, because we
10307 // don't want to perform this optimization on every DAGCombine invocation.
10309 bool EverChanged = false;
10312 // There can be multiple store sequences on the same chain.
10313 // Keep trying to merge store sequences until we are unable to do so
10314 // or until we merge the last store on the chain.
10315 bool Changed = MergeConsecutiveStores(ST);
10316 EverChanged |= Changed;
10317 if (!Changed) break;
10318 } while (ST->getOpcode() != ISD::DELETED_NODE);
10321 return SDValue(N, 0);
10324 return ReduceLoadOpStoreWidth(N);
10327 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10328 SDValue InVec = N->getOperand(0);
10329 SDValue InVal = N->getOperand(1);
10330 SDValue EltNo = N->getOperand(2);
10333 // If the inserted element is an UNDEF, just use the input vector.
10334 if (InVal.getOpcode() == ISD::UNDEF)
10337 EVT VT = InVec.getValueType();
10339 // If we can't generate a legal BUILD_VECTOR, exit
10340 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10343 // Check that we know which element is being inserted
10344 if (!isa<ConstantSDNode>(EltNo))
10346 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10348 // Canonicalize insert_vector_elt dag nodes.
10350 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10351 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10353 // Do this only if the child insert_vector node has one use; also
10354 // do this only if indices are both constants and Idx1 < Idx0.
10355 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10356 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10357 unsigned OtherElt =
10358 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10359 if (Elt < OtherElt) {
10361 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10362 InVec.getOperand(0), InVal, EltNo);
10363 AddToWorklist(NewOp.getNode());
10364 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10365 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10369 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10370 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10371 // vector elements.
10372 SmallVector<SDValue, 8> Ops;
10373 // Do not combine these two vectors if the output vector will not replace
10374 // the input vector.
10375 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10376 Ops.append(InVec.getNode()->op_begin(),
10377 InVec.getNode()->op_end());
10378 } else if (InVec.getOpcode() == ISD::UNDEF) {
10379 unsigned NElts = VT.getVectorNumElements();
10380 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10385 // Insert the element
10386 if (Elt < Ops.size()) {
10387 // All the operands of BUILD_VECTOR must have the same type;
10388 // we enforce that here.
10389 EVT OpVT = Ops[0].getValueType();
10390 if (InVal.getValueType() != OpVT)
10391 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10392 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10393 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10397 // Return the new vector
10398 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10401 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10402 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10403 EVT ResultVT = EVE->getValueType(0);
10404 EVT VecEltVT = InVecVT.getVectorElementType();
10405 unsigned Align = OriginalLoad->getAlignment();
10406 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10407 VecEltVT.getTypeForEVT(*DAG.getContext()));
10409 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10414 SDValue NewPtr = OriginalLoad->getBasePtr();
10416 EVT PtrType = NewPtr.getValueType();
10417 MachinePointerInfo MPI;
10418 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10419 int Elt = ConstEltNo->getZExtValue();
10420 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10421 if (TLI.isBigEndian())
10422 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10423 Offset = DAG.getConstant(PtrOff, PtrType);
10424 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10426 Offset = DAG.getNode(
10427 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10428 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10429 if (TLI.isBigEndian())
10430 Offset = DAG.getNode(
10431 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10432 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10433 MPI = OriginalLoad->getPointerInfo();
10435 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10437 // The replacement we need to do here is a little tricky: we need to
10438 // replace an extractelement of a load with a load.
10439 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10440 // Note that this replacement assumes that the extractvalue is the only
10441 // use of the load; that's okay because we don't want to perform this
10442 // transformation in other cases anyway.
10445 if (ResultVT.bitsGT(VecEltVT)) {
10446 // If the result type of vextract is wider than the load, then issue an
10447 // extending load instead.
10448 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10452 Load = DAG.getExtLoad(
10453 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10454 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10455 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10456 Chain = Load.getValue(1);
10458 Load = DAG.getLoad(
10459 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10460 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10461 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10462 Chain = Load.getValue(1);
10463 if (ResultVT.bitsLT(VecEltVT))
10464 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10466 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10468 WorklistRemover DeadNodes(*this);
10469 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10470 SDValue To[] = { Load, Chain };
10471 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10472 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10473 // worklist explicitly as well.
10474 AddToWorklist(Load.getNode());
10475 AddUsersToWorklist(Load.getNode()); // Add users too
10476 // Make sure to revisit this node to clean it up; it will usually be dead.
10477 AddToWorklist(EVE);
10479 return SDValue(EVE, 0);
10482 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10483 // (vextract (scalar_to_vector val, 0) -> val
10484 SDValue InVec = N->getOperand(0);
10485 EVT VT = InVec.getValueType();
10486 EVT NVT = N->getValueType(0);
10488 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10489 // Check if the result type doesn't match the inserted element type. A
10490 // SCALAR_TO_VECTOR may truncate the inserted element and the
10491 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10492 SDValue InOp = InVec.getOperand(0);
10493 if (InOp.getValueType() != NVT) {
10494 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10495 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10500 SDValue EltNo = N->getOperand(1);
10501 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10503 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10504 // We only perform this optimization before the op legalization phase because
10505 // we may introduce new vector instructions which are not backed by TD
10506 // patterns. For example on AVX, extracting elements from a wide vector
10507 // without using extract_subvector. However, if we can find an underlying
10508 // scalar value, then we can always use that.
10509 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10511 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10512 int NumElem = VT.getVectorNumElements();
10513 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10514 // Find the new index to extract from.
10515 int OrigElt = SVOp->getMaskElt(Elt);
10517 // Extracting an undef index is undef.
10519 return DAG.getUNDEF(NVT);
10521 // Select the right vector half to extract from.
10523 if (OrigElt < NumElem) {
10524 SVInVec = InVec->getOperand(0);
10526 SVInVec = InVec->getOperand(1);
10527 OrigElt -= NumElem;
10530 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10531 SDValue InOp = SVInVec.getOperand(OrigElt);
10532 if (InOp.getValueType() != NVT) {
10533 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10534 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10540 // FIXME: We should handle recursing on other vector shuffles and
10541 // scalar_to_vector here as well.
10543 if (!LegalOperations) {
10544 EVT IndexTy = TLI.getVectorIdxTy();
10545 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10546 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10550 bool BCNumEltsChanged = false;
10551 EVT ExtVT = VT.getVectorElementType();
10554 // If the result of load has to be truncated, then it's not necessarily
10556 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10559 if (InVec.getOpcode() == ISD::BITCAST) {
10560 // Don't duplicate a load with other uses.
10561 if (!InVec.hasOneUse())
10564 EVT BCVT = InVec.getOperand(0).getValueType();
10565 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10567 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10568 BCNumEltsChanged = true;
10569 InVec = InVec.getOperand(0);
10570 ExtVT = BCVT.getVectorElementType();
10573 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10574 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10575 ISD::isNormalLoad(InVec.getNode()) &&
10576 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10577 SDValue Index = N->getOperand(1);
10578 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10579 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10583 // Perform only after legalization to ensure build_vector / vector_shuffle
10584 // optimizations have already been done.
10585 if (!LegalOperations) return SDValue();
10587 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10588 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10589 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10592 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10594 LoadSDNode *LN0 = nullptr;
10595 const ShuffleVectorSDNode *SVN = nullptr;
10596 if (ISD::isNormalLoad(InVec.getNode())) {
10597 LN0 = cast<LoadSDNode>(InVec);
10598 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10599 InVec.getOperand(0).getValueType() == ExtVT &&
10600 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10601 // Don't duplicate a load with other uses.
10602 if (!InVec.hasOneUse())
10605 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10606 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10607 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10609 // (load $addr+1*size)
10611 // Don't duplicate a load with other uses.
10612 if (!InVec.hasOneUse())
10615 // If the bit convert changed the number of elements, it is unsafe
10616 // to examine the mask.
10617 if (BCNumEltsChanged)
10620 // Select the input vector, guarding against out of range extract vector.
10621 unsigned NumElems = VT.getVectorNumElements();
10622 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10623 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10625 if (InVec.getOpcode() == ISD::BITCAST) {
10626 // Don't duplicate a load with other uses.
10627 if (!InVec.hasOneUse())
10630 InVec = InVec.getOperand(0);
10632 if (ISD::isNormalLoad(InVec.getNode())) {
10633 LN0 = cast<LoadSDNode>(InVec);
10634 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10635 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10639 // Make sure we found a non-volatile load and the extractelement is
10641 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10644 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10646 return DAG.getUNDEF(LVT);
10648 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10654 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10655 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10656 // We perform this optimization post type-legalization because
10657 // the type-legalizer often scalarizes integer-promoted vectors.
10658 // Performing this optimization before may create bit-casts which
10659 // will be type-legalized to complex code sequences.
10660 // We perform this optimization only before the operation legalizer because we
10661 // may introduce illegal operations.
10662 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10665 unsigned NumInScalars = N->getNumOperands();
10667 EVT VT = N->getValueType(0);
10669 // Check to see if this is a BUILD_VECTOR of a bunch of values
10670 // which come from any_extend or zero_extend nodes. If so, we can create
10671 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10672 // optimizations. We do not handle sign-extend because we can't fill the sign
10674 EVT SourceType = MVT::Other;
10675 bool AllAnyExt = true;
10677 for (unsigned i = 0; i != NumInScalars; ++i) {
10678 SDValue In = N->getOperand(i);
10679 // Ignore undef inputs.
10680 if (In.getOpcode() == ISD::UNDEF) continue;
10682 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10683 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10685 // Abort if the element is not an extension.
10686 if (!ZeroExt && !AnyExt) {
10687 SourceType = MVT::Other;
10691 // The input is a ZeroExt or AnyExt. Check the original type.
10692 EVT InTy = In.getOperand(0).getValueType();
10694 // Check that all of the widened source types are the same.
10695 if (SourceType == MVT::Other)
10698 else if (InTy != SourceType) {
10699 // Multiple income types. Abort.
10700 SourceType = MVT::Other;
10704 // Check if all of the extends are ANY_EXTENDs.
10705 AllAnyExt &= AnyExt;
10708 // In order to have valid types, all of the inputs must be extended from the
10709 // same source type and all of the inputs must be any or zero extend.
10710 // Scalar sizes must be a power of two.
10711 EVT OutScalarTy = VT.getScalarType();
10712 bool ValidTypes = SourceType != MVT::Other &&
10713 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10714 isPowerOf2_32(SourceType.getSizeInBits());
10716 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10717 // turn into a single shuffle instruction.
10721 bool isLE = TLI.isLittleEndian();
10722 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10723 assert(ElemRatio > 1 && "Invalid element size ratio");
10724 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10725 DAG.getConstant(0, SourceType);
10727 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10728 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10730 // Populate the new build_vector
10731 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10732 SDValue Cast = N->getOperand(i);
10733 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10734 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10735 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10737 if (Cast.getOpcode() == ISD::UNDEF)
10738 In = DAG.getUNDEF(SourceType);
10740 In = Cast->getOperand(0);
10741 unsigned Index = isLE ? (i * ElemRatio) :
10742 (i * ElemRatio + (ElemRatio - 1));
10744 assert(Index < Ops.size() && "Invalid index");
10748 // The type of the new BUILD_VECTOR node.
10749 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10750 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10751 "Invalid vector size");
10752 // Check if the new vector type is legal.
10753 if (!isTypeLegal(VecVT)) return SDValue();
10755 // Make the new BUILD_VECTOR.
10756 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10758 // The new BUILD_VECTOR node has the potential to be further optimized.
10759 AddToWorklist(BV.getNode());
10760 // Bitcast to the desired type.
10761 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10764 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10765 EVT VT = N->getValueType(0);
10767 unsigned NumInScalars = N->getNumOperands();
10770 EVT SrcVT = MVT::Other;
10771 unsigned Opcode = ISD::DELETED_NODE;
10772 unsigned NumDefs = 0;
10774 for (unsigned i = 0; i != NumInScalars; ++i) {
10775 SDValue In = N->getOperand(i);
10776 unsigned Opc = In.getOpcode();
10778 if (Opc == ISD::UNDEF)
10781 // If all scalar values are floats and converted from integers.
10782 if (Opcode == ISD::DELETED_NODE &&
10783 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10790 EVT InVT = In.getOperand(0).getValueType();
10792 // If all scalar values are typed differently, bail out. It's chosen to
10793 // simplify BUILD_VECTOR of integer types.
10794 if (SrcVT == MVT::Other)
10801 // If the vector has just one element defined, it's not worth to fold it into
10802 // a vectorized one.
10806 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10807 && "Should only handle conversion from integer to float.");
10808 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10810 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10812 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10815 SmallVector<SDValue, 8> Opnds;
10816 for (unsigned i = 0; i != NumInScalars; ++i) {
10817 SDValue In = N->getOperand(i);
10819 if (In.getOpcode() == ISD::UNDEF)
10820 Opnds.push_back(DAG.getUNDEF(SrcVT));
10822 Opnds.push_back(In.getOperand(0));
10824 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10825 AddToWorklist(BV.getNode());
10827 return DAG.getNode(Opcode, dl, VT, BV);
10830 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10831 unsigned NumInScalars = N->getNumOperands();
10833 EVT VT = N->getValueType(0);
10835 // A vector built entirely of undefs is undef.
10836 if (ISD::allOperandsUndef(N))
10837 return DAG.getUNDEF(VT);
10839 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10843 V = reduceBuildVecConvertToConvertBuildVec(N);
10847 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10848 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10849 // at most two distinct vectors, turn this into a shuffle node.
10851 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10852 if (!isTypeLegal(VT))
10855 // May only combine to shuffle after legalize if shuffle is legal.
10856 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10859 SDValue VecIn1, VecIn2;
10860 bool UsesZeroVector = false;
10861 for (unsigned i = 0; i != NumInScalars; ++i) {
10862 SDValue Op = N->getOperand(i);
10863 // Ignore undef inputs.
10864 if (Op.getOpcode() == ISD::UNDEF) continue;
10866 // See if we can combine this build_vector into a blend with a zero vector.
10867 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10868 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10869 (Op.getOpcode() == ISD::ConstantFP &&
10870 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10871 UsesZeroVector = true;
10875 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10876 // constant index, bail out.
10877 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10878 !isa<ConstantSDNode>(Op.getOperand(1))) {
10879 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10883 // We allow up to two distinct input vectors.
10884 SDValue ExtractedFromVec = Op.getOperand(0);
10885 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10888 if (!VecIn1.getNode()) {
10889 VecIn1 = ExtractedFromVec;
10890 } else if (!VecIn2.getNode() && !UsesZeroVector) {
10891 VecIn2 = ExtractedFromVec;
10893 // Too many inputs.
10894 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10899 // If everything is good, we can make a shuffle operation.
10900 if (VecIn1.getNode()) {
10901 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
10902 SmallVector<int, 8> Mask;
10903 for (unsigned i = 0; i != NumInScalars; ++i) {
10904 unsigned Opcode = N->getOperand(i).getOpcode();
10905 if (Opcode == ISD::UNDEF) {
10906 Mask.push_back(-1);
10910 // Operands can also be zero.
10911 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
10912 assert(UsesZeroVector &&
10913 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
10914 "Unexpected node found!");
10915 Mask.push_back(NumInScalars+i);
10919 // If extracting from the first vector, just use the index directly.
10920 SDValue Extract = N->getOperand(i);
10921 SDValue ExtVal = Extract.getOperand(1);
10922 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10923 if (Extract.getOperand(0) == VecIn1) {
10924 Mask.push_back(ExtIndex);
10928 // Otherwise, use InIdx + InputVecSize
10929 Mask.push_back(InNumElements + ExtIndex);
10932 // Avoid introducing illegal shuffles with zero.
10933 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
10936 // We can't generate a shuffle node with mismatched input and output types.
10937 // Attempt to transform a single input vector to the correct type.
10938 if ((VT != VecIn1.getValueType())) {
10939 // If the input vector type has a different base type to the output
10940 // vector type, bail out.
10941 EVT VTElemType = VT.getVectorElementType();
10942 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
10943 (VecIn2.getNode() &&
10944 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
10947 // If the input vector is too small, widen it.
10948 // We only support widening of vectors which are half the size of the
10949 // output registers. For example XMM->YMM widening on X86 with AVX.
10950 EVT VecInT = VecIn1.getValueType();
10951 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
10952 // If we only have one small input, widen it by adding undef values.
10953 if (!VecIn2.getNode())
10954 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
10955 DAG.getUNDEF(VecIn1.getValueType()));
10956 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
10957 // If we have two small inputs of the same type, try to concat them.
10958 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
10959 VecIn2 = SDValue(nullptr, 0);
10962 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
10963 // If the input vector is too large, try to split it.
10964 // We don't support having two input vectors that are too large.
10965 if (VecIn2.getNode())
10968 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
10971 // Try to replace VecIn1 with two extract_subvectors
10972 // No need to update the masks, they should still be correct.
10973 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
10974 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
10975 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
10976 DAG.getConstant(0, TLI.getVectorIdxTy()));
10977 UsesZeroVector = false;
10982 if (UsesZeroVector)
10983 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
10984 DAG.getConstantFP(0.0, VT);
10986 // If VecIn2 is unused then change it to undef.
10987 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10989 // Check that we were able to transform all incoming values to the same
10991 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10992 VecIn1.getValueType() != VT)
10995 // Return the new VECTOR_SHUFFLE node.
10999 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11005 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11006 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11007 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11008 // inputs come from at most two distinct vectors, turn this into a shuffle
11011 // If we only have one input vector, we don't need to do any concatenation.
11012 if (N->getNumOperands() == 1)
11013 return N->getOperand(0);
11015 // Check if all of the operands are undefs.
11016 EVT VT = N->getValueType(0);
11017 if (ISD::allOperandsUndef(N))
11018 return DAG.getUNDEF(VT);
11020 // Optimize concat_vectors where one of the vectors is undef.
11021 if (N->getNumOperands() == 2 &&
11022 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11023 SDValue In = N->getOperand(0);
11024 assert(In.getValueType().isVector() && "Must concat vectors");
11026 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11027 if (In->getOpcode() == ISD::BITCAST &&
11028 !In->getOperand(0)->getValueType(0).isVector()) {
11029 SDValue Scalar = In->getOperand(0);
11030 EVT SclTy = Scalar->getValueType(0);
11032 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11035 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11036 VT.getSizeInBits() / SclTy.getSizeInBits());
11037 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11040 SDLoc dl = SDLoc(N);
11041 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11042 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11046 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11047 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11048 if (N->getNumOperands() == 2 &&
11049 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
11050 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
11051 EVT VT = N->getValueType(0);
11052 SDValue N0 = N->getOperand(0);
11053 SDValue N1 = N->getOperand(1);
11054 SmallVector<SDValue, 8> Opnds;
11055 unsigned BuildVecNumElts = N0.getNumOperands();
11057 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
11058 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
11059 if (SclTy0.isFloatingPoint()) {
11060 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11061 Opnds.push_back(N0.getOperand(i));
11062 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11063 Opnds.push_back(N1.getOperand(i));
11065 // If BUILD_VECTOR are from built from integer, they may have different
11066 // operand types. Get the smaller type and truncate all operands to it.
11067 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
11068 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11069 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11070 N0.getOperand(i)));
11071 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11072 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11073 N1.getOperand(i)));
11076 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11079 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11080 // nodes often generate nop CONCAT_VECTOR nodes.
11081 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11082 // place the incoming vectors at the exact same location.
11083 SDValue SingleSource = SDValue();
11084 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11086 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11087 SDValue Op = N->getOperand(i);
11089 if (Op.getOpcode() == ISD::UNDEF)
11092 // Check if this is the identity extract:
11093 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11096 // Find the single incoming vector for the extract_subvector.
11097 if (SingleSource.getNode()) {
11098 if (Op.getOperand(0) != SingleSource)
11101 SingleSource = Op.getOperand(0);
11103 // Check the source type is the same as the type of the result.
11104 // If not, this concat may extend the vector, so we can not
11105 // optimize it away.
11106 if (SingleSource.getValueType() != N->getValueType(0))
11110 unsigned IdentityIndex = i * PartNumElem;
11111 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11112 // The extract index must be constant.
11116 // Check that we are reading from the identity index.
11117 if (CS->getZExtValue() != IdentityIndex)
11121 if (SingleSource.getNode())
11122 return SingleSource;
11127 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11128 EVT NVT = N->getValueType(0);
11129 SDValue V = N->getOperand(0);
11131 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11133 // (extract_subvec (concat V1, V2, ...), i)
11136 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11138 if (V->getOperand(0).getValueType() != NVT)
11140 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11141 unsigned NumElems = NVT.getVectorNumElements();
11142 assert((Idx % NumElems) == 0 &&
11143 "IDX in concat is not a multiple of the result vector length.");
11144 return V->getOperand(Idx / NumElems);
11148 if (V->getOpcode() == ISD::BITCAST)
11149 V = V.getOperand(0);
11151 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11153 // Handle only simple case where vector being inserted and vector
11154 // being extracted are of same type, and are half size of larger vectors.
11155 EVT BigVT = V->getOperand(0).getValueType();
11156 EVT SmallVT = V->getOperand(1).getValueType();
11157 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11160 // Only handle cases where both indexes are constants with the same type.
11161 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11162 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11164 if (InsIdx && ExtIdx &&
11165 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11166 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11168 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11170 // indices are equal or bit offsets are equal => V1
11171 // otherwise => (extract_subvec V1, ExtIdx)
11172 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11173 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11174 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11175 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11176 DAG.getNode(ISD::BITCAST, dl,
11177 N->getOperand(0).getValueType(),
11178 V->getOperand(0)), N->getOperand(1));
11185 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11186 SDValue V, SelectionDAG &DAG) {
11188 EVT VT = V.getValueType();
11190 switch (V.getOpcode()) {
11194 case ISD::CONCAT_VECTORS: {
11195 EVT OpVT = V->getOperand(0).getValueType();
11196 int OpSize = OpVT.getVectorNumElements();
11197 SmallBitVector OpUsedElements(OpSize, false);
11198 bool FoundSimplification = false;
11199 SmallVector<SDValue, 4> NewOps;
11200 NewOps.reserve(V->getNumOperands());
11201 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11202 SDValue Op = V->getOperand(i);
11203 bool OpUsed = false;
11204 for (int j = 0; j < OpSize; ++j)
11205 if (UsedElements[i * OpSize + j]) {
11206 OpUsedElements[j] = true;
11210 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11211 : DAG.getUNDEF(OpVT));
11212 FoundSimplification |= Op == NewOps.back();
11213 OpUsedElements.reset();
11215 if (FoundSimplification)
11216 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11220 case ISD::INSERT_SUBVECTOR: {
11221 SDValue BaseV = V->getOperand(0);
11222 SDValue SubV = V->getOperand(1);
11223 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11227 int SubSize = SubV.getValueType().getVectorNumElements();
11228 int Idx = IdxN->getZExtValue();
11229 bool SubVectorUsed = false;
11230 SmallBitVector SubUsedElements(SubSize, false);
11231 for (int i = 0; i < SubSize; ++i)
11232 if (UsedElements[i + Idx]) {
11233 SubVectorUsed = true;
11234 SubUsedElements[i] = true;
11235 UsedElements[i + Idx] = false;
11238 // Now recurse on both the base and sub vectors.
11239 SDValue SimplifiedSubV =
11241 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11242 : DAG.getUNDEF(SubV.getValueType());
11243 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11244 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11245 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11246 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11252 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11253 SDValue N1, SelectionDAG &DAG) {
11254 EVT VT = SVN->getValueType(0);
11255 int NumElts = VT.getVectorNumElements();
11256 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11257 for (int M : SVN->getMask())
11258 if (M >= 0 && M < NumElts)
11259 N0UsedElements[M] = true;
11260 else if (M >= NumElts)
11261 N1UsedElements[M - NumElts] = true;
11263 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11264 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11265 if (S0 == N0 && S1 == N1)
11268 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11271 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
11272 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11273 EVT VT = N->getValueType(0);
11274 unsigned NumElts = VT.getVectorNumElements();
11276 SDValue N0 = N->getOperand(0);
11277 SDValue N1 = N->getOperand(1);
11278 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11280 SmallVector<SDValue, 4> Ops;
11281 EVT ConcatVT = N0.getOperand(0).getValueType();
11282 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11283 unsigned NumConcats = NumElts / NumElemsPerConcat;
11285 // Look at every vector that's inserted. We're looking for exact
11286 // subvector-sized copies from a concatenated vector
11287 for (unsigned I = 0; I != NumConcats; ++I) {
11288 // Make sure we're dealing with a copy.
11289 unsigned Begin = I * NumElemsPerConcat;
11290 bool AllUndef = true, NoUndef = true;
11291 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11292 if (SVN->getMaskElt(J) >= 0)
11299 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11302 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11303 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11306 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11307 if (FirstElt < N0.getNumOperands())
11308 Ops.push_back(N0.getOperand(FirstElt));
11310 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11312 } else if (AllUndef) {
11313 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11314 } else { // Mixed with general masks and undefs, can't do optimization.
11319 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11322 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11323 EVT VT = N->getValueType(0);
11324 unsigned NumElts = VT.getVectorNumElements();
11326 SDValue N0 = N->getOperand(0);
11327 SDValue N1 = N->getOperand(1);
11329 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11331 // Canonicalize shuffle undef, undef -> undef
11332 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11333 return DAG.getUNDEF(VT);
11335 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11337 // Canonicalize shuffle v, v -> v, undef
11339 SmallVector<int, 8> NewMask;
11340 for (unsigned i = 0; i != NumElts; ++i) {
11341 int Idx = SVN->getMaskElt(i);
11342 if (Idx >= (int)NumElts) Idx -= NumElts;
11343 NewMask.push_back(Idx);
11345 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11349 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11350 if (N0.getOpcode() == ISD::UNDEF) {
11351 SmallVector<int, 8> NewMask;
11352 for (unsigned i = 0; i != NumElts; ++i) {
11353 int Idx = SVN->getMaskElt(i);
11355 if (Idx >= (int)NumElts)
11358 Idx = -1; // remove reference to lhs
11360 NewMask.push_back(Idx);
11362 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11366 // Remove references to rhs if it is undef
11367 if (N1.getOpcode() == ISD::UNDEF) {
11368 bool Changed = false;
11369 SmallVector<int, 8> NewMask;
11370 for (unsigned i = 0; i != NumElts; ++i) {
11371 int Idx = SVN->getMaskElt(i);
11372 if (Idx >= (int)NumElts) {
11376 NewMask.push_back(Idx);
11379 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11382 // If it is a splat, check if the argument vector is another splat or a
11383 // build_vector with all scalar elements the same.
11384 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11385 SDNode *V = N0.getNode();
11387 // If this is a bit convert that changes the element type of the vector but
11388 // not the number of vector elements, look through it. Be careful not to
11389 // look though conversions that change things like v4f32 to v2f64.
11390 if (V->getOpcode() == ISD::BITCAST) {
11391 SDValue ConvInput = V->getOperand(0);
11392 if (ConvInput.getValueType().isVector() &&
11393 ConvInput.getValueType().getVectorNumElements() == NumElts)
11394 V = ConvInput.getNode();
11397 if (V->getOpcode() == ISD::BUILD_VECTOR) {
11398 assert(V->getNumOperands() == NumElts &&
11399 "BUILD_VECTOR has wrong number of operands");
11401 bool AllSame = true;
11402 for (unsigned i = 0; i != NumElts; ++i) {
11403 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11404 Base = V->getOperand(i);
11408 // Splat of <u, u, u, u>, return <u, u, u, u>
11409 if (!Base.getNode())
11411 for (unsigned i = 0; i != NumElts; ++i) {
11412 if (V->getOperand(i) != Base) {
11417 // Splat of <x, x, x, x>, return <x, x, x, x>
11423 // There are various patterns used to build up a vector from smaller vectors,
11424 // subvectors, or elements. Scan chains of these and replace unused insertions
11425 // or components with undef.
11426 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11429 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11430 Level < AfterLegalizeVectorOps &&
11431 (N1.getOpcode() == ISD::UNDEF ||
11432 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11433 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11434 SDValue V = partitionShuffleOfConcats(N, DAG);
11440 // Canonicalize shuffles according to rules:
11441 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11442 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11443 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11444 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11445 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11446 TLI.isTypeLegal(VT)) {
11447 // The incoming shuffle must be of the same type as the result of the
11448 // current shuffle.
11449 assert(N1->getOperand(0).getValueType() == VT &&
11450 "Shuffle types don't match");
11452 SDValue SV0 = N1->getOperand(0);
11453 SDValue SV1 = N1->getOperand(1);
11454 bool HasSameOp0 = N0 == SV0;
11455 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11456 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11457 // Commute the operands of this shuffle so that next rule
11459 return DAG.getCommutedVectorShuffle(*SVN);
11462 // Try to fold according to rules:
11463 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11464 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11465 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11466 // Don't try to fold shuffles with illegal type.
11467 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11468 TLI.isTypeLegal(VT)) {
11469 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11471 // The incoming shuffle must be of the same type as the result of the
11472 // current shuffle.
11473 assert(OtherSV->getOperand(0).getValueType() == VT &&
11474 "Shuffle types don't match");
11477 SmallVector<int, 4> Mask;
11478 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11479 // operand, and SV1 as the second operand.
11480 for (unsigned i = 0; i != NumElts; ++i) {
11481 int Idx = SVN->getMaskElt(i);
11483 // Propagate Undef.
11484 Mask.push_back(Idx);
11488 SDValue CurrentVec;
11489 if (Idx < (int)NumElts) {
11490 // This shuffle index refers to the inner shuffle N0. Lookup the inner
11491 // shuffle mask to identify which vector is actually referenced.
11492 Idx = OtherSV->getMaskElt(Idx);
11494 // Propagate Undef.
11495 Mask.push_back(Idx);
11499 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11500 : OtherSV->getOperand(1);
11502 // This shuffle index references an element within N1.
11506 // Simple case where 'CurrentVec' is UNDEF.
11507 if (CurrentVec.getOpcode() == ISD::UNDEF) {
11508 Mask.push_back(-1);
11512 // Canonicalize the shuffle index. We don't know yet if CurrentVec
11513 // will be the first or second operand of the combined shuffle.
11514 Idx = Idx % NumElts;
11515 if (!SV0.getNode() || SV0 == CurrentVec) {
11516 // Ok. CurrentVec is the left hand side.
11517 // Update the mask accordingly.
11519 Mask.push_back(Idx);
11523 // Bail out if we cannot convert the shuffle pair into a single shuffle.
11524 if (SV1.getNode() && SV1 != CurrentVec)
11527 // Ok. CurrentVec is the right hand side.
11528 // Update the mask accordingly.
11530 Mask.push_back(Idx + NumElts);
11533 // Check if all indices in Mask are Undef. In case, propagate Undef.
11534 bool isUndefMask = true;
11535 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11536 isUndefMask &= Mask[i] < 0;
11539 return DAG.getUNDEF(VT);
11541 if (!SV0.getNode())
11542 SV0 = DAG.getUNDEF(VT);
11543 if (!SV1.getNode())
11544 SV1 = DAG.getUNDEF(VT);
11546 // Avoid introducing shuffles with illegal mask.
11547 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11548 // Compute the commuted shuffle mask and test again.
11549 for (unsigned i = 0; i != NumElts; ++i) {
11553 else if (idx < (int)NumElts)
11554 Mask[i] = idx + NumElts;
11556 Mask[i] = idx - NumElts;
11559 if (!TLI.isShuffleMaskLegal(Mask, VT))
11562 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11563 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11564 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11565 std::swap(SV0, SV1);
11568 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11569 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11570 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11571 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11577 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11578 SDValue N0 = N->getOperand(0);
11579 SDValue N2 = N->getOperand(2);
11581 // If the input vector is a concatenation, and the insert replaces
11582 // one of the halves, we can optimize into a single concat_vectors.
11583 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11584 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11585 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11586 EVT VT = N->getValueType(0);
11588 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11589 // (concat_vectors Z, Y)
11591 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11592 N->getOperand(1), N0.getOperand(1));
11594 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11595 // (concat_vectors X, Z)
11596 if (InsIdx == VT.getVectorNumElements()/2)
11597 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11598 N0.getOperand(0), N->getOperand(1));
11604 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11605 /// with the destination vector and a zero vector.
11606 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11607 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11608 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11609 EVT VT = N->getValueType(0);
11611 SDValue LHS = N->getOperand(0);
11612 SDValue RHS = N->getOperand(1);
11613 if (N->getOpcode() == ISD::AND) {
11614 if (RHS.getOpcode() == ISD::BITCAST)
11615 RHS = RHS.getOperand(0);
11616 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11617 SmallVector<int, 8> Indices;
11618 unsigned NumElts = RHS.getNumOperands();
11619 for (unsigned i = 0; i != NumElts; ++i) {
11620 SDValue Elt = RHS.getOperand(i);
11621 if (!isa<ConstantSDNode>(Elt))
11624 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11625 Indices.push_back(i);
11626 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11627 Indices.push_back(NumElts+i);
11632 // Let's see if the target supports this vector_shuffle.
11633 EVT RVT = RHS.getValueType();
11634 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11637 // Return the new VECTOR_SHUFFLE node.
11638 EVT EltVT = RVT.getVectorElementType();
11639 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11640 DAG.getConstant(0, EltVT));
11641 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11642 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11643 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11644 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11651 /// Visit a binary vector operation, like ADD.
11652 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11653 assert(N->getValueType(0).isVector() &&
11654 "SimplifyVBinOp only works on vectors!");
11656 SDValue LHS = N->getOperand(0);
11657 SDValue RHS = N->getOperand(1);
11658 SDValue Shuffle = XformToShuffleWithZero(N);
11659 if (Shuffle.getNode()) return Shuffle;
11661 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11663 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11664 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11665 // Check if both vectors are constants. If not bail out.
11666 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11667 cast<BuildVectorSDNode>(RHS)->isConstant()))
11670 SmallVector<SDValue, 8> Ops;
11671 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11672 SDValue LHSOp = LHS.getOperand(i);
11673 SDValue RHSOp = RHS.getOperand(i);
11675 // Can't fold divide by zero.
11676 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11677 N->getOpcode() == ISD::FDIV) {
11678 if ((RHSOp.getOpcode() == ISD::Constant &&
11679 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11680 (RHSOp.getOpcode() == ISD::ConstantFP &&
11681 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11685 EVT VT = LHSOp.getValueType();
11686 EVT RVT = RHSOp.getValueType();
11688 // Integer BUILD_VECTOR operands may have types larger than the element
11689 // size (e.g., when the element type is not legal). Prior to type
11690 // legalization, the types may not match between the two BUILD_VECTORS.
11691 // Truncate one of the operands to make them match.
11692 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11693 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11695 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11699 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11701 if (FoldOp.getOpcode() != ISD::UNDEF &&
11702 FoldOp.getOpcode() != ISD::Constant &&
11703 FoldOp.getOpcode() != ISD::ConstantFP)
11705 Ops.push_back(FoldOp);
11706 AddToWorklist(FoldOp.getNode());
11709 if (Ops.size() == LHS.getNumOperands())
11710 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11713 // Type legalization might introduce new shuffles in the DAG.
11714 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11715 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11716 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11717 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11718 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11719 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11720 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11721 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11723 if (SVN0->getMask().equals(SVN1->getMask())) {
11724 EVT VT = N->getValueType(0);
11725 SDValue UndefVector = LHS.getOperand(1);
11726 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11727 LHS.getOperand(0), RHS.getOperand(0));
11728 AddUsersToWorklist(N);
11729 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11730 &SVN0->getMask()[0]);
11737 /// Visit a binary vector operation, like FABS/FNEG.
11738 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11739 assert(N->getValueType(0).isVector() &&
11740 "SimplifyVUnaryOp only works on vectors!");
11742 SDValue N0 = N->getOperand(0);
11744 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11747 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11748 SmallVector<SDValue, 8> Ops;
11749 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11750 SDValue Op = N0.getOperand(i);
11751 if (Op.getOpcode() != ISD::UNDEF &&
11752 Op.getOpcode() != ISD::ConstantFP)
11754 EVT EltVT = Op.getValueType();
11755 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11756 if (FoldOp.getOpcode() != ISD::UNDEF &&
11757 FoldOp.getOpcode() != ISD::ConstantFP)
11759 Ops.push_back(FoldOp);
11760 AddToWorklist(FoldOp.getNode());
11763 if (Ops.size() != N0.getNumOperands())
11766 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11769 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11770 SDValue N1, SDValue N2){
11771 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11773 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11774 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11776 // If we got a simplified select_cc node back from SimplifySelectCC, then
11777 // break it down into a new SETCC node, and a new SELECT node, and then return
11778 // the SELECT node, since we were called with a SELECT node.
11779 if (SCC.getNode()) {
11780 // Check to see if we got a select_cc back (to turn into setcc/select).
11781 // Otherwise, just return whatever node we got back, like fabs.
11782 if (SCC.getOpcode() == ISD::SELECT_CC) {
11783 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11785 SCC.getOperand(0), SCC.getOperand(1),
11786 SCC.getOperand(4));
11787 AddToWorklist(SETCC.getNode());
11788 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11789 SCC.getOperand(2), SCC.getOperand(3));
11797 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11798 /// being selected between, see if we can simplify the select. Callers of this
11799 /// should assume that TheSelect is deleted if this returns true. As such, they
11800 /// should return the appropriate thing (e.g. the node) back to the top-level of
11801 /// the DAG combiner loop to avoid it being looked at.
11802 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11805 // Cannot simplify select with vector condition
11806 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11808 // If this is a select from two identical things, try to pull the operation
11809 // through the select.
11810 if (LHS.getOpcode() != RHS.getOpcode() ||
11811 !LHS.hasOneUse() || !RHS.hasOneUse())
11814 // If this is a load and the token chain is identical, replace the select
11815 // of two loads with a load through a select of the address to load from.
11816 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11817 // constants have been dropped into the constant pool.
11818 if (LHS.getOpcode() == ISD::LOAD) {
11819 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11820 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11822 // Token chains must be identical.
11823 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11824 // Do not let this transformation reduce the number of volatile loads.
11825 LLD->isVolatile() || RLD->isVolatile() ||
11826 // If this is an EXTLOAD, the VT's must match.
11827 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11828 // If this is an EXTLOAD, the kind of extension must match.
11829 (LLD->getExtensionType() != RLD->getExtensionType() &&
11830 // The only exception is if one of the extensions is anyext.
11831 LLD->getExtensionType() != ISD::EXTLOAD &&
11832 RLD->getExtensionType() != ISD::EXTLOAD) ||
11833 // FIXME: this discards src value information. This is
11834 // over-conservative. It would be beneficial to be able to remember
11835 // both potential memory locations. Since we are discarding
11836 // src value info, don't do the transformation if the memory
11837 // locations are not in the default address space.
11838 LLD->getPointerInfo().getAddrSpace() != 0 ||
11839 RLD->getPointerInfo().getAddrSpace() != 0 ||
11840 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11841 LLD->getBasePtr().getValueType()))
11844 // Check that the select condition doesn't reach either load. If so,
11845 // folding this will induce a cycle into the DAG. If not, this is safe to
11846 // xform, so create a select of the addresses.
11848 if (TheSelect->getOpcode() == ISD::SELECT) {
11849 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11850 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11851 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11853 // The loads must not depend on one another.
11854 if (LLD->isPredecessorOf(RLD) ||
11855 RLD->isPredecessorOf(LLD))
11857 Addr = DAG.getSelect(SDLoc(TheSelect),
11858 LLD->getBasePtr().getValueType(),
11859 TheSelect->getOperand(0), LLD->getBasePtr(),
11860 RLD->getBasePtr());
11861 } else { // Otherwise SELECT_CC
11862 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11863 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11865 if ((LLD->hasAnyUseOfValue(1) &&
11866 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11867 (RLD->hasAnyUseOfValue(1) &&
11868 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11871 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11872 LLD->getBasePtr().getValueType(),
11873 TheSelect->getOperand(0),
11874 TheSelect->getOperand(1),
11875 LLD->getBasePtr(), RLD->getBasePtr(),
11876 TheSelect->getOperand(4));
11880 // It is safe to replace the two loads if they have different alignments,
11881 // but the new load must be the minimum (most restrictive) alignment of the
11883 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11884 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11885 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11886 Load = DAG.getLoad(TheSelect->getValueType(0),
11888 // FIXME: Discards pointer and AA info.
11889 LLD->getChain(), Addr, MachinePointerInfo(),
11890 LLD->isVolatile(), LLD->isNonTemporal(),
11891 isInvariant, Alignment);
11893 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11894 RLD->getExtensionType() : LLD->getExtensionType(),
11896 TheSelect->getValueType(0),
11897 // FIXME: Discards pointer and AA info.
11898 LLD->getChain(), Addr, MachinePointerInfo(),
11899 LLD->getMemoryVT(), LLD->isVolatile(),
11900 LLD->isNonTemporal(), isInvariant, Alignment);
11903 // Users of the select now use the result of the load.
11904 CombineTo(TheSelect, Load);
11906 // Users of the old loads now use the new load's chain. We know the
11907 // old-load value is dead now.
11908 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11909 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11916 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11917 /// where 'cond' is the comparison specified by CC.
11918 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11919 SDValue N2, SDValue N3,
11920 ISD::CondCode CC, bool NotExtCompare) {
11921 // (x ? y : y) -> y.
11922 if (N2 == N3) return N2;
11924 EVT VT = N2.getValueType();
11925 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11926 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11927 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11929 // Determine if the condition we're dealing with is constant
11930 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11931 N0, N1, CC, DL, false);
11932 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11933 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11935 // fold select_cc true, x, y -> x
11936 if (SCCC && !SCCC->isNullValue())
11938 // fold select_cc false, x, y -> y
11939 if (SCCC && SCCC->isNullValue())
11942 // Check to see if we can simplify the select into an fabs node
11943 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11944 // Allow either -0.0 or 0.0
11945 if (CFP->getValueAPF().isZero()) {
11946 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11947 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11948 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11949 N2 == N3.getOperand(0))
11950 return DAG.getNode(ISD::FABS, DL, VT, N0);
11952 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11953 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11954 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11955 N2.getOperand(0) == N3)
11956 return DAG.getNode(ISD::FABS, DL, VT, N3);
11960 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11961 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11962 // in it. This is a win when the constant is not otherwise available because
11963 // it replaces two constant pool loads with one. We only do this if the FP
11964 // type is known to be legal, because if it isn't, then we are before legalize
11965 // types an we want the other legalization to happen first (e.g. to avoid
11966 // messing with soft float) and if the ConstantFP is not legal, because if
11967 // it is legal, we may not need to store the FP constant in a constant pool.
11968 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11969 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11970 if (TLI.isTypeLegal(N2.getValueType()) &&
11971 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11972 TargetLowering::Legal &&
11973 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11974 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11975 // If both constants have multiple uses, then we won't need to do an
11976 // extra load, they are likely around in registers for other users.
11977 (TV->hasOneUse() || FV->hasOneUse())) {
11978 Constant *Elts[] = {
11979 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11980 const_cast<ConstantFP*>(TV->getConstantFPValue())
11982 Type *FPTy = Elts[0]->getType();
11983 const DataLayout &TD = *TLI.getDataLayout();
11985 // Create a ConstantArray of the two constants.
11986 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11987 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11988 TD.getPrefTypeAlignment(FPTy));
11989 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11991 // Get the offsets to the 0 and 1 element of the array so that we can
11992 // select between them.
11993 SDValue Zero = DAG.getIntPtrConstant(0);
11994 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11995 SDValue One = DAG.getIntPtrConstant(EltSize);
11997 SDValue Cond = DAG.getSetCC(DL,
11998 getSetCCResultType(N0.getValueType()),
12000 AddToWorklist(Cond.getNode());
12001 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12003 AddToWorklist(CstOffset.getNode());
12004 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12006 AddToWorklist(CPIdx.getNode());
12007 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12008 MachinePointerInfo::getConstantPool(), false,
12009 false, false, Alignment);
12014 // Check to see if we can perform the "gzip trick", transforming
12015 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12016 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12017 (N1C->isNullValue() || // (a < 0) ? b : 0
12018 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
12019 EVT XType = N0.getValueType();
12020 EVT AType = N2.getValueType();
12021 if (XType.bitsGE(AType)) {
12022 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12023 // single-bit constant.
12024 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12025 unsigned ShCtV = N2C->getAPIntValue().logBase2();
12026 ShCtV = XType.getSizeInBits()-ShCtV-1;
12027 SDValue ShCt = DAG.getConstant(ShCtV,
12028 getShiftAmountTy(N0.getValueType()));
12029 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12031 AddToWorklist(Shift.getNode());
12033 if (XType.bitsGT(AType)) {
12034 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12035 AddToWorklist(Shift.getNode());
12038 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12041 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12043 DAG.getConstant(XType.getSizeInBits()-1,
12044 getShiftAmountTy(N0.getValueType())));
12045 AddToWorklist(Shift.getNode());
12047 if (XType.bitsGT(AType)) {
12048 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12049 AddToWorklist(Shift.getNode());
12052 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12056 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12057 // where y is has a single bit set.
12058 // A plaintext description would be, we can turn the SELECT_CC into an AND
12059 // when the condition can be materialized as an all-ones register. Any
12060 // single bit-test can be materialized as an all-ones register with
12061 // shift-left and shift-right-arith.
12062 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12063 N0->getValueType(0) == VT &&
12064 N1C && N1C->isNullValue() &&
12065 N2C && N2C->isNullValue()) {
12066 SDValue AndLHS = N0->getOperand(0);
12067 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12068 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12069 // Shift the tested bit over the sign bit.
12070 APInt AndMask = ConstAndRHS->getAPIntValue();
12072 DAG.getConstant(AndMask.countLeadingZeros(),
12073 getShiftAmountTy(AndLHS.getValueType()));
12074 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12076 // Now arithmetic right shift it all the way over, so the result is either
12077 // all-ones, or zero.
12079 DAG.getConstant(AndMask.getBitWidth()-1,
12080 getShiftAmountTy(Shl.getValueType()));
12081 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12083 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12087 // fold select C, 16, 0 -> shl C, 4
12088 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12089 TLI.getBooleanContents(N0.getValueType()) ==
12090 TargetLowering::ZeroOrOneBooleanContent) {
12092 // If the caller doesn't want us to simplify this into a zext of a compare,
12094 if (NotExtCompare && N2C->getAPIntValue() == 1)
12097 // Get a SetCC of the condition
12098 // NOTE: Don't create a SETCC if it's not legal on this target.
12099 if (!LegalOperations ||
12100 TLI.isOperationLegal(ISD::SETCC,
12101 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12103 // cast from setcc result type to select result type
12105 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12107 if (N2.getValueType().bitsLT(SCC.getValueType()))
12108 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12109 N2.getValueType());
12111 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12112 N2.getValueType(), SCC);
12114 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12115 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12116 N2.getValueType(), SCC);
12119 AddToWorklist(SCC.getNode());
12120 AddToWorklist(Temp.getNode());
12122 if (N2C->getAPIntValue() == 1)
12125 // shl setcc result by log2 n2c
12126 return DAG.getNode(
12127 ISD::SHL, DL, N2.getValueType(), Temp,
12128 DAG.getConstant(N2C->getAPIntValue().logBase2(),
12129 getShiftAmountTy(Temp.getValueType())));
12133 // Check to see if this is the equivalent of setcc
12134 // FIXME: Turn all of these into setcc if setcc if setcc is legal
12135 // otherwise, go ahead with the folds.
12136 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12137 EVT XType = N0.getValueType();
12138 if (!LegalOperations ||
12139 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12140 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12141 if (Res.getValueType() != VT)
12142 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12146 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12147 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12148 (!LegalOperations ||
12149 TLI.isOperationLegal(ISD::CTLZ, XType))) {
12150 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12151 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12152 DAG.getConstant(Log2_32(XType.getSizeInBits()),
12153 getShiftAmountTy(Ctlz.getValueType())));
12155 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12156 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12157 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12158 XType, DAG.getConstant(0, XType), N0);
12159 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12160 return DAG.getNode(ISD::SRL, DL, XType,
12161 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12162 DAG.getConstant(XType.getSizeInBits()-1,
12163 getShiftAmountTy(XType)));
12165 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12166 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12167 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12168 DAG.getConstant(XType.getSizeInBits()-1,
12169 getShiftAmountTy(N0.getValueType())));
12170 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12174 // Check to see if this is an integer abs.
12175 // select_cc setg[te] X, 0, X, -X ->
12176 // select_cc setgt X, -1, X, -X ->
12177 // select_cc setl[te] X, 0, -X, X ->
12178 // select_cc setlt X, 1, -X, X ->
12179 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12181 ConstantSDNode *SubC = nullptr;
12182 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12183 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12184 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12185 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12186 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12187 (N1C->isOne() && CC == ISD::SETLT)) &&
12188 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12189 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12191 EVT XType = N0.getValueType();
12192 if (SubC && SubC->isNullValue() && XType.isInteger()) {
12193 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12195 DAG.getConstant(XType.getSizeInBits()-1,
12196 getShiftAmountTy(N0.getValueType())));
12197 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12199 AddToWorklist(Shift.getNode());
12200 AddToWorklist(Add.getNode());
12201 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12208 /// This is a stub for TargetLowering::SimplifySetCC.
12209 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12210 SDValue N1, ISD::CondCode Cond,
12211 SDLoc DL, bool foldBooleans) {
12212 TargetLowering::DAGCombinerInfo
12213 DagCombineInfo(DAG, Level, false, this);
12214 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12217 /// Given an ISD::SDIV node expressing a divide by constant, return
12218 /// a DAG expression to select that will generate the same value by multiplying
12219 /// by a magic number.
12220 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12221 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12222 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12226 // Avoid division by zero.
12227 if (!C->getAPIntValue())
12230 std::vector<SDNode*> Built;
12232 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12234 for (SDNode *N : Built)
12239 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12240 /// DAG expression that will generate the same value by right shifting.
12241 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12242 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12246 // Avoid division by zero.
12247 if (!C->getAPIntValue())
12250 std::vector<SDNode *> Built;
12251 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12253 for (SDNode *N : Built)
12258 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12259 /// expression that will generate the same value by multiplying by a magic
12261 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12262 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12263 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12267 // Avoid division by zero.
12268 if (!C->getAPIntValue())
12271 std::vector<SDNode*> Built;
12273 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12275 for (SDNode *N : Built)
12280 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12281 if (Level >= AfterLegalizeDAG)
12284 // Expose the DAG combiner to the target combiner implementations.
12285 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12287 unsigned Iterations = 0;
12288 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12290 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12291 // For the reciprocal, we need to find the zero of the function:
12292 // F(X) = A X - 1 [which has a zero at X = 1/A]
12294 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12295 // does not require additional intermediate precision]
12296 EVT VT = Op.getValueType();
12298 SDValue FPOne = DAG.getConstantFP(1.0, VT);
12300 AddToWorklist(Est.getNode());
12302 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12303 for (unsigned i = 0; i < Iterations; ++i) {
12304 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12305 AddToWorklist(NewEst.getNode());
12307 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12308 AddToWorklist(NewEst.getNode());
12310 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12311 AddToWorklist(NewEst.getNode());
12313 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12314 AddToWorklist(Est.getNode());
12323 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12324 /// For the reciprocal sqrt, we need to find the zero of the function:
12325 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12327 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12328 /// As a result, we precompute A/2 prior to the iteration loop.
12329 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12330 unsigned Iterations) {
12331 EVT VT = Arg.getValueType();
12333 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12335 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12336 // this entire sequence requires only one FP constant.
12337 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12338 AddToWorklist(HalfArg.getNode());
12340 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12341 AddToWorklist(HalfArg.getNode());
12343 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12344 for (unsigned i = 0; i < Iterations; ++i) {
12345 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12346 AddToWorklist(NewEst.getNode());
12348 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12349 AddToWorklist(NewEst.getNode());
12351 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12352 AddToWorklist(NewEst.getNode());
12354 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12355 AddToWorklist(Est.getNode());
12360 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12361 /// For the reciprocal sqrt, we need to find the zero of the function:
12362 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12364 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12365 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12366 unsigned Iterations) {
12367 EVT VT = Arg.getValueType();
12369 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12370 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12372 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12373 for (unsigned i = 0; i < Iterations; ++i) {
12374 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12375 AddToWorklist(HalfEst.getNode());
12377 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12378 AddToWorklist(Est.getNode());
12380 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12381 AddToWorklist(Est.getNode());
12383 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12384 AddToWorklist(Est.getNode());
12386 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12387 AddToWorklist(Est.getNode());
12392 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12393 if (Level >= AfterLegalizeDAG)
12396 // Expose the DAG combiner to the target combiner implementations.
12397 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12398 unsigned Iterations = 0;
12399 bool UseOneConstNR = false;
12400 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12401 AddToWorklist(Est.getNode());
12403 Est = UseOneConstNR ?
12404 BuildRsqrtNROneConst(Op, Est, Iterations) :
12405 BuildRsqrtNRTwoConst(Op, Est, Iterations);
12413 /// Return true if base is a frame index, which is known not to alias with
12414 /// anything but itself. Provides base object and offset as results.
12415 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12416 const GlobalValue *&GV, const void *&CV) {
12417 // Assume it is a primitive operation.
12418 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12420 // If it's an adding a simple constant then integrate the offset.
12421 if (Base.getOpcode() == ISD::ADD) {
12422 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12423 Base = Base.getOperand(0);
12424 Offset += C->getZExtValue();
12428 // Return the underlying GlobalValue, and update the Offset. Return false
12429 // for GlobalAddressSDNode since the same GlobalAddress may be represented
12430 // by multiple nodes with different offsets.
12431 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12432 GV = G->getGlobal();
12433 Offset += G->getOffset();
12437 // Return the underlying Constant value, and update the Offset. Return false
12438 // for ConstantSDNodes since the same constant pool entry may be represented
12439 // by multiple nodes with different offsets.
12440 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12441 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12442 : (const void *)C->getConstVal();
12443 Offset += C->getOffset();
12446 // If it's any of the following then it can't alias with anything but itself.
12447 return isa<FrameIndexSDNode>(Base);
12450 /// Return true if there is any possibility that the two addresses overlap.
12451 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12452 // If they are the same then they must be aliases.
12453 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12455 // If they are both volatile then they cannot be reordered.
12456 if (Op0->isVolatile() && Op1->isVolatile()) return true;
12458 // Gather base node and offset information.
12459 SDValue Base1, Base2;
12460 int64_t Offset1, Offset2;
12461 const GlobalValue *GV1, *GV2;
12462 const void *CV1, *CV2;
12463 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12464 Base1, Offset1, GV1, CV1);
12465 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12466 Base2, Offset2, GV2, CV2);
12468 // If they have a same base address then check to see if they overlap.
12469 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12470 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12471 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12473 // It is possible for different frame indices to alias each other, mostly
12474 // when tail call optimization reuses return address slots for arguments.
12475 // To catch this case, look up the actual index of frame indices to compute
12476 // the real alias relationship.
12477 if (isFrameIndex1 && isFrameIndex2) {
12478 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12479 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12480 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12481 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12482 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12485 // Otherwise, if we know what the bases are, and they aren't identical, then
12486 // we know they cannot alias.
12487 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12490 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12491 // compared to the size and offset of the access, we may be able to prove they
12492 // do not alias. This check is conservative for now to catch cases created by
12493 // splitting vector types.
12494 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12495 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12496 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12497 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12498 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12499 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12500 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12502 // There is no overlap between these relatively aligned accesses of similar
12503 // size, return no alias.
12504 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12505 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12509 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12511 : DAG.getSubtarget().useAA();
12513 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12514 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12518 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12519 // Use alias analysis information.
12520 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12521 Op1->getSrcValueOffset());
12522 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12523 Op0->getSrcValueOffset() - MinOffset;
12524 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12525 Op1->getSrcValueOffset() - MinOffset;
12526 AliasAnalysis::AliasResult AAResult =
12527 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12529 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12530 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12532 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12533 if (AAResult == AliasAnalysis::NoAlias)
12537 // Otherwise we have to assume they alias.
12541 /// Walk up chain skipping non-aliasing memory nodes,
12542 /// looking for aliasing nodes and adding them to the Aliases vector.
12543 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12544 SmallVectorImpl<SDValue> &Aliases) {
12545 SmallVector<SDValue, 8> Chains; // List of chains to visit.
12546 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
12548 // Get alias information for node.
12549 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12552 Chains.push_back(OriginalChain);
12553 unsigned Depth = 0;
12555 // Look at each chain and determine if it is an alias. If so, add it to the
12556 // aliases list. If not, then continue up the chain looking for the next
12558 while (!Chains.empty()) {
12559 SDValue Chain = Chains.back();
12562 // For TokenFactor nodes, look at each operand and only continue up the
12563 // chain until we find two aliases. If we've seen two aliases, assume we'll
12564 // find more and revert to original chain since the xform is unlikely to be
12567 // FIXME: The depth check could be made to return the last non-aliasing
12568 // chain we found before we hit a tokenfactor rather than the original
12570 if (Depth > 6 || Aliases.size() == 2) {
12572 Aliases.push_back(OriginalChain);
12576 // Don't bother if we've been before.
12577 if (!Visited.insert(Chain.getNode()).second)
12580 switch (Chain.getOpcode()) {
12581 case ISD::EntryToken:
12582 // Entry token is ideal chain operand, but handled in FindBetterChain.
12587 // Get alias information for Chain.
12588 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12589 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12591 // If chain is alias then stop here.
12592 if (!(IsLoad && IsOpLoad) &&
12593 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12594 Aliases.push_back(Chain);
12596 // Look further up the chain.
12597 Chains.push_back(Chain.getOperand(0));
12603 case ISD::TokenFactor:
12604 // We have to check each of the operands of the token factor for "small"
12605 // token factors, so we queue them up. Adding the operands to the queue
12606 // (stack) in reverse order maintains the original order and increases the
12607 // likelihood that getNode will find a matching token factor (CSE.)
12608 if (Chain.getNumOperands() > 16) {
12609 Aliases.push_back(Chain);
12612 for (unsigned n = Chain.getNumOperands(); n;)
12613 Chains.push_back(Chain.getOperand(--n));
12618 // For all other instructions we will just have to take what we can get.
12619 Aliases.push_back(Chain);
12624 // We need to be careful here to also search for aliases through the
12625 // value operand of a store, etc. Consider the following situation:
12627 // L1 = load Token1, %52
12628 // S1 = store Token1, L1, %51
12629 // L2 = load Token1, %52+8
12630 // S2 = store Token1, L2, %51+8
12631 // Token2 = Token(S1, S2)
12632 // L3 = load Token2, %53
12633 // S3 = store Token2, L3, %52
12634 // L4 = load Token2, %53+8
12635 // S4 = store Token2, L4, %52+8
12636 // If we search for aliases of S3 (which loads address %52), and we look
12637 // only through the chain, then we'll miss the trivial dependence on L1
12638 // (which also loads from %52). We then might change all loads and
12639 // stores to use Token1 as their chain operand, which could result in
12640 // copying %53 into %52 before copying %52 into %51 (which should
12643 // The problem is, however, that searching for such data dependencies
12644 // can become expensive, and the cost is not directly related to the
12645 // chain depth. Instead, we'll rule out such configurations here by
12646 // insisting that we've visited all chain users (except for users
12647 // of the original chain, which is not necessary). When doing this,
12648 // we need to look through nodes we don't care about (otherwise, things
12649 // like register copies will interfere with trivial cases).
12651 SmallVector<const SDNode *, 16> Worklist;
12652 for (const SDNode *N : Visited)
12653 if (N != OriginalChain.getNode())
12654 Worklist.push_back(N);
12656 while (!Worklist.empty()) {
12657 const SDNode *M = Worklist.pop_back_val();
12659 // We have already visited M, and want to make sure we've visited any uses
12660 // of M that we care about. For uses that we've not visisted, and don't
12661 // care about, queue them to the worklist.
12663 for (SDNode::use_iterator UI = M->use_begin(),
12664 UIE = M->use_end(); UI != UIE; ++UI)
12665 if (UI.getUse().getValueType() == MVT::Other &&
12666 Visited.insert(*UI).second) {
12667 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12668 // We've not visited this use, and we care about it (it could have an
12669 // ordering dependency with the original node).
12671 Aliases.push_back(OriginalChain);
12675 // We've not visited this use, but we don't care about it. Mark it as
12676 // visited and enqueue it to the worklist.
12677 Worklist.push_back(*UI);
12682 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12683 /// (aliasing node.)
12684 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12685 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
12687 // Accumulate all the aliases to this node.
12688 GatherAllAliases(N, OldChain, Aliases);
12690 // If no operands then chain to entry token.
12691 if (Aliases.size() == 0)
12692 return DAG.getEntryNode();
12694 // If a single operand then chain to it. We don't need to revisit it.
12695 if (Aliases.size() == 1)
12698 // Construct a custom tailored token factor.
12699 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12702 /// This is the entry point for the file.
12703 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12704 CodeGenOpt::Level OptLevel) {
12705 /// This is the main entry point to this class.
12706 DAGCombiner(*this, AA, OptLevel).Run(Level);