1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue 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 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
742 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
745 if (N0.hasOneUse()) {
746 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
748 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
749 if (!OpNode.getNode())
751 AddToWorklist(OpNode.getNode());
752 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
757 if (N1.getOpcode() == Opc) {
758 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
759 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
760 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
761 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
762 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
765 if (N1.hasOneUse()) {
766 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
768 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
769 if (!OpNode.getNode())
771 AddToWorklist(OpNode.getNode());
772 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
780 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
782 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
784 DEBUG(dbgs() << "\nReplacing.1 ";
786 dbgs() << "\nWith: ";
787 To[0].getNode()->dump(&DAG);
788 dbgs() << " and " << NumTo-1 << " other values\n");
789 for (unsigned i = 0, e = NumTo; i != e; ++i)
790 assert((!To[i].getNode() ||
791 N->getValueType(i) == To[i].getValueType()) &&
792 "Cannot combine value to value of different type!");
794 WorklistRemover DeadNodes(*this);
795 DAG.ReplaceAllUsesWith(N, To);
797 // Push the new nodes and any users onto the worklist
798 for (unsigned i = 0, e = NumTo; i != e; ++i) {
799 if (To[i].getNode()) {
800 AddToWorklist(To[i].getNode());
801 AddUsersToWorklist(To[i].getNode());
806 // Finally, if the node is now dead, remove it from the graph. The node
807 // may not be dead if the replacement process recursively simplified to
808 // something else needing this node.
810 deleteAndRecombine(N);
811 return SDValue(N, 0);
815 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
816 // Replace all uses. If any nodes become isomorphic to other nodes and
817 // are deleted, make sure to remove them from our worklist.
818 WorklistRemover DeadNodes(*this);
819 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
821 // Push the new node and any (possibly new) users onto the worklist.
822 AddToWorklist(TLO.New.getNode());
823 AddUsersToWorklist(TLO.New.getNode());
825 // Finally, if the node is now dead, remove it from the graph. The node
826 // may not be dead if the replacement process recursively simplified to
827 // something else needing this node.
828 if (TLO.Old.getNode()->use_empty())
829 deleteAndRecombine(TLO.Old.getNode());
832 /// Check the specified integer node value to see if it can be simplified or if
833 /// things it uses can be simplified by bit propagation. If so, return true.
834 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
835 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
836 APInt KnownZero, KnownOne;
837 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
841 AddToWorklist(Op.getNode());
843 // Replace the old value with the new one.
845 DEBUG(dbgs() << "\nReplacing.2 ";
846 TLO.Old.getNode()->dump(&DAG);
847 dbgs() << "\nWith: ";
848 TLO.New.getNode()->dump(&DAG);
851 CommitTargetLoweringOpt(TLO);
855 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
857 EVT VT = Load->getValueType(0);
858 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
860 DEBUG(dbgs() << "\nReplacing.9 ";
862 dbgs() << "\nWith: ";
863 Trunc.getNode()->dump(&DAG);
865 WorklistRemover DeadNodes(*this);
866 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
867 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
868 deleteAndRecombine(Load);
869 AddToWorklist(Trunc.getNode());
872 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
875 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
876 EVT MemVT = LD->getMemoryVT();
877 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
878 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
880 : LD->getExtensionType();
882 return DAG.getExtLoad(ExtType, dl, PVT,
883 LD->getChain(), LD->getBasePtr(),
884 MemVT, LD->getMemOperand());
887 unsigned Opc = Op.getOpcode();
890 case ISD::AssertSext:
891 return DAG.getNode(ISD::AssertSext, dl, PVT,
892 SExtPromoteOperand(Op.getOperand(0), PVT),
894 case ISD::AssertZext:
895 return DAG.getNode(ISD::AssertZext, dl, PVT,
896 ZExtPromoteOperand(Op.getOperand(0), PVT),
898 case ISD::Constant: {
900 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
901 return DAG.getNode(ExtOpc, dl, PVT, Op);
905 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
907 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
910 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
911 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
913 EVT OldVT = Op.getValueType();
915 bool Replace = false;
916 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
917 if (!NewOp.getNode())
919 AddToWorklist(NewOp.getNode());
922 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
923 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
924 DAG.getValueType(OldVT));
927 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
928 EVT OldVT = Op.getValueType();
930 bool Replace = false;
931 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
932 if (!NewOp.getNode())
934 AddToWorklist(NewOp.getNode());
937 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
938 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
941 /// Promote the specified integer binary operation if the target indicates it is
942 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
943 /// i32 since i16 instructions are longer.
944 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
945 if (!LegalOperations)
948 EVT VT = Op.getValueType();
949 if (VT.isVector() || !VT.isInteger())
952 // If operation type is 'undesirable', e.g. i16 on x86, consider
954 unsigned Opc = Op.getOpcode();
955 if (TLI.isTypeDesirableForOp(Opc, VT))
959 // Consult target whether it is a good idea to promote this operation and
960 // what's the right type to promote it to.
961 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
962 assert(PVT != VT && "Don't know what type to promote to!");
964 bool Replace0 = false;
965 SDValue N0 = Op.getOperand(0);
966 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
970 bool Replace1 = false;
971 SDValue N1 = Op.getOperand(1);
976 NN1 = PromoteOperand(N1, PVT, Replace1);
981 AddToWorklist(NN0.getNode());
983 AddToWorklist(NN1.getNode());
986 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
988 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
990 DEBUG(dbgs() << "\nPromoting ";
991 Op.getNode()->dump(&DAG));
993 return DAG.getNode(ISD::TRUNCATE, dl, VT,
994 DAG.getNode(Opc, dl, PVT, NN0, NN1));
999 /// Promote the specified integer shift operation if the target indicates it is
1000 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1001 /// i32 since i16 instructions are longer.
1002 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1003 if (!LegalOperations)
1006 EVT VT = Op.getValueType();
1007 if (VT.isVector() || !VT.isInteger())
1010 // If operation type is 'undesirable', e.g. i16 on x86, consider
1012 unsigned Opc = Op.getOpcode();
1013 if (TLI.isTypeDesirableForOp(Opc, VT))
1017 // Consult target whether it is a good idea to promote this operation and
1018 // what's the right type to promote it to.
1019 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1020 assert(PVT != VT && "Don't know what type to promote to!");
1022 bool Replace = false;
1023 SDValue N0 = Op.getOperand(0);
1024 if (Opc == ISD::SRA)
1025 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1026 else if (Opc == ISD::SRL)
1027 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1029 N0 = PromoteOperand(N0, PVT, Replace);
1033 AddToWorklist(N0.getNode());
1035 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1037 DEBUG(dbgs() << "\nPromoting ";
1038 Op.getNode()->dump(&DAG));
1040 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1041 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1046 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1047 if (!LegalOperations)
1050 EVT VT = Op.getValueType();
1051 if (VT.isVector() || !VT.isInteger())
1054 // If operation type is 'undesirable', e.g. i16 on x86, consider
1056 unsigned Opc = Op.getOpcode();
1057 if (TLI.isTypeDesirableForOp(Opc, VT))
1061 // Consult target whether it is a good idea to promote this operation and
1062 // what's the right type to promote it to.
1063 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1064 assert(PVT != VT && "Don't know what type to promote to!");
1065 // fold (aext (aext x)) -> (aext x)
1066 // fold (aext (zext x)) -> (zext x)
1067 // fold (aext (sext x)) -> (sext x)
1068 DEBUG(dbgs() << "\nPromoting ";
1069 Op.getNode()->dump(&DAG));
1070 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1075 bool DAGCombiner::PromoteLoad(SDValue Op) {
1076 if (!LegalOperations)
1079 EVT VT = Op.getValueType();
1080 if (VT.isVector() || !VT.isInteger())
1083 // If operation type is 'undesirable', e.g. i16 on x86, consider
1085 unsigned Opc = Op.getOpcode();
1086 if (TLI.isTypeDesirableForOp(Opc, VT))
1090 // Consult target whether it is a good idea to promote this operation and
1091 // what's the right type to promote it to.
1092 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1093 assert(PVT != VT && "Don't know what type to promote to!");
1096 SDNode *N = Op.getNode();
1097 LoadSDNode *LD = cast<LoadSDNode>(N);
1098 EVT MemVT = LD->getMemoryVT();
1099 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1100 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1102 : LD->getExtensionType();
1103 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1104 LD->getChain(), LD->getBasePtr(),
1105 MemVT, LD->getMemOperand());
1106 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1108 DEBUG(dbgs() << "\nPromoting ";
1111 Result.getNode()->dump(&DAG);
1113 WorklistRemover DeadNodes(*this);
1114 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1115 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1116 deleteAndRecombine(N);
1117 AddToWorklist(Result.getNode());
1123 /// \brief Recursively delete a node which has no uses and any operands for
1124 /// which it is the only use.
1126 /// Note that this both deletes the nodes and removes them from the worklist.
1127 /// It also adds any nodes who have had a user deleted to the worklist as they
1128 /// may now have only one use and subject to other combines.
1129 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1130 if (!N->use_empty())
1133 SmallSetVector<SDNode *, 16> Nodes;
1136 N = Nodes.pop_back_val();
1140 if (N->use_empty()) {
1141 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1142 Nodes.insert(N->getOperand(i).getNode());
1144 removeFromWorklist(N);
1149 } while (!Nodes.empty());
1153 //===----------------------------------------------------------------------===//
1154 // Main DAG Combiner implementation
1155 //===----------------------------------------------------------------------===//
1157 void DAGCombiner::Run(CombineLevel AtLevel) {
1158 // set the instance variables, so that the various visit routines may use it.
1160 LegalOperations = Level >= AfterLegalizeVectorOps;
1161 LegalTypes = Level >= AfterLegalizeTypes;
1163 // Early exit if this basic block is in an optnone function.
1164 AttributeSet FnAttrs =
1165 DAG.getMachineFunction().getFunction()->getAttributes();
1166 if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1167 Attribute::OptimizeNone))
1170 // Add all the dag nodes to the worklist.
1171 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1172 E = DAG.allnodes_end(); I != E; ++I)
1175 // Create a dummy node (which is not added to allnodes), that adds a reference
1176 // to the root node, preventing it from being deleted, and tracking any
1177 // changes of the root.
1178 HandleSDNode Dummy(DAG.getRoot());
1180 // while the worklist isn't empty, find a node and
1181 // try and combine it.
1182 while (!WorklistMap.empty()) {
1184 // The Worklist holds the SDNodes in order, but it may contain null entries.
1186 N = Worklist.pop_back_val();
1189 bool GoodWorklistEntry = WorklistMap.erase(N);
1190 (void)GoodWorklistEntry;
1191 assert(GoodWorklistEntry &&
1192 "Found a worklist entry without a corresponding map entry!");
1194 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1195 // N is deleted from the DAG, since they too may now be dead or may have a
1196 // reduced number of uses, allowing other xforms.
1197 if (recursivelyDeleteUnusedNodes(N))
1200 WorklistRemover DeadNodes(*this);
1202 // If this combine is running after legalizing the DAG, re-legalize any
1203 // nodes pulled off the worklist.
1204 if (Level == AfterLegalizeDAG) {
1205 SmallSetVector<SDNode *, 16> UpdatedNodes;
1206 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1208 for (SDNode *LN : UpdatedNodes) {
1210 AddUsersToWorklist(LN);
1216 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1218 // Add any operands of the new node which have not yet been combined to the
1219 // worklist as well. Because the worklist uniques things already, this
1220 // won't repeatedly process the same operand.
1221 CombinedNodes.insert(N);
1222 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1223 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1224 AddToWorklist(N->getOperand(i).getNode());
1226 SDValue RV = combine(N);
1233 // If we get back the same node we passed in, rather than a new node or
1234 // zero, we know that the node must have defined multiple values and
1235 // CombineTo was used. Since CombineTo takes care of the worklist
1236 // mechanics for us, we have no work to do in this case.
1237 if (RV.getNode() == N)
1240 assert(N->getOpcode() != ISD::DELETED_NODE &&
1241 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1242 "Node was deleted but visit returned new node!");
1244 DEBUG(dbgs() << " ... into: ";
1245 RV.getNode()->dump(&DAG));
1247 // Transfer debug value.
1248 DAG.TransferDbgValues(SDValue(N, 0), RV);
1249 if (N->getNumValues() == RV.getNode()->getNumValues())
1250 DAG.ReplaceAllUsesWith(N, RV.getNode());
1252 assert(N->getValueType(0) == RV.getValueType() &&
1253 N->getNumValues() == 1 && "Type mismatch");
1255 DAG.ReplaceAllUsesWith(N, &OpV);
1258 // Push the new node and any users onto the worklist
1259 AddToWorklist(RV.getNode());
1260 AddUsersToWorklist(RV.getNode());
1262 // Finally, if the node is now dead, remove it from the graph. The node
1263 // may not be dead if the replacement process recursively simplified to
1264 // something else needing this node. This will also take care of adding any
1265 // operands which have lost a user to the worklist.
1266 recursivelyDeleteUnusedNodes(N);
1269 // If the root changed (e.g. it was a dead load, update the root).
1270 DAG.setRoot(Dummy.getValue());
1271 DAG.RemoveDeadNodes();
1274 SDValue DAGCombiner::visit(SDNode *N) {
1275 switch (N->getOpcode()) {
1277 case ISD::TokenFactor: return visitTokenFactor(N);
1278 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1279 case ISD::ADD: return visitADD(N);
1280 case ISD::SUB: return visitSUB(N);
1281 case ISD::ADDC: return visitADDC(N);
1282 case ISD::SUBC: return visitSUBC(N);
1283 case ISD::ADDE: return visitADDE(N);
1284 case ISD::SUBE: return visitSUBE(N);
1285 case ISD::MUL: return visitMUL(N);
1286 case ISD::SDIV: return visitSDIV(N);
1287 case ISD::UDIV: return visitUDIV(N);
1288 case ISD::SREM: return visitSREM(N);
1289 case ISD::UREM: return visitUREM(N);
1290 case ISD::MULHU: return visitMULHU(N);
1291 case ISD::MULHS: return visitMULHS(N);
1292 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1293 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1294 case ISD::SMULO: return visitSMULO(N);
1295 case ISD::UMULO: return visitUMULO(N);
1296 case ISD::SDIVREM: return visitSDIVREM(N);
1297 case ISD::UDIVREM: return visitUDIVREM(N);
1298 case ISD::AND: return visitAND(N);
1299 case ISD::OR: return visitOR(N);
1300 case ISD::XOR: return visitXOR(N);
1301 case ISD::SHL: return visitSHL(N);
1302 case ISD::SRA: return visitSRA(N);
1303 case ISD::SRL: return visitSRL(N);
1305 case ISD::ROTL: return visitRotate(N);
1306 case ISD::CTLZ: return visitCTLZ(N);
1307 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1308 case ISD::CTTZ: return visitCTTZ(N);
1309 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1310 case ISD::CTPOP: return visitCTPOP(N);
1311 case ISD::SELECT: return visitSELECT(N);
1312 case ISD::VSELECT: return visitVSELECT(N);
1313 case ISD::SELECT_CC: return visitSELECT_CC(N);
1314 case ISD::SETCC: return visitSETCC(N);
1315 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1316 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1317 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1318 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1319 case ISD::TRUNCATE: return visitTRUNCATE(N);
1320 case ISD::BITCAST: return visitBITCAST(N);
1321 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1322 case ISD::FADD: return visitFADD(N);
1323 case ISD::FSUB: return visitFSUB(N);
1324 case ISD::FMUL: return visitFMUL(N);
1325 case ISD::FMA: return visitFMA(N);
1326 case ISD::FDIV: return visitFDIV(N);
1327 case ISD::FREM: return visitFREM(N);
1328 case ISD::FSQRT: return visitFSQRT(N);
1329 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1330 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1331 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1332 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1333 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1334 case ISD::FP_ROUND: return visitFP_ROUND(N);
1335 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1336 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1337 case ISD::FNEG: return visitFNEG(N);
1338 case ISD::FABS: return visitFABS(N);
1339 case ISD::FFLOOR: return visitFFLOOR(N);
1340 case ISD::FMINNUM: return visitFMINNUM(N);
1341 case ISD::FMAXNUM: return visitFMAXNUM(N);
1342 case ISD::FCEIL: return visitFCEIL(N);
1343 case ISD::FTRUNC: return visitFTRUNC(N);
1344 case ISD::BRCOND: return visitBRCOND(N);
1345 case ISD::BR_CC: return visitBR_CC(N);
1346 case ISD::LOAD: return visitLOAD(N);
1347 case ISD::STORE: return visitSTORE(N);
1348 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1349 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1350 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1351 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1352 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1353 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1354 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1355 case ISD::MLOAD: return visitMLOAD(N);
1356 case ISD::MSTORE: return visitMSTORE(N);
1361 SDValue DAGCombiner::combine(SDNode *N) {
1362 SDValue RV = visit(N);
1364 // If nothing happened, try a target-specific DAG combine.
1365 if (!RV.getNode()) {
1366 assert(N->getOpcode() != ISD::DELETED_NODE &&
1367 "Node was deleted but visit returned NULL!");
1369 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1370 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1372 // Expose the DAG combiner to the target combiner impls.
1373 TargetLowering::DAGCombinerInfo
1374 DagCombineInfo(DAG, Level, false, this);
1376 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1380 // If nothing happened still, try promoting the operation.
1381 if (!RV.getNode()) {
1382 switch (N->getOpcode()) {
1390 RV = PromoteIntBinOp(SDValue(N, 0));
1395 RV = PromoteIntShiftOp(SDValue(N, 0));
1397 case ISD::SIGN_EXTEND:
1398 case ISD::ZERO_EXTEND:
1399 case ISD::ANY_EXTEND:
1400 RV = PromoteExtend(SDValue(N, 0));
1403 if (PromoteLoad(SDValue(N, 0)))
1409 // If N is a commutative binary node, try commuting it to enable more
1411 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1412 N->getNumValues() == 1) {
1413 SDValue N0 = N->getOperand(0);
1414 SDValue N1 = N->getOperand(1);
1416 // Constant operands are canonicalized to RHS.
1417 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1418 SDValue Ops[] = {N1, N0};
1420 if (const BinaryWithFlagsSDNode *BinNode =
1421 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1422 CSENode = DAG.getNodeIfExists(
1423 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1424 BinNode->hasNoSignedWrap(), BinNode->isExact());
1426 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1429 return SDValue(CSENode, 0);
1436 /// Given a node, return its input chain if it has one, otherwise return a null
1438 static SDValue getInputChainForNode(SDNode *N) {
1439 if (unsigned NumOps = N->getNumOperands()) {
1440 if (N->getOperand(0).getValueType() == MVT::Other)
1441 return N->getOperand(0);
1442 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1443 return N->getOperand(NumOps-1);
1444 for (unsigned i = 1; i < NumOps-1; ++i)
1445 if (N->getOperand(i).getValueType() == MVT::Other)
1446 return N->getOperand(i);
1451 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1452 // If N has two operands, where one has an input chain equal to the other,
1453 // the 'other' chain is redundant.
1454 if (N->getNumOperands() == 2) {
1455 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1456 return N->getOperand(0);
1457 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1458 return N->getOperand(1);
1461 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1462 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1463 SmallPtrSet<SDNode*, 16> SeenOps;
1464 bool Changed = false; // If we should replace this token factor.
1466 // Start out with this token factor.
1469 // Iterate through token factors. The TFs grows when new token factors are
1471 for (unsigned i = 0; i < TFs.size(); ++i) {
1472 SDNode *TF = TFs[i];
1474 // Check each of the operands.
1475 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1476 SDValue Op = TF->getOperand(i);
1478 switch (Op.getOpcode()) {
1479 case ISD::EntryToken:
1480 // Entry tokens don't need to be added to the list. They are
1485 case ISD::TokenFactor:
1486 if (Op.hasOneUse() &&
1487 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1488 // Queue up for processing.
1489 TFs.push_back(Op.getNode());
1490 // Clean up in case the token factor is removed.
1491 AddToWorklist(Op.getNode());
1498 // Only add if it isn't already in the list.
1499 if (SeenOps.insert(Op.getNode()).second)
1510 // If we've change things around then replace token factor.
1513 // The entry token is the only possible outcome.
1514 Result = DAG.getEntryNode();
1516 // New and improved token factor.
1517 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1520 // Don't add users to work list.
1521 return CombineTo(N, Result, false);
1527 /// MERGE_VALUES can always be eliminated.
1528 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1529 WorklistRemover DeadNodes(*this);
1530 // Replacing results may cause a different MERGE_VALUES to suddenly
1531 // be CSE'd with N, and carry its uses with it. Iterate until no
1532 // uses remain, to ensure that the node can be safely deleted.
1533 // First add the users of this node to the work list so that they
1534 // can be tried again once they have new operands.
1535 AddUsersToWorklist(N);
1537 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1538 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1539 } while (!N->use_empty());
1540 deleteAndRecombine(N);
1541 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1544 SDValue DAGCombiner::visitADD(SDNode *N) {
1545 SDValue N0 = N->getOperand(0);
1546 SDValue N1 = N->getOperand(1);
1547 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1548 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1549 EVT VT = N0.getValueType();
1552 if (VT.isVector()) {
1553 SDValue FoldedVOp = SimplifyVBinOp(N);
1554 if (FoldedVOp.getNode()) return FoldedVOp;
1556 // fold (add x, 0) -> x, vector edition
1557 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1559 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1563 // fold (add x, undef) -> undef
1564 if (N0.getOpcode() == ISD::UNDEF)
1566 if (N1.getOpcode() == ISD::UNDEF)
1568 // fold (add c1, c2) -> c1+c2
1570 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1571 // canonicalize constant to RHS
1573 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1574 // fold (add x, 0) -> x
1575 if (N1C && N1C->isNullValue())
1577 // fold (add Sym, c) -> Sym+c
1578 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1579 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1580 GA->getOpcode() == ISD::GlobalAddress)
1581 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1583 (uint64_t)N1C->getSExtValue());
1584 // fold ((c1-A)+c2) -> (c1+c2)-A
1585 if (N1C && N0.getOpcode() == ISD::SUB)
1586 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1587 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1588 DAG.getConstant(N1C->getAPIntValue()+
1589 N0C->getAPIntValue(), VT),
1592 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1595 // fold ((0-A) + B) -> B-A
1596 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1597 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1598 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1599 // fold (A + (0-B)) -> A-B
1600 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1601 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1602 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1603 // fold (A+(B-A)) -> B
1604 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1605 return N1.getOperand(0);
1606 // fold ((B-A)+A) -> B
1607 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1608 return N0.getOperand(0);
1609 // fold (A+(B-(A+C))) to (B-C)
1610 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1611 N0 == N1.getOperand(1).getOperand(0))
1612 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1613 N1.getOperand(1).getOperand(1));
1614 // fold (A+(B-(C+A))) to (B-C)
1615 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1616 N0 == N1.getOperand(1).getOperand(1))
1617 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1618 N1.getOperand(1).getOperand(0));
1619 // fold (A+((B-A)+or-C)) to (B+or-C)
1620 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1621 N1.getOperand(0).getOpcode() == ISD::SUB &&
1622 N0 == N1.getOperand(0).getOperand(1))
1623 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1624 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1626 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1627 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1628 SDValue N00 = N0.getOperand(0);
1629 SDValue N01 = N0.getOperand(1);
1630 SDValue N10 = N1.getOperand(0);
1631 SDValue N11 = N1.getOperand(1);
1633 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1634 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1635 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1636 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1639 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1640 return SDValue(N, 0);
1642 // fold (a+b) -> (a|b) iff a and b share no bits.
1643 if (VT.isInteger() && !VT.isVector()) {
1644 APInt LHSZero, LHSOne;
1645 APInt RHSZero, RHSOne;
1646 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1648 if (LHSZero.getBoolValue()) {
1649 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1651 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1652 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1653 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1654 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1655 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1660 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1661 if (N1.getOpcode() == ISD::SHL &&
1662 N1.getOperand(0).getOpcode() == ISD::SUB)
1663 if (ConstantSDNode *C =
1664 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1665 if (C->getAPIntValue() == 0)
1666 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1667 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1668 N1.getOperand(0).getOperand(1),
1670 if (N0.getOpcode() == ISD::SHL &&
1671 N0.getOperand(0).getOpcode() == ISD::SUB)
1672 if (ConstantSDNode *C =
1673 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1674 if (C->getAPIntValue() == 0)
1675 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1676 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1677 N0.getOperand(0).getOperand(1),
1680 if (N1.getOpcode() == ISD::AND) {
1681 SDValue AndOp0 = N1.getOperand(0);
1682 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1683 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1684 unsigned DestBits = VT.getScalarType().getSizeInBits();
1686 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1687 // and similar xforms where the inner op is either ~0 or 0.
1688 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1690 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1694 // add (sext i1), X -> sub X, (zext i1)
1695 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1696 N0.getOperand(0).getValueType() == MVT::i1 &&
1697 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1699 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1700 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1703 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1704 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1705 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1706 if (TN->getVT() == MVT::i1) {
1708 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1709 DAG.getConstant(1, VT));
1710 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1717 SDValue DAGCombiner::visitADDC(SDNode *N) {
1718 SDValue N0 = N->getOperand(0);
1719 SDValue N1 = N->getOperand(1);
1720 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1721 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1722 EVT VT = N0.getValueType();
1724 // If the flag result is dead, turn this into an ADD.
1725 if (!N->hasAnyUseOfValue(1))
1726 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1727 DAG.getNode(ISD::CARRY_FALSE,
1728 SDLoc(N), MVT::Glue));
1730 // canonicalize constant to RHS.
1732 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1734 // fold (addc x, 0) -> x + no carry out
1735 if (N1C && N1C->isNullValue())
1736 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1737 SDLoc(N), MVT::Glue));
1739 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1740 APInt LHSZero, LHSOne;
1741 APInt RHSZero, RHSOne;
1742 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1744 if (LHSZero.getBoolValue()) {
1745 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1747 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1748 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1749 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1750 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1751 DAG.getNode(ISD::CARRY_FALSE,
1752 SDLoc(N), MVT::Glue));
1758 SDValue DAGCombiner::visitADDE(SDNode *N) {
1759 SDValue N0 = N->getOperand(0);
1760 SDValue N1 = N->getOperand(1);
1761 SDValue CarryIn = N->getOperand(2);
1762 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1763 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1765 // canonicalize constant to RHS
1767 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1770 // fold (adde x, y, false) -> (addc x, y)
1771 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1772 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1777 // Since it may not be valid to emit a fold to zero for vector initializers
1778 // check if we can before folding.
1779 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1781 bool LegalOperations, bool LegalTypes) {
1783 return DAG.getConstant(0, VT);
1784 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1785 return DAG.getConstant(0, VT);
1789 SDValue DAGCombiner::visitSUB(SDNode *N) {
1790 SDValue N0 = N->getOperand(0);
1791 SDValue N1 = N->getOperand(1);
1792 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1793 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1794 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1795 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1796 EVT VT = N0.getValueType();
1799 if (VT.isVector()) {
1800 SDValue FoldedVOp = SimplifyVBinOp(N);
1801 if (FoldedVOp.getNode()) return FoldedVOp;
1803 // fold (sub x, 0) -> x, vector edition
1804 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1808 // fold (sub x, x) -> 0
1809 // FIXME: Refactor this and xor and other similar operations together.
1811 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1812 // fold (sub c1, c2) -> c1-c2
1814 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1815 // fold (sub x, c) -> (add x, -c)
1817 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1818 DAG.getConstant(-N1C->getAPIntValue(), VT));
1819 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1820 if (N0C && N0C->isAllOnesValue())
1821 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1822 // fold A-(A-B) -> B
1823 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1824 return N1.getOperand(1);
1825 // fold (A+B)-A -> B
1826 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1827 return N0.getOperand(1);
1828 // fold (A+B)-B -> A
1829 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1830 return N0.getOperand(0);
1831 // fold C2-(A+C1) -> (C2-C1)-A
1832 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1833 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1835 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1838 // fold ((A+(B+or-C))-B) -> A+or-C
1839 if (N0.getOpcode() == ISD::ADD &&
1840 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1841 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1842 N0.getOperand(1).getOperand(0) == N1)
1843 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1844 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1845 // fold ((A+(C+B))-B) -> A+C
1846 if (N0.getOpcode() == ISD::ADD &&
1847 N0.getOperand(1).getOpcode() == ISD::ADD &&
1848 N0.getOperand(1).getOperand(1) == N1)
1849 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1850 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1851 // fold ((A-(B-C))-C) -> A-B
1852 if (N0.getOpcode() == ISD::SUB &&
1853 N0.getOperand(1).getOpcode() == ISD::SUB &&
1854 N0.getOperand(1).getOperand(1) == N1)
1855 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1856 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1858 // If either operand of a sub is undef, the result is undef
1859 if (N0.getOpcode() == ISD::UNDEF)
1861 if (N1.getOpcode() == ISD::UNDEF)
1864 // If the relocation model supports it, consider symbol offsets.
1865 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1866 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1867 // fold (sub Sym, c) -> Sym-c
1868 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1869 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1871 (uint64_t)N1C->getSExtValue());
1872 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1873 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1874 if (GA->getGlobal() == GB->getGlobal())
1875 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1879 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1880 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1881 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1882 if (TN->getVT() == MVT::i1) {
1884 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1885 DAG.getConstant(1, VT));
1886 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1893 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1894 SDValue N0 = N->getOperand(0);
1895 SDValue N1 = N->getOperand(1);
1896 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1897 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1898 EVT VT = N0.getValueType();
1900 // If the flag result is dead, turn this into an SUB.
1901 if (!N->hasAnyUseOfValue(1))
1902 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1903 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1906 // fold (subc x, x) -> 0 + no borrow
1908 return CombineTo(N, DAG.getConstant(0, VT),
1909 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1912 // fold (subc x, 0) -> x + no borrow
1913 if (N1C && N1C->isNullValue())
1914 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1917 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1918 if (N0C && N0C->isAllOnesValue())
1919 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1920 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1926 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1927 SDValue N0 = N->getOperand(0);
1928 SDValue N1 = N->getOperand(1);
1929 SDValue CarryIn = N->getOperand(2);
1931 // fold (sube x, y, false) -> (subc x, y)
1932 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1933 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1938 SDValue DAGCombiner::visitMUL(SDNode *N) {
1939 SDValue N0 = N->getOperand(0);
1940 SDValue N1 = N->getOperand(1);
1941 EVT VT = N0.getValueType();
1943 // fold (mul x, undef) -> 0
1944 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1945 return DAG.getConstant(0, VT);
1947 bool N0IsConst = false;
1948 bool N1IsConst = false;
1949 APInt ConstValue0, ConstValue1;
1951 if (VT.isVector()) {
1952 SDValue FoldedVOp = SimplifyVBinOp(N);
1953 if (FoldedVOp.getNode()) return FoldedVOp;
1955 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1956 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1958 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1959 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1961 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1962 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1966 // fold (mul c1, c2) -> c1*c2
1967 if (N0IsConst && N1IsConst)
1968 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1970 // canonicalize constant to RHS
1971 if (N0IsConst && !N1IsConst)
1972 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1973 // fold (mul x, 0) -> 0
1974 if (N1IsConst && ConstValue1 == 0)
1976 // We require a splat of the entire scalar bit width for non-contiguous
1979 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1980 // fold (mul x, 1) -> x
1981 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1983 // fold (mul x, -1) -> 0-x
1984 if (N1IsConst && ConstValue1.isAllOnesValue())
1985 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1986 DAG.getConstant(0, VT), N0);
1987 // fold (mul x, (1 << c)) -> x << c
1988 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1989 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1990 DAG.getConstant(ConstValue1.logBase2(),
1991 getShiftAmountTy(N0.getValueType())));
1992 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1993 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1994 unsigned Log2Val = (-ConstValue1).logBase2();
1995 // FIXME: If the input is something that is easily negated (e.g. a
1996 // single-use add), we should put the negate there.
1997 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1998 DAG.getConstant(0, VT),
1999 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2000 DAG.getConstant(Log2Val,
2001 getShiftAmountTy(N0.getValueType()))));
2005 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2006 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2007 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2008 isa<ConstantSDNode>(N0.getOperand(1)))) {
2009 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2010 N1, N0.getOperand(1));
2011 AddToWorklist(C3.getNode());
2012 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2013 N0.getOperand(0), C3);
2016 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2019 SDValue Sh(nullptr,0), Y(nullptr,0);
2020 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2021 if (N0.getOpcode() == ISD::SHL &&
2022 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2023 isa<ConstantSDNode>(N0.getOperand(1))) &&
2024 N0.getNode()->hasOneUse()) {
2026 } else if (N1.getOpcode() == ISD::SHL &&
2027 isa<ConstantSDNode>(N1.getOperand(1)) &&
2028 N1.getNode()->hasOneUse()) {
2033 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2034 Sh.getOperand(0), Y);
2035 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2036 Mul, Sh.getOperand(1));
2040 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2041 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2042 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2043 isa<ConstantSDNode>(N0.getOperand(1))))
2044 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2045 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2046 N0.getOperand(0), N1),
2047 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2048 N0.getOperand(1), N1));
2051 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2058 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2059 SDValue N0 = N->getOperand(0);
2060 SDValue N1 = N->getOperand(1);
2061 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2062 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2063 EVT VT = N->getValueType(0);
2066 if (VT.isVector()) {
2067 SDValue FoldedVOp = SimplifyVBinOp(N);
2068 if (FoldedVOp.getNode()) return FoldedVOp;
2071 // fold (sdiv c1, c2) -> c1/c2
2072 if (N0C && N1C && !N1C->isNullValue())
2073 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2074 // fold (sdiv X, 1) -> X
2075 if (N1C && N1C->getAPIntValue() == 1LL)
2077 // fold (sdiv X, -1) -> 0-X
2078 if (N1C && N1C->isAllOnesValue())
2079 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2080 DAG.getConstant(0, VT), N0);
2081 // If we know the sign bits of both operands are zero, strength reduce to a
2082 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2083 if (!VT.isVector()) {
2084 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2085 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2089 // fold (sdiv X, pow2) -> simple ops after legalize
2090 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2091 (-N1C->getAPIntValue()).isPowerOf2())) {
2092 // If dividing by powers of two is cheap, then don't perform the following
2094 if (TLI.isPow2SDivCheap())
2097 // Target-specific implementation of sdiv x, pow2.
2098 SDValue Res = BuildSDIVPow2(N);
2102 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2104 // Splat the sign bit into the register
2106 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2107 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2108 getShiftAmountTy(N0.getValueType())));
2109 AddToWorklist(SGN.getNode());
2111 // Add (N0 < 0) ? abs2 - 1 : 0;
2113 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2114 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2115 getShiftAmountTy(SGN.getValueType())));
2116 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2117 AddToWorklist(SRL.getNode());
2118 AddToWorklist(ADD.getNode()); // Divide by pow2
2119 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2120 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2122 // If we're dividing by a positive value, we're done. Otherwise, we must
2123 // negate the result.
2124 if (N1C->getAPIntValue().isNonNegative())
2127 AddToWorklist(SRA.getNode());
2128 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2131 // if integer divide is expensive and we satisfy the requirements, emit an
2132 // alternate sequence.
2133 if (N1C && !TLI.isIntDivCheap()) {
2134 SDValue Op = BuildSDIV(N);
2135 if (Op.getNode()) return Op;
2139 if (N0.getOpcode() == ISD::UNDEF)
2140 return DAG.getConstant(0, VT);
2141 // X / undef -> undef
2142 if (N1.getOpcode() == ISD::UNDEF)
2148 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2149 SDValue N0 = N->getOperand(0);
2150 SDValue N1 = N->getOperand(1);
2151 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2152 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2153 EVT VT = N->getValueType(0);
2156 if (VT.isVector()) {
2157 SDValue FoldedVOp = SimplifyVBinOp(N);
2158 if (FoldedVOp.getNode()) return FoldedVOp;
2161 // fold (udiv c1, c2) -> c1/c2
2162 if (N0C && N1C && !N1C->isNullValue())
2163 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2164 // fold (udiv x, (1 << c)) -> x >>u c
2165 if (N1C && N1C->getAPIntValue().isPowerOf2())
2166 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2167 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2168 getShiftAmountTy(N0.getValueType())));
2169 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2170 if (N1.getOpcode() == ISD::SHL) {
2171 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2172 if (SHC->getAPIntValue().isPowerOf2()) {
2173 EVT ADDVT = N1.getOperand(1).getValueType();
2174 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2176 DAG.getConstant(SHC->getAPIntValue()
2179 AddToWorklist(Add.getNode());
2180 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2184 // fold (udiv x, c) -> alternate
2185 if (N1C && !TLI.isIntDivCheap()) {
2186 SDValue Op = BuildUDIV(N);
2187 if (Op.getNode()) return Op;
2191 if (N0.getOpcode() == ISD::UNDEF)
2192 return DAG.getConstant(0, VT);
2193 // X / undef -> undef
2194 if (N1.getOpcode() == ISD::UNDEF)
2200 SDValue DAGCombiner::visitSREM(SDNode *N) {
2201 SDValue N0 = N->getOperand(0);
2202 SDValue N1 = N->getOperand(1);
2203 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2204 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2205 EVT VT = N->getValueType(0);
2207 // fold (srem c1, c2) -> c1%c2
2208 if (N0C && N1C && !N1C->isNullValue())
2209 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2210 // If we know the sign bits of both operands are zero, strength reduce to a
2211 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2212 if (!VT.isVector()) {
2213 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2214 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2217 // If X/C can be simplified by the division-by-constant logic, lower
2218 // X%C to the equivalent of X-X/C*C.
2219 if (N1C && !N1C->isNullValue()) {
2220 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2221 AddToWorklist(Div.getNode());
2222 SDValue OptimizedDiv = combine(Div.getNode());
2223 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2224 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2226 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2227 AddToWorklist(Mul.getNode());
2233 if (N0.getOpcode() == ISD::UNDEF)
2234 return DAG.getConstant(0, VT);
2235 // X % undef -> undef
2236 if (N1.getOpcode() == ISD::UNDEF)
2242 SDValue DAGCombiner::visitUREM(SDNode *N) {
2243 SDValue N0 = N->getOperand(0);
2244 SDValue N1 = N->getOperand(1);
2245 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2246 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2247 EVT VT = N->getValueType(0);
2249 // fold (urem c1, c2) -> c1%c2
2250 if (N0C && N1C && !N1C->isNullValue())
2251 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2252 // fold (urem x, pow2) -> (and x, pow2-1)
2253 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2254 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2255 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2256 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2257 if (N1.getOpcode() == ISD::SHL) {
2258 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2259 if (SHC->getAPIntValue().isPowerOf2()) {
2261 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2262 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2264 AddToWorklist(Add.getNode());
2265 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2270 // If X/C can be simplified by the division-by-constant logic, lower
2271 // X%C to the equivalent of X-X/C*C.
2272 if (N1C && !N1C->isNullValue()) {
2273 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2274 AddToWorklist(Div.getNode());
2275 SDValue OptimizedDiv = combine(Div.getNode());
2276 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2277 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2279 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2280 AddToWorklist(Mul.getNode());
2286 if (N0.getOpcode() == ISD::UNDEF)
2287 return DAG.getConstant(0, VT);
2288 // X % undef -> undef
2289 if (N1.getOpcode() == ISD::UNDEF)
2295 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2296 SDValue N0 = N->getOperand(0);
2297 SDValue N1 = N->getOperand(1);
2298 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2299 EVT VT = N->getValueType(0);
2302 // fold (mulhs x, 0) -> 0
2303 if (N1C && N1C->isNullValue())
2305 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2306 if (N1C && N1C->getAPIntValue() == 1)
2307 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2308 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2309 getShiftAmountTy(N0.getValueType())));
2310 // fold (mulhs x, undef) -> 0
2311 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2312 return DAG.getConstant(0, VT);
2314 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2316 if (VT.isSimple() && !VT.isVector()) {
2317 MVT Simple = VT.getSimpleVT();
2318 unsigned SimpleSize = Simple.getSizeInBits();
2319 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2320 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2321 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2322 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2323 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2324 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2325 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2326 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2333 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2334 SDValue N0 = N->getOperand(0);
2335 SDValue N1 = N->getOperand(1);
2336 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2337 EVT VT = N->getValueType(0);
2340 // fold (mulhu x, 0) -> 0
2341 if (N1C && N1C->isNullValue())
2343 // fold (mulhu x, 1) -> 0
2344 if (N1C && N1C->getAPIntValue() == 1)
2345 return DAG.getConstant(0, N0.getValueType());
2346 // fold (mulhu x, undef) -> 0
2347 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2348 return DAG.getConstant(0, VT);
2350 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2352 if (VT.isSimple() && !VT.isVector()) {
2353 MVT Simple = VT.getSimpleVT();
2354 unsigned SimpleSize = Simple.getSizeInBits();
2355 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2356 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2357 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2358 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2359 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2360 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2361 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2362 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2369 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2370 /// give the opcodes for the two computations that are being performed. Return
2371 /// true if a simplification was made.
2372 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2374 // If the high half is not needed, just compute the low half.
2375 bool HiExists = N->hasAnyUseOfValue(1);
2377 (!LegalOperations ||
2378 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2379 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2380 return CombineTo(N, Res, Res);
2383 // If the low half is not needed, just compute the high half.
2384 bool LoExists = N->hasAnyUseOfValue(0);
2386 (!LegalOperations ||
2387 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2388 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2389 return CombineTo(N, Res, Res);
2392 // If both halves are used, return as it is.
2393 if (LoExists && HiExists)
2396 // If the two computed results can be simplified separately, separate them.
2398 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2399 AddToWorklist(Lo.getNode());
2400 SDValue LoOpt = combine(Lo.getNode());
2401 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2402 (!LegalOperations ||
2403 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2404 return CombineTo(N, LoOpt, LoOpt);
2408 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2409 AddToWorklist(Hi.getNode());
2410 SDValue HiOpt = combine(Hi.getNode());
2411 if (HiOpt.getNode() && HiOpt != Hi &&
2412 (!LegalOperations ||
2413 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2414 return CombineTo(N, HiOpt, HiOpt);
2420 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2421 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2422 if (Res.getNode()) return Res;
2424 EVT VT = N->getValueType(0);
2427 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2429 if (VT.isSimple() && !VT.isVector()) {
2430 MVT Simple = VT.getSimpleVT();
2431 unsigned SimpleSize = Simple.getSizeInBits();
2432 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2433 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2434 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2435 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2436 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2437 // Compute the high part as N1.
2438 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2439 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2440 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2441 // Compute the low part as N0.
2442 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2443 return CombineTo(N, Lo, Hi);
2450 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2451 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2452 if (Res.getNode()) return Res;
2454 EVT VT = N->getValueType(0);
2457 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2459 if (VT.isSimple() && !VT.isVector()) {
2460 MVT Simple = VT.getSimpleVT();
2461 unsigned SimpleSize = Simple.getSizeInBits();
2462 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2463 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2464 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2465 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2466 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2467 // Compute the high part as N1.
2468 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2469 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2470 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2471 // Compute the low part as N0.
2472 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2473 return CombineTo(N, Lo, Hi);
2480 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2481 // (smulo x, 2) -> (saddo x, x)
2482 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2483 if (C2->getAPIntValue() == 2)
2484 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2485 N->getOperand(0), N->getOperand(0));
2490 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2491 // (umulo x, 2) -> (uaddo x, x)
2492 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2493 if (C2->getAPIntValue() == 2)
2494 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2495 N->getOperand(0), N->getOperand(0));
2500 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2501 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2502 if (Res.getNode()) return Res;
2507 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2508 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2509 if (Res.getNode()) return Res;
2514 /// If this is a binary operator with two operands of the same opcode, try to
2516 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2517 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2518 EVT VT = N0.getValueType();
2519 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2521 // Bail early if none of these transforms apply.
2522 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2524 // For each of OP in AND/OR/XOR:
2525 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2526 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2527 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2528 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2529 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2531 // do not sink logical op inside of a vector extend, since it may combine
2533 EVT Op0VT = N0.getOperand(0).getValueType();
2534 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2535 N0.getOpcode() == ISD::SIGN_EXTEND ||
2536 N0.getOpcode() == ISD::BSWAP ||
2537 // Avoid infinite looping with PromoteIntBinOp.
2538 (N0.getOpcode() == ISD::ANY_EXTEND &&
2539 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2540 (N0.getOpcode() == ISD::TRUNCATE &&
2541 (!TLI.isZExtFree(VT, Op0VT) ||
2542 !TLI.isTruncateFree(Op0VT, VT)) &&
2543 TLI.isTypeLegal(Op0VT))) &&
2545 Op0VT == N1.getOperand(0).getValueType() &&
2546 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2547 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2548 N0.getOperand(0).getValueType(),
2549 N0.getOperand(0), N1.getOperand(0));
2550 AddToWorklist(ORNode.getNode());
2551 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2554 // For each of OP in SHL/SRL/SRA/AND...
2555 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2556 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2557 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2558 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2559 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2560 N0.getOperand(1) == N1.getOperand(1)) {
2561 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2562 N0.getOperand(0).getValueType(),
2563 N0.getOperand(0), N1.getOperand(0));
2564 AddToWorklist(ORNode.getNode());
2565 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2566 ORNode, N0.getOperand(1));
2569 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2570 // Only perform this optimization after type legalization and before
2571 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2572 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2573 // we don't want to undo this promotion.
2574 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2576 if ((N0.getOpcode() == ISD::BITCAST ||
2577 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2578 Level == AfterLegalizeTypes) {
2579 SDValue In0 = N0.getOperand(0);
2580 SDValue In1 = N1.getOperand(0);
2581 EVT In0Ty = In0.getValueType();
2582 EVT In1Ty = In1.getValueType();
2584 // If both incoming values are integers, and the original types are the
2586 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2587 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2588 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2589 AddToWorklist(Op.getNode());
2594 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2595 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2596 // If both shuffles use the same mask, and both shuffle within a single
2597 // vector, then it is worthwhile to move the swizzle after the operation.
2598 // The type-legalizer generates this pattern when loading illegal
2599 // vector types from memory. In many cases this allows additional shuffle
2601 // There are other cases where moving the shuffle after the xor/and/or
2602 // is profitable even if shuffles don't perform a swizzle.
2603 // If both shuffles use the same mask, and both shuffles have the same first
2604 // or second operand, then it might still be profitable to move the shuffle
2605 // after the xor/and/or operation.
2606 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2607 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2608 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2610 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2611 "Inputs to shuffles are not the same type");
2613 // Check that both shuffles use the same mask. The masks are known to be of
2614 // the same length because the result vector type is the same.
2615 // Check also that shuffles have only one use to avoid introducing extra
2617 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2618 SVN0->getMask().equals(SVN1->getMask())) {
2619 SDValue ShOp = N0->getOperand(1);
2621 // Don't try to fold this node if it requires introducing a
2622 // build vector of all zeros that might be illegal at this stage.
2623 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2625 ShOp = DAG.getConstant(0, VT);
2630 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2631 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2632 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2633 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2634 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2635 N0->getOperand(0), N1->getOperand(0));
2636 AddToWorklist(NewNode.getNode());
2637 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2638 &SVN0->getMask()[0]);
2641 // Don't try to fold this node if it requires introducing a
2642 // build vector of all zeros that might be illegal at this stage.
2643 ShOp = N0->getOperand(0);
2644 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2646 ShOp = DAG.getConstant(0, VT);
2651 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2652 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2653 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2654 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2655 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2656 N0->getOperand(1), N1->getOperand(1));
2657 AddToWorklist(NewNode.getNode());
2658 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2659 &SVN0->getMask()[0]);
2667 SDValue DAGCombiner::visitAND(SDNode *N) {
2668 SDValue N0 = N->getOperand(0);
2669 SDValue N1 = N->getOperand(1);
2670 SDValue LL, LR, RL, RR, CC0, CC1;
2671 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2672 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2673 EVT VT = N1.getValueType();
2674 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2677 if (VT.isVector()) {
2678 SDValue FoldedVOp = SimplifyVBinOp(N);
2679 if (FoldedVOp.getNode()) return FoldedVOp;
2681 // fold (and x, 0) -> 0, vector edition
2682 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2683 // do not return N0, because undef node may exist in N0
2684 return DAG.getConstant(
2685 APInt::getNullValue(
2686 N0.getValueType().getScalarType().getSizeInBits()),
2688 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2689 // do not return N1, because undef node may exist in N1
2690 return DAG.getConstant(
2691 APInt::getNullValue(
2692 N1.getValueType().getScalarType().getSizeInBits()),
2695 // fold (and x, -1) -> x, vector edition
2696 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2698 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2702 // fold (and x, undef) -> 0
2703 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2704 return DAG.getConstant(0, VT);
2705 // fold (and c1, c2) -> c1&c2
2707 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2708 // canonicalize constant to RHS
2710 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2711 // fold (and x, -1) -> x
2712 if (N1C && N1C->isAllOnesValue())
2714 // if (and x, c) is known to be zero, return 0
2715 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2716 APInt::getAllOnesValue(BitWidth)))
2717 return DAG.getConstant(0, VT);
2719 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2722 // fold (and (or x, C), D) -> D if (C & D) == D
2723 if (N1C && N0.getOpcode() == ISD::OR)
2724 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2725 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2727 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2728 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2729 SDValue N0Op0 = N0.getOperand(0);
2730 APInt Mask = ~N1C->getAPIntValue();
2731 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2732 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2733 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2734 N0.getValueType(), N0Op0);
2736 // Replace uses of the AND with uses of the Zero extend node.
2739 // We actually want to replace all uses of the any_extend with the
2740 // zero_extend, to avoid duplicating things. This will later cause this
2741 // AND to be folded.
2742 CombineTo(N0.getNode(), Zext);
2743 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2746 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2747 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2748 // already be zero by virtue of the width of the base type of the load.
2750 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2752 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2753 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2754 N0.getOpcode() == ISD::LOAD) {
2755 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2756 N0 : N0.getOperand(0) );
2758 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2759 // This can be a pure constant or a vector splat, in which case we treat the
2760 // vector as a scalar and use the splat value.
2761 APInt Constant = APInt::getNullValue(1);
2762 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2763 Constant = C->getAPIntValue();
2764 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2765 APInt SplatValue, SplatUndef;
2766 unsigned SplatBitSize;
2768 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2769 SplatBitSize, HasAnyUndefs);
2771 // Undef bits can contribute to a possible optimisation if set, so
2773 SplatValue |= SplatUndef;
2775 // The splat value may be something like "0x00FFFFFF", which means 0 for
2776 // the first vector value and FF for the rest, repeating. We need a mask
2777 // that will apply equally to all members of the vector, so AND all the
2778 // lanes of the constant together.
2779 EVT VT = Vector->getValueType(0);
2780 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2782 // If the splat value has been compressed to a bitlength lower
2783 // than the size of the vector lane, we need to re-expand it to
2785 if (BitWidth > SplatBitSize)
2786 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2787 SplatBitSize < BitWidth;
2788 SplatBitSize = SplatBitSize * 2)
2789 SplatValue |= SplatValue.shl(SplatBitSize);
2791 Constant = APInt::getAllOnesValue(BitWidth);
2792 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2793 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2797 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2798 // actually legal and isn't going to get expanded, else this is a false
2800 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2801 Load->getValueType(0),
2802 Load->getMemoryVT());
2804 // Resize the constant to the same size as the original memory access before
2805 // extension. If it is still the AllOnesValue then this AND is completely
2808 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2811 switch (Load->getExtensionType()) {
2812 default: B = false; break;
2813 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2815 case ISD::NON_EXTLOAD: B = true; break;
2818 if (B && Constant.isAllOnesValue()) {
2819 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2820 // preserve semantics once we get rid of the AND.
2821 SDValue NewLoad(Load, 0);
2822 if (Load->getExtensionType() == ISD::EXTLOAD) {
2823 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2824 Load->getValueType(0), SDLoc(Load),
2825 Load->getChain(), Load->getBasePtr(),
2826 Load->getOffset(), Load->getMemoryVT(),
2827 Load->getMemOperand());
2828 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2829 if (Load->getNumValues() == 3) {
2830 // PRE/POST_INC loads have 3 values.
2831 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2832 NewLoad.getValue(2) };
2833 CombineTo(Load, To, 3, true);
2835 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2839 // Fold the AND away, taking care not to fold to the old load node if we
2841 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2843 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2846 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2847 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2848 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2849 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2851 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2852 LL.getValueType().isInteger()) {
2853 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2854 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2855 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2856 LR.getValueType(), LL, RL);
2857 AddToWorklist(ORNode.getNode());
2858 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2860 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2861 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2862 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2863 LR.getValueType(), LL, RL);
2864 AddToWorklist(ANDNode.getNode());
2865 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2867 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2868 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2869 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2870 LR.getValueType(), LL, RL);
2871 AddToWorklist(ORNode.getNode());
2872 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2875 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2876 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2877 Op0 == Op1 && LL.getValueType().isInteger() &&
2878 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2879 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2880 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2881 cast<ConstantSDNode>(RR)->isNullValue()))) {
2882 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2883 LL, DAG.getConstant(1, LL.getValueType()));
2884 AddToWorklist(ADDNode.getNode());
2885 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2886 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2888 // canonicalize equivalent to ll == rl
2889 if (LL == RR && LR == RL) {
2890 Op1 = ISD::getSetCCSwappedOperands(Op1);
2893 if (LL == RL && LR == RR) {
2894 bool isInteger = LL.getValueType().isInteger();
2895 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2896 if (Result != ISD::SETCC_INVALID &&
2897 (!LegalOperations ||
2898 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2899 TLI.isOperationLegal(ISD::SETCC,
2900 getSetCCResultType(N0.getSimpleValueType())))))
2901 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2906 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2907 if (N0.getOpcode() == N1.getOpcode()) {
2908 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2909 if (Tmp.getNode()) return Tmp;
2912 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2913 // fold (and (sra)) -> (and (srl)) when possible.
2914 if (!VT.isVector() &&
2915 SimplifyDemandedBits(SDValue(N, 0)))
2916 return SDValue(N, 0);
2918 // fold (zext_inreg (extload x)) -> (zextload x)
2919 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2920 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2921 EVT MemVT = LN0->getMemoryVT();
2922 // If we zero all the possible extended bits, then we can turn this into
2923 // a zextload if we are running before legalize or the operation is legal.
2924 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2925 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2926 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2927 ((!LegalOperations && !LN0->isVolatile()) ||
2928 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2929 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2930 LN0->getChain(), LN0->getBasePtr(),
2931 MemVT, LN0->getMemOperand());
2933 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2934 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2937 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2938 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2940 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2941 EVT MemVT = LN0->getMemoryVT();
2942 // If we zero all the possible extended bits, then we can turn this into
2943 // a zextload if we are running before legalize or the operation is legal.
2944 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2945 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2946 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2947 ((!LegalOperations && !LN0->isVolatile()) ||
2948 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2949 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2950 LN0->getChain(), LN0->getBasePtr(),
2951 MemVT, LN0->getMemOperand());
2953 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2954 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2958 // fold (and (load x), 255) -> (zextload x, i8)
2959 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2960 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2961 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2962 (N0.getOpcode() == ISD::ANY_EXTEND &&
2963 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2964 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2965 LoadSDNode *LN0 = HasAnyExt
2966 ? cast<LoadSDNode>(N0.getOperand(0))
2967 : cast<LoadSDNode>(N0);
2968 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2969 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2970 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2971 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2972 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2973 EVT LoadedVT = LN0->getMemoryVT();
2974 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2976 if (ExtVT == LoadedVT &&
2977 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2981 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2982 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2983 LN0->getMemOperand());
2985 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2986 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2989 // Do not change the width of a volatile load.
2990 // Do not generate loads of non-round integer types since these can
2991 // be expensive (and would be wrong if the type is not byte sized).
2992 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2993 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2995 EVT PtrType = LN0->getOperand(1).getValueType();
2997 unsigned Alignment = LN0->getAlignment();
2998 SDValue NewPtr = LN0->getBasePtr();
3000 // For big endian targets, we need to add an offset to the pointer
3001 // to load the correct bytes. For little endian systems, we merely
3002 // need to read fewer bytes from the same pointer.
3003 if (TLI.isBigEndian()) {
3004 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3005 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3006 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3007 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3008 NewPtr, DAG.getConstant(PtrOff, PtrType));
3009 Alignment = MinAlign(Alignment, PtrOff);
3012 AddToWorklist(NewPtr.getNode());
3015 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3016 LN0->getChain(), NewPtr,
3017 LN0->getPointerInfo(),
3018 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3019 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3021 CombineTo(LN0, Load, Load.getValue(1));
3022 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3028 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3029 VT.getSizeInBits() <= 64) {
3030 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3031 APInt ADDC = ADDI->getAPIntValue();
3032 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3033 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3034 // immediate for an add, but it is legal if its top c2 bits are set,
3035 // transform the ADD so the immediate doesn't need to be materialized
3037 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3038 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3039 SRLI->getZExtValue());
3040 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3042 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3044 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3045 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3046 CombineTo(N0.getNode(), NewAdd);
3047 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3055 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3056 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3057 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3058 N0.getOperand(1), false);
3059 if (BSwap.getNode())
3066 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3067 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3068 bool DemandHighBits) {
3069 if (!LegalOperations)
3072 EVT VT = N->getValueType(0);
3073 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3075 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3078 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3079 bool LookPassAnd0 = false;
3080 bool LookPassAnd1 = false;
3081 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3083 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3085 if (N0.getOpcode() == ISD::AND) {
3086 if (!N0.getNode()->hasOneUse())
3088 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3089 if (!N01C || N01C->getZExtValue() != 0xFF00)
3091 N0 = N0.getOperand(0);
3092 LookPassAnd0 = true;
3095 if (N1.getOpcode() == ISD::AND) {
3096 if (!N1.getNode()->hasOneUse())
3098 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3099 if (!N11C || N11C->getZExtValue() != 0xFF)
3101 N1 = N1.getOperand(0);
3102 LookPassAnd1 = true;
3105 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3107 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3109 if (!N0.getNode()->hasOneUse() ||
3110 !N1.getNode()->hasOneUse())
3113 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3114 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3117 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3120 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3121 SDValue N00 = N0->getOperand(0);
3122 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3123 if (!N00.getNode()->hasOneUse())
3125 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3126 if (!N001C || N001C->getZExtValue() != 0xFF)
3128 N00 = N00.getOperand(0);
3129 LookPassAnd0 = true;
3132 SDValue N10 = N1->getOperand(0);
3133 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3134 if (!N10.getNode()->hasOneUse())
3136 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3137 if (!N101C || N101C->getZExtValue() != 0xFF00)
3139 N10 = N10.getOperand(0);
3140 LookPassAnd1 = true;
3146 // Make sure everything beyond the low halfword gets set to zero since the SRL
3147 // 16 will clear the top bits.
3148 unsigned OpSizeInBits = VT.getSizeInBits();
3149 if (DemandHighBits && OpSizeInBits > 16) {
3150 // If the left-shift isn't masked out then the only way this is a bswap is
3151 // if all bits beyond the low 8 are 0. In that case the entire pattern
3152 // reduces to a left shift anyway: leave it for other parts of the combiner.
3156 // However, if the right shift isn't masked out then it might be because
3157 // it's not needed. See if we can spot that too.
3158 if (!LookPassAnd1 &&
3159 !DAG.MaskedValueIsZero(
3160 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3164 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3165 if (OpSizeInBits > 16)
3166 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3167 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3171 /// Return true if the specified node is an element that makes up a 32-bit
3172 /// packed halfword byteswap.
3173 /// ((x & 0x000000ff) << 8) |
3174 /// ((x & 0x0000ff00) >> 8) |
3175 /// ((x & 0x00ff0000) << 8) |
3176 /// ((x & 0xff000000) >> 8)
3177 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3178 if (!N.getNode()->hasOneUse())
3181 unsigned Opc = N.getOpcode();
3182 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3185 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3190 switch (N1C->getZExtValue()) {
3193 case 0xFF: Num = 0; break;
3194 case 0xFF00: Num = 1; break;
3195 case 0xFF0000: Num = 2; break;
3196 case 0xFF000000: Num = 3; break;
3199 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3200 SDValue N0 = N.getOperand(0);
3201 if (Opc == ISD::AND) {
3202 if (Num == 0 || Num == 2) {
3204 // (x >> 8) & 0xff0000
3205 if (N0.getOpcode() != ISD::SRL)
3207 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3208 if (!C || C->getZExtValue() != 8)
3211 // (x << 8) & 0xff00
3212 // (x << 8) & 0xff000000
3213 if (N0.getOpcode() != ISD::SHL)
3215 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3216 if (!C || C->getZExtValue() != 8)
3219 } else if (Opc == ISD::SHL) {
3221 // (x & 0xff0000) << 8
3222 if (Num != 0 && Num != 2)
3224 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3225 if (!C || C->getZExtValue() != 8)
3227 } else { // Opc == ISD::SRL
3228 // (x & 0xff00) >> 8
3229 // (x & 0xff000000) >> 8
3230 if (Num != 1 && Num != 3)
3232 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3233 if (!C || C->getZExtValue() != 8)
3240 Parts[Num] = N0.getOperand(0).getNode();
3244 /// Match a 32-bit packed halfword bswap. That is
3245 /// ((x & 0x000000ff) << 8) |
3246 /// ((x & 0x0000ff00) >> 8) |
3247 /// ((x & 0x00ff0000) << 8) |
3248 /// ((x & 0xff000000) >> 8)
3249 /// => (rotl (bswap x), 16)
3250 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3251 if (!LegalOperations)
3254 EVT VT = N->getValueType(0);
3257 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3261 // (or (or (and), (and)), (or (and), (and)))
3262 // (or (or (or (and), (and)), (and)), (and))
3263 if (N0.getOpcode() != ISD::OR)
3265 SDValue N00 = N0.getOperand(0);
3266 SDValue N01 = N0.getOperand(1);
3267 SDNode *Parts[4] = {};
3269 if (N1.getOpcode() == ISD::OR &&
3270 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3271 // (or (or (and), (and)), (or (and), (and)))
3272 SDValue N000 = N00.getOperand(0);
3273 if (!isBSwapHWordElement(N000, Parts))
3276 SDValue N001 = N00.getOperand(1);
3277 if (!isBSwapHWordElement(N001, Parts))
3279 SDValue N010 = N01.getOperand(0);
3280 if (!isBSwapHWordElement(N010, Parts))
3282 SDValue N011 = N01.getOperand(1);
3283 if (!isBSwapHWordElement(N011, Parts))
3286 // (or (or (or (and), (and)), (and)), (and))
3287 if (!isBSwapHWordElement(N1, Parts))
3289 if (!isBSwapHWordElement(N01, Parts))
3291 if (N00.getOpcode() != ISD::OR)
3293 SDValue N000 = N00.getOperand(0);
3294 if (!isBSwapHWordElement(N000, Parts))
3296 SDValue N001 = N00.getOperand(1);
3297 if (!isBSwapHWordElement(N001, Parts))
3301 // Make sure the parts are all coming from the same node.
3302 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3305 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3306 SDValue(Parts[0],0));
3308 // Result of the bswap should be rotated by 16. If it's not legal, then
3309 // do (x << 16) | (x >> 16).
3310 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3311 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3312 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3313 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3314 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3315 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3316 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3317 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3320 SDValue DAGCombiner::visitOR(SDNode *N) {
3321 SDValue N0 = N->getOperand(0);
3322 SDValue N1 = N->getOperand(1);
3323 SDValue LL, LR, RL, RR, CC0, CC1;
3324 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3325 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3326 EVT VT = N1.getValueType();
3329 if (VT.isVector()) {
3330 SDValue FoldedVOp = SimplifyVBinOp(N);
3331 if (FoldedVOp.getNode()) return FoldedVOp;
3333 // fold (or x, 0) -> x, vector edition
3334 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3336 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3339 // fold (or x, -1) -> -1, vector edition
3340 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3341 // do not return N0, because undef node may exist in N0
3342 return DAG.getConstant(
3343 APInt::getAllOnesValue(
3344 N0.getValueType().getScalarType().getSizeInBits()),
3346 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3347 // do not return N1, because undef node may exist in N1
3348 return DAG.getConstant(
3349 APInt::getAllOnesValue(
3350 N1.getValueType().getScalarType().getSizeInBits()),
3353 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3354 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3355 // Do this only if the resulting shuffle is legal.
3356 if (isa<ShuffleVectorSDNode>(N0) &&
3357 isa<ShuffleVectorSDNode>(N1) &&
3358 // Avoid folding a node with illegal type.
3359 TLI.isTypeLegal(VT) &&
3360 N0->getOperand(1) == N1->getOperand(1) &&
3361 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3362 bool CanFold = true;
3363 unsigned NumElts = VT.getVectorNumElements();
3364 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3365 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3366 // We construct two shuffle masks:
3367 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3368 // and N1 as the second operand.
3369 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3370 // and N0 as the second operand.
3371 // We do this because OR is commutable and therefore there might be
3372 // two ways to fold this node into a shuffle.
3373 SmallVector<int,4> Mask1;
3374 SmallVector<int,4> Mask2;
3376 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3377 int M0 = SV0->getMaskElt(i);
3378 int M1 = SV1->getMaskElt(i);
3380 // Both shuffle indexes are undef. Propagate Undef.
3381 if (M0 < 0 && M1 < 0) {
3382 Mask1.push_back(M0);
3383 Mask2.push_back(M0);
3387 if (M0 < 0 || M1 < 0 ||
3388 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3389 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3394 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3395 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3399 // Fold this sequence only if the resulting shuffle is 'legal'.
3400 if (TLI.isShuffleMaskLegal(Mask1, VT))
3401 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3402 N1->getOperand(0), &Mask1[0]);
3403 if (TLI.isShuffleMaskLegal(Mask2, VT))
3404 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3405 N0->getOperand(0), &Mask2[0]);
3410 // fold (or x, undef) -> -1
3411 if (!LegalOperations &&
3412 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3413 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3414 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3416 // fold (or c1, c2) -> c1|c2
3418 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3419 // canonicalize constant to RHS
3421 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3422 // fold (or x, 0) -> x
3423 if (N1C && N1C->isNullValue())
3425 // fold (or x, -1) -> -1
3426 if (N1C && N1C->isAllOnesValue())
3428 // fold (or x, c) -> c iff (x & ~c) == 0
3429 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3432 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3433 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3434 if (BSwap.getNode())
3436 BSwap = MatchBSwapHWordLow(N, N0, N1);
3437 if (BSwap.getNode())
3441 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3444 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3445 // iff (c1 & c2) == 0.
3446 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3447 isa<ConstantSDNode>(N0.getOperand(1))) {
3448 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3449 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3450 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3452 ISD::AND, SDLoc(N), VT,
3453 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3457 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3458 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3459 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3460 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3462 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3463 LL.getValueType().isInteger()) {
3464 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3465 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3466 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3467 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3468 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3469 LR.getValueType(), LL, RL);
3470 AddToWorklist(ORNode.getNode());
3471 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3473 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3474 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3475 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3476 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3477 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3478 LR.getValueType(), LL, RL);
3479 AddToWorklist(ANDNode.getNode());
3480 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3483 // canonicalize equivalent to ll == rl
3484 if (LL == RR && LR == RL) {
3485 Op1 = ISD::getSetCCSwappedOperands(Op1);
3488 if (LL == RL && LR == RR) {
3489 bool isInteger = LL.getValueType().isInteger();
3490 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3491 if (Result != ISD::SETCC_INVALID &&
3492 (!LegalOperations ||
3493 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3494 TLI.isOperationLegal(ISD::SETCC,
3495 getSetCCResultType(N0.getValueType())))))
3496 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3501 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3502 if (N0.getOpcode() == N1.getOpcode()) {
3503 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3504 if (Tmp.getNode()) return Tmp;
3507 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3508 if (N0.getOpcode() == ISD::AND &&
3509 N1.getOpcode() == ISD::AND &&
3510 N0.getOperand(1).getOpcode() == ISD::Constant &&
3511 N1.getOperand(1).getOpcode() == ISD::Constant &&
3512 // Don't increase # computations.
3513 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3514 // We can only do this xform if we know that bits from X that are set in C2
3515 // but not in C1 are already zero. Likewise for Y.
3516 const APInt &LHSMask =
3517 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3518 const APInt &RHSMask =
3519 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3521 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3522 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3523 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3524 N0.getOperand(0), N1.getOperand(0));
3525 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3526 DAG.getConstant(LHSMask | RHSMask, VT));
3530 // See if this is some rotate idiom.
3531 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3532 return SDValue(Rot, 0);
3534 // Simplify the operands using demanded-bits information.
3535 if (!VT.isVector() &&
3536 SimplifyDemandedBits(SDValue(N, 0)))
3537 return SDValue(N, 0);
3542 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3543 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3544 if (Op.getOpcode() == ISD::AND) {
3545 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3546 Mask = Op.getOperand(1);
3547 Op = Op.getOperand(0);
3553 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3561 // Return true if we can prove that, whenever Neg and Pos are both in the
3562 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3563 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3565 // (or (shift1 X, Neg), (shift2 X, Pos))
3567 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3568 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3569 // to consider shift amounts with defined behavior.
3570 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3571 // If OpSize is a power of 2 then:
3573 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3574 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3576 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3577 // for the stronger condition:
3579 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3581 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3582 // we can just replace Neg with Neg' for the rest of the function.
3584 // In other cases we check for the even stronger condition:
3586 // Neg == OpSize - Pos [B]
3588 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3589 // behavior if Pos == 0 (and consequently Neg == OpSize).
3591 // We could actually use [A] whenever OpSize is a power of 2, but the
3592 // only extra cases that it would match are those uninteresting ones
3593 // where Neg and Pos are never in range at the same time. E.g. for
3594 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3595 // as well as (sub 32, Pos), but:
3597 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3599 // always invokes undefined behavior for 32-bit X.
3601 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3602 unsigned MaskLoBits = 0;
3603 if (Neg.getOpcode() == ISD::AND &&
3604 isPowerOf2_64(OpSize) &&
3605 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3606 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3607 Neg = Neg.getOperand(0);
3608 MaskLoBits = Log2_64(OpSize);
3611 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3612 if (Neg.getOpcode() != ISD::SUB)
3614 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3617 SDValue NegOp1 = Neg.getOperand(1);
3619 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3620 // Pos'. The truncation is redundant for the purpose of the equality.
3622 Pos.getOpcode() == ISD::AND &&
3623 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3624 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3625 Pos = Pos.getOperand(0);
3627 // The condition we need is now:
3629 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3631 // If NegOp1 == Pos then we need:
3633 // OpSize & Mask == NegC & Mask
3635 // (because "x & Mask" is a truncation and distributes through subtraction).
3638 Width = NegC->getAPIntValue();
3639 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3640 // Then the condition we want to prove becomes:
3642 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3644 // which, again because "x & Mask" is a truncation, becomes:
3646 // NegC & Mask == (OpSize - PosC) & Mask
3647 // OpSize & Mask == (NegC + PosC) & Mask
3648 else if (Pos.getOpcode() == ISD::ADD &&
3649 Pos.getOperand(0) == NegOp1 &&
3650 Pos.getOperand(1).getOpcode() == ISD::Constant)
3651 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3652 NegC->getAPIntValue());
3656 // Now we just need to check that OpSize & Mask == Width & Mask.
3658 // Opsize & Mask is 0 since Mask is Opsize - 1.
3659 return Width.getLoBits(MaskLoBits) == 0;
3660 return Width == OpSize;
3663 // A subroutine of MatchRotate used once we have found an OR of two opposite
3664 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3665 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3666 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3667 // Neg with outer conversions stripped away.
3668 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3669 SDValue Neg, SDValue InnerPos,
3670 SDValue InnerNeg, unsigned PosOpcode,
3671 unsigned NegOpcode, SDLoc DL) {
3672 // fold (or (shl x, (*ext y)),
3673 // (srl x, (*ext (sub 32, y)))) ->
3674 // (rotl x, y) or (rotr x, (sub 32, y))
3676 // fold (or (shl x, (*ext (sub 32, y))),
3677 // (srl x, (*ext y))) ->
3678 // (rotr x, y) or (rotl x, (sub 32, y))
3679 EVT VT = Shifted.getValueType();
3680 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3681 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3682 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3683 HasPos ? Pos : Neg).getNode();
3689 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3690 // idioms for rotate, and if the target supports rotation instructions, generate
3692 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3693 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3694 EVT VT = LHS.getValueType();
3695 if (!TLI.isTypeLegal(VT)) return nullptr;
3697 // The target must have at least one rotate flavor.
3698 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3699 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3700 if (!HasROTL && !HasROTR) return nullptr;
3702 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3703 SDValue LHSShift; // The shift.
3704 SDValue LHSMask; // AND value if any.
3705 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3706 return nullptr; // Not part of a rotate.
3708 SDValue RHSShift; // The shift.
3709 SDValue RHSMask; // AND value if any.
3710 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3711 return nullptr; // Not part of a rotate.
3713 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3714 return nullptr; // Not shifting the same value.
3716 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3717 return nullptr; // Shifts must disagree.
3719 // Canonicalize shl to left side in a shl/srl pair.
3720 if (RHSShift.getOpcode() == ISD::SHL) {
3721 std::swap(LHS, RHS);
3722 std::swap(LHSShift, RHSShift);
3723 std::swap(LHSMask , RHSMask );
3726 unsigned OpSizeInBits = VT.getSizeInBits();
3727 SDValue LHSShiftArg = LHSShift.getOperand(0);
3728 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3729 SDValue RHSShiftArg = RHSShift.getOperand(0);
3730 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3732 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3733 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3734 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3735 RHSShiftAmt.getOpcode() == ISD::Constant) {
3736 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3737 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3738 if ((LShVal + RShVal) != OpSizeInBits)
3741 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3742 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3744 // If there is an AND of either shifted operand, apply it to the result.
3745 if (LHSMask.getNode() || RHSMask.getNode()) {
3746 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3748 if (LHSMask.getNode()) {
3749 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3750 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3752 if (RHSMask.getNode()) {
3753 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3754 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3757 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3760 return Rot.getNode();
3763 // If there is a mask here, and we have a variable shift, we can't be sure
3764 // that we're masking out the right stuff.
3765 if (LHSMask.getNode() || RHSMask.getNode())
3768 // If the shift amount is sign/zext/any-extended just peel it off.
3769 SDValue LExtOp0 = LHSShiftAmt;
3770 SDValue RExtOp0 = RHSShiftAmt;
3771 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3772 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3773 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3774 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3775 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3776 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3777 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3778 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3779 LExtOp0 = LHSShiftAmt.getOperand(0);
3780 RExtOp0 = RHSShiftAmt.getOperand(0);
3783 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3784 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3788 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3789 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3796 SDValue DAGCombiner::visitXOR(SDNode *N) {
3797 SDValue N0 = N->getOperand(0);
3798 SDValue N1 = N->getOperand(1);
3799 SDValue LHS, RHS, CC;
3800 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3801 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3802 EVT VT = N0.getValueType();
3805 if (VT.isVector()) {
3806 SDValue FoldedVOp = SimplifyVBinOp(N);
3807 if (FoldedVOp.getNode()) return FoldedVOp;
3809 // fold (xor x, 0) -> x, vector edition
3810 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3812 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3816 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3817 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3818 return DAG.getConstant(0, VT);
3819 // fold (xor x, undef) -> undef
3820 if (N0.getOpcode() == ISD::UNDEF)
3822 if (N1.getOpcode() == ISD::UNDEF)
3824 // fold (xor c1, c2) -> c1^c2
3826 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3827 // canonicalize constant to RHS
3829 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3830 // fold (xor x, 0) -> x
3831 if (N1C && N1C->isNullValue())
3834 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3838 // fold !(x cc y) -> (x !cc y)
3839 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3840 bool isInt = LHS.getValueType().isInteger();
3841 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3844 if (!LegalOperations ||
3845 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3846 switch (N0.getOpcode()) {
3848 llvm_unreachable("Unhandled SetCC Equivalent!");
3850 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3851 case ISD::SELECT_CC:
3852 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3853 N0.getOperand(3), NotCC);
3858 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3859 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3860 N0.getNode()->hasOneUse() &&
3861 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3862 SDValue V = N0.getOperand(0);
3863 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3864 DAG.getConstant(1, V.getValueType()));
3865 AddToWorklist(V.getNode());
3866 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3869 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3870 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3871 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3872 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3873 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3874 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3875 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3876 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3877 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3878 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3881 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3882 if (N1C && N1C->isAllOnesValue() &&
3883 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3884 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3885 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3886 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3887 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3888 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3889 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3890 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3893 // fold (xor (and x, y), y) -> (and (not x), y)
3894 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3895 N0->getOperand(1) == N1) {
3896 SDValue X = N0->getOperand(0);
3897 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3898 AddToWorklist(NotX.getNode());
3899 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3901 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3902 if (N1C && N0.getOpcode() == ISD::XOR) {
3903 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3904 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3906 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3907 DAG.getConstant(N1C->getAPIntValue() ^
3908 N00C->getAPIntValue(), VT));
3910 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3911 DAG.getConstant(N1C->getAPIntValue() ^
3912 N01C->getAPIntValue(), VT));
3914 // fold (xor x, x) -> 0
3916 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3918 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3919 if (N0.getOpcode() == N1.getOpcode()) {
3920 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3921 if (Tmp.getNode()) return Tmp;
3924 // Simplify the expression using non-local knowledge.
3925 if (!VT.isVector() &&
3926 SimplifyDemandedBits(SDValue(N, 0)))
3927 return SDValue(N, 0);
3932 /// Handle transforms common to the three shifts, when the shift amount is a
3934 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3935 // We can't and shouldn't fold opaque constants.
3936 if (Amt->isOpaque())
3939 SDNode *LHS = N->getOperand(0).getNode();
3940 if (!LHS->hasOneUse()) return SDValue();
3942 // We want to pull some binops through shifts, so that we have (and (shift))
3943 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3944 // thing happens with address calculations, so it's important to canonicalize
3946 bool HighBitSet = false; // Can we transform this if the high bit is set?
3948 switch (LHS->getOpcode()) {
3949 default: return SDValue();
3952 HighBitSet = false; // We can only transform sra if the high bit is clear.
3955 HighBitSet = true; // We can only transform sra if the high bit is set.
3958 if (N->getOpcode() != ISD::SHL)
3959 return SDValue(); // only shl(add) not sr[al](add).
3960 HighBitSet = false; // We can only transform sra if the high bit is clear.
3964 // We require the RHS of the binop to be a constant and not opaque as well.
3965 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3966 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3968 // FIXME: disable this unless the input to the binop is a shift by a constant.
3969 // If it is not a shift, it pessimizes some common cases like:
3971 // void foo(int *X, int i) { X[i & 1235] = 1; }
3972 // int bar(int *X, int i) { return X[i & 255]; }
3973 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3974 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3975 BinOpLHSVal->getOpcode() != ISD::SRA &&
3976 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3977 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3980 EVT VT = N->getValueType(0);
3982 // If this is a signed shift right, and the high bit is modified by the
3983 // logical operation, do not perform the transformation. The highBitSet
3984 // boolean indicates the value of the high bit of the constant which would
3985 // cause it to be modified for this operation.
3986 if (N->getOpcode() == ISD::SRA) {
3987 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3988 if (BinOpRHSSignSet != HighBitSet)
3992 if (!TLI.isDesirableToCommuteWithShift(LHS))
3995 // Fold the constants, shifting the binop RHS by the shift amount.
3996 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3998 LHS->getOperand(1), N->getOperand(1));
3999 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4001 // Create the new shift.
4002 SDValue NewShift = DAG.getNode(N->getOpcode(),
4003 SDLoc(LHS->getOperand(0)),
4004 VT, LHS->getOperand(0), N->getOperand(1));
4006 // Create the new binop.
4007 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4010 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4011 assert(N->getOpcode() == ISD::TRUNCATE);
4012 assert(N->getOperand(0).getOpcode() == ISD::AND);
4014 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4015 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4016 SDValue N01 = N->getOperand(0).getOperand(1);
4018 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4019 EVT TruncVT = N->getValueType(0);
4020 SDValue N00 = N->getOperand(0).getOperand(0);
4021 APInt TruncC = N01C->getAPIntValue();
4022 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4024 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4025 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4026 DAG.getConstant(TruncC, TruncVT));
4033 SDValue DAGCombiner::visitRotate(SDNode *N) {
4034 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4035 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4036 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4037 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4038 if (NewOp1.getNode())
4039 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4040 N->getOperand(0), NewOp1);
4045 SDValue DAGCombiner::visitSHL(SDNode *N) {
4046 SDValue N0 = N->getOperand(0);
4047 SDValue N1 = N->getOperand(1);
4048 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4049 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4050 EVT VT = N0.getValueType();
4051 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4054 if (VT.isVector()) {
4055 SDValue FoldedVOp = SimplifyVBinOp(N);
4056 if (FoldedVOp.getNode()) return FoldedVOp;
4058 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4059 // If setcc produces all-one true value then:
4060 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4061 if (N1CV && N1CV->isConstant()) {
4062 if (N0.getOpcode() == ISD::AND) {
4063 SDValue N00 = N0->getOperand(0);
4064 SDValue N01 = N0->getOperand(1);
4065 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4067 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4068 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4069 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4070 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4071 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4074 N1C = isConstOrConstSplat(N1);
4079 // fold (shl c1, c2) -> c1<<c2
4081 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4082 // fold (shl 0, x) -> 0
4083 if (N0C && N0C->isNullValue())
4085 // fold (shl x, c >= size(x)) -> undef
4086 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4087 return DAG.getUNDEF(VT);
4088 // fold (shl x, 0) -> x
4089 if (N1C && N1C->isNullValue())
4091 // fold (shl undef, x) -> 0
4092 if (N0.getOpcode() == ISD::UNDEF)
4093 return DAG.getConstant(0, VT);
4094 // if (shl x, c) is known to be zero, return 0
4095 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4096 APInt::getAllOnesValue(OpSizeInBits)))
4097 return DAG.getConstant(0, VT);
4098 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4099 if (N1.getOpcode() == ISD::TRUNCATE &&
4100 N1.getOperand(0).getOpcode() == ISD::AND) {
4101 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4102 if (NewOp1.getNode())
4103 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4106 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4107 return SDValue(N, 0);
4109 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4110 if (N1C && N0.getOpcode() == ISD::SHL) {
4111 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4112 uint64_t c1 = N0C1->getZExtValue();
4113 uint64_t c2 = N1C->getZExtValue();
4114 if (c1 + c2 >= OpSizeInBits)
4115 return DAG.getConstant(0, VT);
4116 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4117 DAG.getConstant(c1 + c2, N1.getValueType()));
4121 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4122 // For this to be valid, the second form must not preserve any of the bits
4123 // that are shifted out by the inner shift in the first form. This means
4124 // the outer shift size must be >= the number of bits added by the ext.
4125 // As a corollary, we don't care what kind of ext it is.
4126 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4127 N0.getOpcode() == ISD::ANY_EXTEND ||
4128 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4129 N0.getOperand(0).getOpcode() == ISD::SHL) {
4130 SDValue N0Op0 = N0.getOperand(0);
4131 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4132 uint64_t c1 = N0Op0C1->getZExtValue();
4133 uint64_t c2 = N1C->getZExtValue();
4134 EVT InnerShiftVT = N0Op0.getValueType();
4135 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4136 if (c2 >= OpSizeInBits - InnerShiftSize) {
4137 if (c1 + c2 >= OpSizeInBits)
4138 return DAG.getConstant(0, VT);
4139 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4140 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4141 N0Op0->getOperand(0)),
4142 DAG.getConstant(c1 + c2, N1.getValueType()));
4147 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4148 // Only fold this if the inner zext has no other uses to avoid increasing
4149 // the total number of instructions.
4150 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4151 N0.getOperand(0).getOpcode() == ISD::SRL) {
4152 SDValue N0Op0 = N0.getOperand(0);
4153 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4154 uint64_t c1 = N0Op0C1->getZExtValue();
4155 if (c1 < VT.getScalarSizeInBits()) {
4156 uint64_t c2 = N1C->getZExtValue();
4158 SDValue NewOp0 = N0.getOperand(0);
4159 EVT CountVT = NewOp0.getOperand(1).getValueType();
4160 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4161 NewOp0, DAG.getConstant(c2, CountVT));
4162 AddToWorklist(NewSHL.getNode());
4163 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4169 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4170 // (and (srl x, (sub c1, c2), MASK)
4171 // Only fold this if the inner shift has no other uses -- if it does, folding
4172 // this will increase the total number of instructions.
4173 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4174 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4175 uint64_t c1 = N0C1->getZExtValue();
4176 if (c1 < OpSizeInBits) {
4177 uint64_t c2 = N1C->getZExtValue();
4178 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4181 Mask = Mask.shl(c2 - c1);
4182 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4183 DAG.getConstant(c2 - c1, N1.getValueType()));
4185 Mask = Mask.lshr(c1 - c2);
4186 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4187 DAG.getConstant(c1 - c2, N1.getValueType()));
4189 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4190 DAG.getConstant(Mask, VT));
4194 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4195 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4196 unsigned BitSize = VT.getScalarSizeInBits();
4197 SDValue HiBitsMask =
4198 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4199 BitSize - N1C->getZExtValue()), VT);
4200 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4204 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4205 // Variant of version done on multiply, except mul by a power of 2 is turned
4208 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4209 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4210 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4211 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4212 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4213 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4217 SDValue NewSHL = visitShiftByConstant(N, N1C);
4218 if (NewSHL.getNode())
4225 SDValue DAGCombiner::visitSRA(SDNode *N) {
4226 SDValue N0 = N->getOperand(0);
4227 SDValue N1 = N->getOperand(1);
4228 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4229 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4230 EVT VT = N0.getValueType();
4231 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4234 if (VT.isVector()) {
4235 SDValue FoldedVOp = SimplifyVBinOp(N);
4236 if (FoldedVOp.getNode()) return FoldedVOp;
4238 N1C = isConstOrConstSplat(N1);
4241 // fold (sra c1, c2) -> (sra c1, c2)
4243 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4244 // fold (sra 0, x) -> 0
4245 if (N0C && N0C->isNullValue())
4247 // fold (sra -1, x) -> -1
4248 if (N0C && N0C->isAllOnesValue())
4250 // fold (sra x, (setge c, size(x))) -> undef
4251 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4252 return DAG.getUNDEF(VT);
4253 // fold (sra x, 0) -> x
4254 if (N1C && N1C->isNullValue())
4256 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4258 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4259 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4260 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4262 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4263 ExtVT, VT.getVectorNumElements());
4264 if ((!LegalOperations ||
4265 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4266 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4267 N0.getOperand(0), DAG.getValueType(ExtVT));
4270 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4271 if (N1C && N0.getOpcode() == ISD::SRA) {
4272 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4273 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4274 if (Sum >= OpSizeInBits)
4275 Sum = OpSizeInBits - 1;
4276 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4277 DAG.getConstant(Sum, N1.getValueType()));
4281 // fold (sra (shl X, m), (sub result_size, n))
4282 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4283 // result_size - n != m.
4284 // If truncate is free for the target sext(shl) is likely to result in better
4286 if (N0.getOpcode() == ISD::SHL && N1C) {
4287 // Get the two constanst of the shifts, CN0 = m, CN = n.
4288 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4290 LLVMContext &Ctx = *DAG.getContext();
4291 // Determine what the truncate's result bitsize and type would be.
4292 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4295 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4297 // Determine the residual right-shift amount.
4298 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4300 // If the shift is not a no-op (in which case this should be just a sign
4301 // extend already), the truncated to type is legal, sign_extend is legal
4302 // on that type, and the truncate to that type is both legal and free,
4303 // perform the transform.
4304 if ((ShiftAmt > 0) &&
4305 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4306 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4307 TLI.isTruncateFree(VT, TruncVT)) {
4309 SDValue Amt = DAG.getConstant(ShiftAmt,
4310 getShiftAmountTy(N0.getOperand(0).getValueType()));
4311 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4312 N0.getOperand(0), Amt);
4313 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4315 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4316 N->getValueType(0), Trunc);
4321 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4322 if (N1.getOpcode() == ISD::TRUNCATE &&
4323 N1.getOperand(0).getOpcode() == ISD::AND) {
4324 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4325 if (NewOp1.getNode())
4326 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4329 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4330 // if c1 is equal to the number of bits the trunc removes
4331 if (N0.getOpcode() == ISD::TRUNCATE &&
4332 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4333 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4334 N0.getOperand(0).hasOneUse() &&
4335 N0.getOperand(0).getOperand(1).hasOneUse() &&
4337 SDValue N0Op0 = N0.getOperand(0);
4338 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4339 unsigned LargeShiftVal = LargeShift->getZExtValue();
4340 EVT LargeVT = N0Op0.getValueType();
4342 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4344 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4345 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4346 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4347 N0Op0.getOperand(0), Amt);
4348 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4353 // Simplify, based on bits shifted out of the LHS.
4354 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4355 return SDValue(N, 0);
4358 // If the sign bit is known to be zero, switch this to a SRL.
4359 if (DAG.SignBitIsZero(N0))
4360 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4363 SDValue NewSRA = visitShiftByConstant(N, N1C);
4364 if (NewSRA.getNode())
4371 SDValue DAGCombiner::visitSRL(SDNode *N) {
4372 SDValue N0 = N->getOperand(0);
4373 SDValue N1 = N->getOperand(1);
4374 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4375 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4376 EVT VT = N0.getValueType();
4377 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4380 if (VT.isVector()) {
4381 SDValue FoldedVOp = SimplifyVBinOp(N);
4382 if (FoldedVOp.getNode()) return FoldedVOp;
4384 N1C = isConstOrConstSplat(N1);
4387 // fold (srl c1, c2) -> c1 >>u c2
4389 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4390 // fold (srl 0, x) -> 0
4391 if (N0C && N0C->isNullValue())
4393 // fold (srl x, c >= size(x)) -> undef
4394 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4395 return DAG.getUNDEF(VT);
4396 // fold (srl x, 0) -> x
4397 if (N1C && N1C->isNullValue())
4399 // if (srl x, c) is known to be zero, return 0
4400 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4401 APInt::getAllOnesValue(OpSizeInBits)))
4402 return DAG.getConstant(0, VT);
4404 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4405 if (N1C && N0.getOpcode() == ISD::SRL) {
4406 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4407 uint64_t c1 = N01C->getZExtValue();
4408 uint64_t c2 = N1C->getZExtValue();
4409 if (c1 + c2 >= OpSizeInBits)
4410 return DAG.getConstant(0, VT);
4411 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4412 DAG.getConstant(c1 + c2, N1.getValueType()));
4416 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4417 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4418 N0.getOperand(0).getOpcode() == ISD::SRL &&
4419 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4421 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4422 uint64_t c2 = N1C->getZExtValue();
4423 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4424 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4425 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4426 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4427 if (c1 + OpSizeInBits == InnerShiftSize) {
4428 if (c1 + c2 >= InnerShiftSize)
4429 return DAG.getConstant(0, VT);
4430 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4431 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4432 N0.getOperand(0)->getOperand(0),
4433 DAG.getConstant(c1 + c2, ShiftCountVT)));
4437 // fold (srl (shl x, c), c) -> (and x, cst2)
4438 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4439 unsigned BitSize = N0.getScalarValueSizeInBits();
4440 if (BitSize <= 64) {
4441 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4442 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4443 DAG.getConstant(~0ULL >> ShAmt, VT));
4447 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4448 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4449 // Shifting in all undef bits?
4450 EVT SmallVT = N0.getOperand(0).getValueType();
4451 unsigned BitSize = SmallVT.getScalarSizeInBits();
4452 if (N1C->getZExtValue() >= BitSize)
4453 return DAG.getUNDEF(VT);
4455 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4456 uint64_t ShiftAmt = N1C->getZExtValue();
4457 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4459 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4460 AddToWorklist(SmallShift.getNode());
4461 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4462 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4463 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4464 DAG.getConstant(Mask, VT));
4468 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4469 // bit, which is unmodified by sra.
4470 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4471 if (N0.getOpcode() == ISD::SRA)
4472 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4475 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4476 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4477 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4478 APInt KnownZero, KnownOne;
4479 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4481 // If any of the input bits are KnownOne, then the input couldn't be all
4482 // zeros, thus the result of the srl will always be zero.
4483 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4485 // If all of the bits input the to ctlz node are known to be zero, then
4486 // the result of the ctlz is "32" and the result of the shift is one.
4487 APInt UnknownBits = ~KnownZero;
4488 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4490 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4491 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4492 // Okay, we know that only that the single bit specified by UnknownBits
4493 // could be set on input to the CTLZ node. If this bit is set, the SRL
4494 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4495 // to an SRL/XOR pair, which is likely to simplify more.
4496 unsigned ShAmt = UnknownBits.countTrailingZeros();
4497 SDValue Op = N0.getOperand(0);
4500 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4501 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4502 AddToWorklist(Op.getNode());
4505 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4506 Op, DAG.getConstant(1, VT));
4510 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4511 if (N1.getOpcode() == ISD::TRUNCATE &&
4512 N1.getOperand(0).getOpcode() == ISD::AND) {
4513 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4514 if (NewOp1.getNode())
4515 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4518 // fold operands of srl based on knowledge that the low bits are not
4520 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4521 return SDValue(N, 0);
4524 SDValue NewSRL = visitShiftByConstant(N, N1C);
4525 if (NewSRL.getNode())
4529 // Attempt to convert a srl of a load into a narrower zero-extending load.
4530 SDValue NarrowLoad = ReduceLoadWidth(N);
4531 if (NarrowLoad.getNode())
4534 // Here is a common situation. We want to optimize:
4537 // %b = and i32 %a, 2
4538 // %c = srl i32 %b, 1
4539 // brcond i32 %c ...
4545 // %c = setcc eq %b, 0
4548 // However when after the source operand of SRL is optimized into AND, the SRL
4549 // itself may not be optimized further. Look for it and add the BRCOND into
4551 if (N->hasOneUse()) {
4552 SDNode *Use = *N->use_begin();
4553 if (Use->getOpcode() == ISD::BRCOND)
4555 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4556 // Also look pass the truncate.
4557 Use = *Use->use_begin();
4558 if (Use->getOpcode() == ISD::BRCOND)
4566 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4567 SDValue N0 = N->getOperand(0);
4568 EVT VT = N->getValueType(0);
4570 // fold (ctlz c1) -> c2
4571 if (isa<ConstantSDNode>(N0))
4572 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4576 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4577 SDValue N0 = N->getOperand(0);
4578 EVT VT = N->getValueType(0);
4580 // fold (ctlz_zero_undef c1) -> c2
4581 if (isa<ConstantSDNode>(N0))
4582 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4586 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4587 SDValue N0 = N->getOperand(0);
4588 EVT VT = N->getValueType(0);
4590 // fold (cttz c1) -> c2
4591 if (isa<ConstantSDNode>(N0))
4592 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4596 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4597 SDValue N0 = N->getOperand(0);
4598 EVT VT = N->getValueType(0);
4600 // fold (cttz_zero_undef c1) -> c2
4601 if (isa<ConstantSDNode>(N0))
4602 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4606 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4607 SDValue N0 = N->getOperand(0);
4608 EVT VT = N->getValueType(0);
4610 // fold (ctpop c1) -> c2
4611 if (isa<ConstantSDNode>(N0))
4612 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4617 /// \brief Generate Min/Max node
4618 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4619 SDValue True, SDValue False,
4620 ISD::CondCode CC, const TargetLowering &TLI,
4621 SelectionDAG &DAG) {
4622 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4632 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4633 if (TLI.isOperationLegal(Opcode, VT))
4634 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4643 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4644 if (TLI.isOperationLegal(Opcode, VT))
4645 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4653 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4654 SDValue N0 = N->getOperand(0);
4655 SDValue N1 = N->getOperand(1);
4656 SDValue N2 = N->getOperand(2);
4657 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4658 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4659 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4660 EVT VT = N->getValueType(0);
4661 EVT VT0 = N0.getValueType();
4663 // fold (select C, X, X) -> X
4666 // fold (select true, X, Y) -> X
4667 if (N0C && !N0C->isNullValue())
4669 // fold (select false, X, Y) -> Y
4670 if (N0C && N0C->isNullValue())
4672 // fold (select C, 1, X) -> (or C, X)
4673 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4674 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4675 // fold (select C, 0, 1) -> (xor C, 1)
4676 // We can't do this reliably if integer based booleans have different contents
4677 // to floating point based booleans. This is because we can't tell whether we
4678 // have an integer-based boolean or a floating-point-based boolean unless we
4679 // can find the SETCC that produced it and inspect its operands. This is
4680 // fairly easy if C is the SETCC node, but it can potentially be
4681 // undiscoverable (or not reasonably discoverable). For example, it could be
4682 // in another basic block or it could require searching a complicated
4684 if (VT.isInteger() &&
4685 (VT0 == MVT::i1 || (VT0.isInteger() &&
4686 TLI.getBooleanContents(false, false) ==
4687 TLI.getBooleanContents(false, true) &&
4688 TLI.getBooleanContents(false, false) ==
4689 TargetLowering::ZeroOrOneBooleanContent)) &&
4690 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4693 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4694 N0, DAG.getConstant(1, VT0));
4695 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4696 N0, DAG.getConstant(1, VT0));
4697 AddToWorklist(XORNode.getNode());
4699 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4700 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4702 // fold (select C, 0, X) -> (and (not C), X)
4703 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4704 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4705 AddToWorklist(NOTNode.getNode());
4706 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4708 // fold (select C, X, 1) -> (or (not C), X)
4709 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4710 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4711 AddToWorklist(NOTNode.getNode());
4712 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4714 // fold (select C, X, 0) -> (and C, X)
4715 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4716 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4717 // fold (select X, X, Y) -> (or X, Y)
4718 // fold (select X, 1, Y) -> (or X, Y)
4719 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4720 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4721 // fold (select X, Y, X) -> (and X, Y)
4722 // fold (select X, Y, 0) -> (and X, Y)
4723 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4724 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4726 // If we can fold this based on the true/false value, do so.
4727 if (SimplifySelectOps(N, N1, N2))
4728 return SDValue(N, 0); // Don't revisit N.
4730 // fold selects based on a setcc into other things, such as min/max/abs
4731 if (N0.getOpcode() == ISD::SETCC) {
4732 // select x, y (fcmp lt x, y) -> fminnum x, y
4733 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4735 // This is OK if we don't care about what happens if either operand is a
4739 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4740 // no signed zeros as well as no nans.
4741 const TargetOptions &Options = DAG.getTarget().Options;
4742 if (Options.UnsafeFPMath &&
4743 VT.isFloatingPoint() && N0.hasOneUse() &&
4744 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4745 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4748 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4749 N1, N2, CC, TLI, DAG);
4754 if ((!LegalOperations &&
4755 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4756 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4757 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4758 N0.getOperand(0), N0.getOperand(1),
4759 N1, N2, N0.getOperand(2));
4760 return SimplifySelect(SDLoc(N), N0, N1, N2);
4767 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4770 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4772 // Split the inputs.
4773 SDValue Lo, Hi, LL, LH, RL, RH;
4774 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4775 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4777 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4778 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4780 return std::make_pair(Lo, Hi);
4783 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4784 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4785 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4787 SDValue Cond = N->getOperand(0);
4788 SDValue LHS = N->getOperand(1);
4789 SDValue RHS = N->getOperand(2);
4790 EVT VT = N->getValueType(0);
4791 int NumElems = VT.getVectorNumElements();
4792 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4793 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4794 Cond.getOpcode() == ISD::BUILD_VECTOR);
4796 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4797 // binary ones here.
4798 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4801 // We're sure we have an even number of elements due to the
4802 // concat_vectors we have as arguments to vselect.
4803 // Skip BV elements until we find one that's not an UNDEF
4804 // After we find an UNDEF element, keep looping until we get to half the
4805 // length of the BV and see if all the non-undef nodes are the same.
4806 ConstantSDNode *BottomHalf = nullptr;
4807 for (int i = 0; i < NumElems / 2; ++i) {
4808 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4811 if (BottomHalf == nullptr)
4812 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4813 else if (Cond->getOperand(i).getNode() != BottomHalf)
4817 // Do the same for the second half of the BuildVector
4818 ConstantSDNode *TopHalf = nullptr;
4819 for (int i = NumElems / 2; i < NumElems; ++i) {
4820 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4823 if (TopHalf == nullptr)
4824 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4825 else if (Cond->getOperand(i).getNode() != TopHalf)
4829 assert(TopHalf && BottomHalf &&
4830 "One half of the selector was all UNDEFs and the other was all the "
4831 "same value. This should have been addressed before this function.");
4833 ISD::CONCAT_VECTORS, dl, VT,
4834 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4835 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4838 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4840 if (Level >= AfterLegalizeTypes)
4843 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4844 SDValue Mask = MST->getMask();
4845 SDValue Data = MST->getData();
4848 // If the MSTORE data type requires splitting and the mask is provided by a
4849 // SETCC, then split both nodes and its operands before legalization. This
4850 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4851 // and enables future optimizations (e.g. min/max pattern matching on X86).
4852 if (Mask.getOpcode() == ISD::SETCC) {
4854 // Check if any splitting is required.
4855 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4856 TargetLowering::TypeSplitVector)
4859 SDValue MaskLo, MaskHi, Lo, Hi;
4860 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4863 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4865 SDValue Chain = MST->getChain();
4866 SDValue Ptr = MST->getBasePtr();
4868 EVT MemoryVT = MST->getMemoryVT();
4869 unsigned Alignment = MST->getOriginalAlignment();
4871 // if Alignment is equal to the vector size,
4872 // take the half of it for the second part
4873 unsigned SecondHalfAlignment =
4874 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4875 Alignment/2 : Alignment;
4877 EVT LoMemVT, HiMemVT;
4878 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4880 SDValue DataLo, DataHi;
4881 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4883 MachineMemOperand *MMO = DAG.getMachineFunction().
4884 getMachineMemOperand(MST->getPointerInfo(),
4885 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
4886 Alignment, MST->getAAInfo(), MST->getRanges());
4888 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4890 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4891 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4892 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4894 MMO = DAG.getMachineFunction().
4895 getMachineMemOperand(MST->getPointerInfo(),
4896 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
4897 SecondHalfAlignment, MST->getAAInfo(),
4900 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4902 AddToWorklist(Lo.getNode());
4903 AddToWorklist(Hi.getNode());
4905 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4910 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4912 if (Level >= AfterLegalizeTypes)
4915 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4916 SDValue Mask = MLD->getMask();
4919 // If the MLOAD result requires splitting and the mask is provided by a
4920 // SETCC, then split both nodes and its operands before legalization. This
4921 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4922 // and enables future optimizations (e.g. min/max pattern matching on X86).
4924 if (Mask.getOpcode() == ISD::SETCC) {
4925 EVT VT = N->getValueType(0);
4927 // Check if any splitting is required.
4928 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4929 TargetLowering::TypeSplitVector)
4932 SDValue MaskLo, MaskHi, Lo, Hi;
4933 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4935 SDValue Src0 = MLD->getSrc0();
4936 SDValue Src0Lo, Src0Hi;
4937 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4940 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4942 SDValue Chain = MLD->getChain();
4943 SDValue Ptr = MLD->getBasePtr();
4944 EVT MemoryVT = MLD->getMemoryVT();
4945 unsigned Alignment = MLD->getOriginalAlignment();
4947 // if Alignment is equal to the vector size,
4948 // take the half of it for the second part
4949 unsigned SecondHalfAlignment =
4950 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4951 Alignment/2 : Alignment;
4953 EVT LoMemVT, HiMemVT;
4954 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4956 MachineMemOperand *MMO = DAG.getMachineFunction().
4957 getMachineMemOperand(MLD->getPointerInfo(),
4958 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
4959 Alignment, MLD->getAAInfo(), MLD->getRanges());
4961 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4963 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4964 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4965 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4967 MMO = DAG.getMachineFunction().
4968 getMachineMemOperand(MLD->getPointerInfo(),
4969 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
4970 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4972 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4974 AddToWorklist(Lo.getNode());
4975 AddToWorklist(Hi.getNode());
4977 // Build a factor node to remember that this load is independent of the
4979 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4982 // Legalized the chain result - switch anything that used the old chain to
4984 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4986 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4988 SDValue RetOps[] = { LoadRes, Chain };
4989 return DAG.getMergeValues(RetOps, DL);
4994 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4995 SDValue N0 = N->getOperand(0);
4996 SDValue N1 = N->getOperand(1);
4997 SDValue N2 = N->getOperand(2);
5000 // Canonicalize integer abs.
5001 // vselect (setg[te] X, 0), X, -X ->
5002 // vselect (setgt X, -1), X, -X ->
5003 // vselect (setl[te] X, 0), -X, X ->
5004 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5005 if (N0.getOpcode() == ISD::SETCC) {
5006 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5007 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5009 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5011 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5012 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5013 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5014 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5015 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5016 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5017 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5020 EVT VT = LHS.getValueType();
5021 SDValue Shift = DAG.getNode(
5022 ISD::SRA, DL, VT, LHS,
5023 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5024 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5025 AddToWorklist(Shift.getNode());
5026 AddToWorklist(Add.getNode());
5027 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5031 // If the VSELECT result requires splitting and the mask is provided by a
5032 // SETCC, then split both nodes and its operands before legalization. This
5033 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5034 // and enables future optimizations (e.g. min/max pattern matching on X86).
5035 if (N0.getOpcode() == ISD::SETCC) {
5036 EVT VT = N->getValueType(0);
5038 // Check if any splitting is required.
5039 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5040 TargetLowering::TypeSplitVector)
5043 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5044 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5045 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5046 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5048 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5049 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5051 // Add the new VSELECT nodes to the work list in case they need to be split
5053 AddToWorklist(Lo.getNode());
5054 AddToWorklist(Hi.getNode());
5056 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5059 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5060 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5062 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5063 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5066 // The ConvertSelectToConcatVector function is assuming both the above
5067 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5069 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5070 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5071 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5072 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5080 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5081 SDValue N0 = N->getOperand(0);
5082 SDValue N1 = N->getOperand(1);
5083 SDValue N2 = N->getOperand(2);
5084 SDValue N3 = N->getOperand(3);
5085 SDValue N4 = N->getOperand(4);
5086 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5088 // fold select_cc lhs, rhs, x, x, cc -> x
5092 // Determine if the condition we're dealing with is constant
5093 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5094 N0, N1, CC, SDLoc(N), false);
5095 if (SCC.getNode()) {
5096 AddToWorklist(SCC.getNode());
5098 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5099 if (!SCCC->isNullValue())
5100 return N2; // cond always true -> true val
5102 return N3; // cond always false -> false val
5103 } else if (SCC->getOpcode() == ISD::UNDEF) {
5104 // When the condition is UNDEF, just return the first operand. This is
5105 // coherent the DAG creation, no setcc node is created in this case
5107 } else if (SCC.getOpcode() == ISD::SETCC) {
5108 // Fold to a simpler select_cc
5109 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5110 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5115 // If we can fold this based on the true/false value, do so.
5116 if (SimplifySelectOps(N, N2, N3))
5117 return SDValue(N, 0); // Don't revisit N.
5119 // fold select_cc into other things, such as min/max/abs
5120 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5123 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5124 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5125 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5129 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5130 // dag node into a ConstantSDNode or a build_vector of constants.
5131 // This function is called by the DAGCombiner when visiting sext/zext/aext
5132 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5133 // Vector extends are not folded if operations are legal; this is to
5134 // avoid introducing illegal build_vector dag nodes.
5135 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5136 SelectionDAG &DAG, bool LegalTypes,
5137 bool LegalOperations) {
5138 unsigned Opcode = N->getOpcode();
5139 SDValue N0 = N->getOperand(0);
5140 EVT VT = N->getValueType(0);
5142 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5143 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5145 // fold (sext c1) -> c1
5146 // fold (zext c1) -> c1
5147 // fold (aext c1) -> c1
5148 if (isa<ConstantSDNode>(N0))
5149 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5151 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5152 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5153 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5154 EVT SVT = VT.getScalarType();
5155 if (!(VT.isVector() &&
5156 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5157 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5160 // We can fold this node into a build_vector.
5161 unsigned VTBits = SVT.getSizeInBits();
5162 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5163 unsigned ShAmt = VTBits - EVTBits;
5164 SmallVector<SDValue, 8> Elts;
5165 unsigned NumElts = N0->getNumOperands();
5168 for (unsigned i=0; i != NumElts; ++i) {
5169 SDValue Op = N0->getOperand(i);
5170 if (Op->getOpcode() == ISD::UNDEF) {
5171 Elts.push_back(DAG.getUNDEF(SVT));
5175 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5176 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5177 if (Opcode == ISD::SIGN_EXTEND)
5178 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5181 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5185 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5188 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5189 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5190 // transformation. Returns true if extension are possible and the above
5191 // mentioned transformation is profitable.
5192 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5194 SmallVectorImpl<SDNode *> &ExtendNodes,
5195 const TargetLowering &TLI) {
5196 bool HasCopyToRegUses = false;
5197 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5198 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5199 UE = N0.getNode()->use_end();
5204 if (UI.getUse().getResNo() != N0.getResNo())
5206 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5207 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5208 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5209 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5210 // Sign bits will be lost after a zext.
5213 for (unsigned i = 0; i != 2; ++i) {
5214 SDValue UseOp = User->getOperand(i);
5217 if (!isa<ConstantSDNode>(UseOp))
5222 ExtendNodes.push_back(User);
5225 // If truncates aren't free and there are users we can't
5226 // extend, it isn't worthwhile.
5229 // Remember if this value is live-out.
5230 if (User->getOpcode() == ISD::CopyToReg)
5231 HasCopyToRegUses = true;
5234 if (HasCopyToRegUses) {
5235 bool BothLiveOut = false;
5236 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5238 SDUse &Use = UI.getUse();
5239 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5245 // Both unextended and extended values are live out. There had better be
5246 // a good reason for the transformation.
5247 return ExtendNodes.size();
5252 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5253 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5254 ISD::NodeType ExtType) {
5255 // Extend SetCC uses if necessary.
5256 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5257 SDNode *SetCC = SetCCs[i];
5258 SmallVector<SDValue, 4> Ops;
5260 for (unsigned j = 0; j != 2; ++j) {
5261 SDValue SOp = SetCC->getOperand(j);
5263 Ops.push_back(ExtLoad);
5265 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5268 Ops.push_back(SetCC->getOperand(2));
5269 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5273 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5274 SDValue N0 = N->getOperand(0);
5275 EVT VT = N->getValueType(0);
5277 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5279 return SDValue(Res, 0);
5281 // fold (sext (sext x)) -> (sext x)
5282 // fold (sext (aext x)) -> (sext x)
5283 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5284 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5287 if (N0.getOpcode() == ISD::TRUNCATE) {
5288 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5289 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5290 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5291 if (NarrowLoad.getNode()) {
5292 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5293 if (NarrowLoad.getNode() != N0.getNode()) {
5294 CombineTo(N0.getNode(), NarrowLoad);
5295 // CombineTo deleted the truncate, if needed, but not what's under it.
5298 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5301 // See if the value being truncated is already sign extended. If so, just
5302 // eliminate the trunc/sext pair.
5303 SDValue Op = N0.getOperand(0);
5304 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5305 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5306 unsigned DestBits = VT.getScalarType().getSizeInBits();
5307 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5309 if (OpBits == DestBits) {
5310 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5311 // bits, it is already ready.
5312 if (NumSignBits > DestBits-MidBits)
5314 } else if (OpBits < DestBits) {
5315 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5316 // bits, just sext from i32.
5317 if (NumSignBits > OpBits-MidBits)
5318 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5320 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5321 // bits, just truncate to i32.
5322 if (NumSignBits > OpBits-MidBits)
5323 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5326 // fold (sext (truncate x)) -> (sextinreg x).
5327 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5328 N0.getValueType())) {
5329 if (OpBits < DestBits)
5330 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5331 else if (OpBits > DestBits)
5332 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5333 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5334 DAG.getValueType(N0.getValueType()));
5338 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5339 // None of the supported targets knows how to perform load and sign extend
5340 // on vectors in one instruction. We only perform this transformation on
5342 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5343 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5344 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5345 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5346 bool DoXform = true;
5347 SmallVector<SDNode*, 4> SetCCs;
5348 if (!N0.hasOneUse())
5349 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5351 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5352 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5354 LN0->getBasePtr(), N0.getValueType(),
5355 LN0->getMemOperand());
5356 CombineTo(N, ExtLoad);
5357 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5358 N0.getValueType(), ExtLoad);
5359 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5360 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5362 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5366 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5367 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5368 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5369 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5370 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5371 EVT MemVT = LN0->getMemoryVT();
5372 if ((!LegalOperations && !LN0->isVolatile()) ||
5373 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5374 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5376 LN0->getBasePtr(), MemVT,
5377 LN0->getMemOperand());
5378 CombineTo(N, ExtLoad);
5379 CombineTo(N0.getNode(),
5380 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5381 N0.getValueType(), ExtLoad),
5382 ExtLoad.getValue(1));
5383 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5387 // fold (sext (and/or/xor (load x), cst)) ->
5388 // (and/or/xor (sextload x), (sext cst))
5389 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5390 N0.getOpcode() == ISD::XOR) &&
5391 isa<LoadSDNode>(N0.getOperand(0)) &&
5392 N0.getOperand(1).getOpcode() == ISD::Constant &&
5393 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5394 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5395 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5396 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5397 bool DoXform = true;
5398 SmallVector<SDNode*, 4> SetCCs;
5399 if (!N0.hasOneUse())
5400 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5403 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5404 LN0->getChain(), LN0->getBasePtr(),
5406 LN0->getMemOperand());
5407 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5408 Mask = Mask.sext(VT.getSizeInBits());
5409 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5410 ExtLoad, DAG.getConstant(Mask, VT));
5411 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5412 SDLoc(N0.getOperand(0)),
5413 N0.getOperand(0).getValueType(), ExtLoad);
5415 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5416 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5418 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5423 if (N0.getOpcode() == ISD::SETCC) {
5424 EVT N0VT = N0.getOperand(0).getValueType();
5425 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5426 // Only do this before legalize for now.
5427 if (VT.isVector() && !LegalOperations &&
5428 TLI.getBooleanContents(N0VT) ==
5429 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5430 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5431 // of the same size as the compared operands. Only optimize sext(setcc())
5432 // if this is the case.
5433 EVT SVT = getSetCCResultType(N0VT);
5435 // We know that the # elements of the results is the same as the
5436 // # elements of the compare (and the # elements of the compare result
5437 // for that matter). Check to see that they are the same size. If so,
5438 // we know that the element size of the sext'd result matches the
5439 // element size of the compare operands.
5440 if (VT.getSizeInBits() == SVT.getSizeInBits())
5441 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5443 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5445 // If the desired elements are smaller or larger than the source
5446 // elements we can use a matching integer vector type and then
5447 // truncate/sign extend
5448 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5449 if (SVT == MatchingVectorType) {
5450 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5451 N0.getOperand(0), N0.getOperand(1),
5452 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5453 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5457 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5458 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5460 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5462 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5463 NegOne, DAG.getConstant(0, VT),
5464 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5465 if (SCC.getNode()) return SCC;
5467 if (!VT.isVector()) {
5468 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5469 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5471 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5472 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5473 N0.getOperand(0), N0.getOperand(1), CC);
5474 return DAG.getSelect(DL, VT, SetCC,
5475 NegOne, DAG.getConstant(0, VT));
5480 // fold (sext x) -> (zext x) if the sign bit is known zero.
5481 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5482 DAG.SignBitIsZero(N0))
5483 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5488 // isTruncateOf - If N is a truncate of some other value, return true, record
5489 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5490 // This function computes KnownZero to avoid a duplicated call to
5491 // computeKnownBits in the caller.
5492 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5495 if (N->getOpcode() == ISD::TRUNCATE) {
5496 Op = N->getOperand(0);
5497 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5501 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5502 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5505 SDValue Op0 = N->getOperand(0);
5506 SDValue Op1 = N->getOperand(1);
5507 assert(Op0.getValueType() == Op1.getValueType());
5509 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5510 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5511 if (COp0 && COp0->isNullValue())
5513 else if (COp1 && COp1->isNullValue())
5518 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5520 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5526 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5527 SDValue N0 = N->getOperand(0);
5528 EVT VT = N->getValueType(0);
5530 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5532 return SDValue(Res, 0);
5534 // fold (zext (zext x)) -> (zext x)
5535 // fold (zext (aext x)) -> (zext x)
5536 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5537 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5540 // fold (zext (truncate x)) -> (zext x) or
5541 // (zext (truncate x)) -> (truncate x)
5542 // This is valid when the truncated bits of x are already zero.
5543 // FIXME: We should extend this to work for vectors too.
5546 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5547 APInt TruncatedBits =
5548 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5549 APInt(Op.getValueSizeInBits(), 0) :
5550 APInt::getBitsSet(Op.getValueSizeInBits(),
5551 N0.getValueSizeInBits(),
5552 std::min(Op.getValueSizeInBits(),
5553 VT.getSizeInBits()));
5554 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5555 if (VT.bitsGT(Op.getValueType()))
5556 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5557 if (VT.bitsLT(Op.getValueType()))
5558 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5564 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5565 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5566 if (N0.getOpcode() == ISD::TRUNCATE) {
5567 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5568 if (NarrowLoad.getNode()) {
5569 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5570 if (NarrowLoad.getNode() != N0.getNode()) {
5571 CombineTo(N0.getNode(), NarrowLoad);
5572 // CombineTo deleted the truncate, if needed, but not what's under it.
5575 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5579 // fold (zext (truncate x)) -> (and x, mask)
5580 if (N0.getOpcode() == ISD::TRUNCATE &&
5581 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5583 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5584 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5585 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5586 if (NarrowLoad.getNode()) {
5587 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5588 if (NarrowLoad.getNode() != N0.getNode()) {
5589 CombineTo(N0.getNode(), NarrowLoad);
5590 // CombineTo deleted the truncate, if needed, but not what's under it.
5593 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5596 SDValue Op = N0.getOperand(0);
5597 if (Op.getValueType().bitsLT(VT)) {
5598 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5599 AddToWorklist(Op.getNode());
5600 } else if (Op.getValueType().bitsGT(VT)) {
5601 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5602 AddToWorklist(Op.getNode());
5604 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5605 N0.getValueType().getScalarType());
5608 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5609 // if either of the casts is not free.
5610 if (N0.getOpcode() == ISD::AND &&
5611 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5612 N0.getOperand(1).getOpcode() == ISD::Constant &&
5613 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5614 N0.getValueType()) ||
5615 !TLI.isZExtFree(N0.getValueType(), VT))) {
5616 SDValue X = N0.getOperand(0).getOperand(0);
5617 if (X.getValueType().bitsLT(VT)) {
5618 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5619 } else if (X.getValueType().bitsGT(VT)) {
5620 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5622 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5623 Mask = Mask.zext(VT.getSizeInBits());
5624 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5625 X, DAG.getConstant(Mask, VT));
5628 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5629 // None of the supported targets knows how to perform load and vector_zext
5630 // on vectors in one instruction. We only perform this transformation on
5632 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5633 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5634 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5635 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5636 bool DoXform = true;
5637 SmallVector<SDNode*, 4> SetCCs;
5638 if (!N0.hasOneUse())
5639 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5641 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5642 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5644 LN0->getBasePtr(), N0.getValueType(),
5645 LN0->getMemOperand());
5646 CombineTo(N, ExtLoad);
5647 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5648 N0.getValueType(), ExtLoad);
5649 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5651 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5653 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5657 // fold (zext (and/or/xor (load x), cst)) ->
5658 // (and/or/xor (zextload x), (zext cst))
5659 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5660 N0.getOpcode() == ISD::XOR) &&
5661 isa<LoadSDNode>(N0.getOperand(0)) &&
5662 N0.getOperand(1).getOpcode() == ISD::Constant &&
5663 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5664 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5665 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5666 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5667 bool DoXform = true;
5668 SmallVector<SDNode*, 4> SetCCs;
5669 if (!N0.hasOneUse())
5670 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5673 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5674 LN0->getChain(), LN0->getBasePtr(),
5676 LN0->getMemOperand());
5677 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5678 Mask = Mask.zext(VT.getSizeInBits());
5679 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5680 ExtLoad, DAG.getConstant(Mask, VT));
5681 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5682 SDLoc(N0.getOperand(0)),
5683 N0.getOperand(0).getValueType(), ExtLoad);
5685 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5686 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5688 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5693 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5694 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5695 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5696 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5697 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5698 EVT MemVT = LN0->getMemoryVT();
5699 if ((!LegalOperations && !LN0->isVolatile()) ||
5700 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5701 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5703 LN0->getBasePtr(), MemVT,
5704 LN0->getMemOperand());
5705 CombineTo(N, ExtLoad);
5706 CombineTo(N0.getNode(),
5707 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5709 ExtLoad.getValue(1));
5710 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5714 if (N0.getOpcode() == ISD::SETCC) {
5715 if (!LegalOperations && VT.isVector() &&
5716 N0.getValueType().getVectorElementType() == MVT::i1) {
5717 EVT N0VT = N0.getOperand(0).getValueType();
5718 if (getSetCCResultType(N0VT) == N0.getValueType())
5721 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5722 // Only do this before legalize for now.
5723 EVT EltVT = VT.getVectorElementType();
5724 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5725 DAG.getConstant(1, EltVT));
5726 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5727 // We know that the # elements of the results is the same as the
5728 // # elements of the compare (and the # elements of the compare result
5729 // for that matter). Check to see that they are the same size. If so,
5730 // we know that the element size of the sext'd result matches the
5731 // element size of the compare operands.
5732 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5733 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5735 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5736 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5739 // If the desired elements are smaller or larger than the source
5740 // elements we can use a matching integer vector type and then
5741 // truncate/sign extend
5742 EVT MatchingElementType =
5743 EVT::getIntegerVT(*DAG.getContext(),
5744 N0VT.getScalarType().getSizeInBits());
5745 EVT MatchingVectorType =
5746 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5747 N0VT.getVectorNumElements());
5749 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5751 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5752 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5753 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5754 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5757 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5759 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5760 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5761 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5762 if (SCC.getNode()) return SCC;
5765 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5766 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5767 isa<ConstantSDNode>(N0.getOperand(1)) &&
5768 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5770 SDValue ShAmt = N0.getOperand(1);
5771 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5772 if (N0.getOpcode() == ISD::SHL) {
5773 SDValue InnerZExt = N0.getOperand(0);
5774 // If the original shl may be shifting out bits, do not perform this
5776 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5777 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5778 if (ShAmtVal > KnownZeroBits)
5784 // Ensure that the shift amount is wide enough for the shifted value.
5785 if (VT.getSizeInBits() >= 256)
5786 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5788 return DAG.getNode(N0.getOpcode(), DL, VT,
5789 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5796 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5797 SDValue N0 = N->getOperand(0);
5798 EVT VT = N->getValueType(0);
5800 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5802 return SDValue(Res, 0);
5804 // fold (aext (aext x)) -> (aext x)
5805 // fold (aext (zext x)) -> (zext x)
5806 // fold (aext (sext x)) -> (sext x)
5807 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5808 N0.getOpcode() == ISD::ZERO_EXTEND ||
5809 N0.getOpcode() == ISD::SIGN_EXTEND)
5810 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5812 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5813 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5814 if (N0.getOpcode() == ISD::TRUNCATE) {
5815 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5816 if (NarrowLoad.getNode()) {
5817 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5818 if (NarrowLoad.getNode() != N0.getNode()) {
5819 CombineTo(N0.getNode(), NarrowLoad);
5820 // CombineTo deleted the truncate, if needed, but not what's under it.
5823 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5827 // fold (aext (truncate x))
5828 if (N0.getOpcode() == ISD::TRUNCATE) {
5829 SDValue TruncOp = N0.getOperand(0);
5830 if (TruncOp.getValueType() == VT)
5831 return TruncOp; // x iff x size == zext size.
5832 if (TruncOp.getValueType().bitsGT(VT))
5833 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5834 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5837 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5838 // if the trunc is not free.
5839 if (N0.getOpcode() == ISD::AND &&
5840 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5841 N0.getOperand(1).getOpcode() == ISD::Constant &&
5842 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5843 N0.getValueType())) {
5844 SDValue X = N0.getOperand(0).getOperand(0);
5845 if (X.getValueType().bitsLT(VT)) {
5846 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5847 } else if (X.getValueType().bitsGT(VT)) {
5848 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5850 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5851 Mask = Mask.zext(VT.getSizeInBits());
5852 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5853 X, DAG.getConstant(Mask, VT));
5856 // fold (aext (load x)) -> (aext (truncate (extload x)))
5857 // None of the supported targets knows how to perform load and any_ext
5858 // on vectors in one instruction. We only perform this transformation on
5860 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5861 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5862 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
5863 bool DoXform = true;
5864 SmallVector<SDNode*, 4> SetCCs;
5865 if (!N0.hasOneUse())
5866 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5868 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5869 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5871 LN0->getBasePtr(), N0.getValueType(),
5872 LN0->getMemOperand());
5873 CombineTo(N, ExtLoad);
5874 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5875 N0.getValueType(), ExtLoad);
5876 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5877 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5879 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5883 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5884 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5885 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5886 if (N0.getOpcode() == ISD::LOAD &&
5887 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5889 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5890 ISD::LoadExtType ExtType = LN0->getExtensionType();
5891 EVT MemVT = LN0->getMemoryVT();
5892 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
5893 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5894 VT, LN0->getChain(), LN0->getBasePtr(),
5895 MemVT, LN0->getMemOperand());
5896 CombineTo(N, ExtLoad);
5897 CombineTo(N0.getNode(),
5898 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5899 N0.getValueType(), ExtLoad),
5900 ExtLoad.getValue(1));
5901 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5905 if (N0.getOpcode() == ISD::SETCC) {
5907 // aext(setcc) -> vsetcc
5908 // aext(setcc) -> truncate(vsetcc)
5909 // aext(setcc) -> aext(vsetcc)
5910 // Only do this before legalize for now.
5911 if (VT.isVector() && !LegalOperations) {
5912 EVT N0VT = N0.getOperand(0).getValueType();
5913 // We know that the # elements of the results is the same as the
5914 // # elements of the compare (and the # elements of the compare result
5915 // for that matter). Check to see that they are the same size. If so,
5916 // we know that the element size of the sext'd result matches the
5917 // element size of the compare operands.
5918 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5919 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5921 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5922 // If the desired elements are smaller or larger than the source
5923 // elements we can use a matching integer vector type and then
5924 // truncate/any extend
5926 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5928 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5930 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5931 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5935 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5937 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5938 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5939 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5947 /// See if the specified operand can be simplified with the knowledge that only
5948 /// the bits specified by Mask are used. If so, return the simpler operand,
5949 /// otherwise return a null SDValue.
5950 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5951 switch (V.getOpcode()) {
5953 case ISD::Constant: {
5954 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5955 assert(CV && "Const value should be ConstSDNode.");
5956 const APInt &CVal = CV->getAPIntValue();
5957 APInt NewVal = CVal & Mask;
5959 return DAG.getConstant(NewVal, V.getValueType());
5964 // If the LHS or RHS don't contribute bits to the or, drop them.
5965 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5966 return V.getOperand(1);
5967 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5968 return V.getOperand(0);
5971 // Only look at single-use SRLs.
5972 if (!V.getNode()->hasOneUse())
5974 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5975 // See if we can recursively simplify the LHS.
5976 unsigned Amt = RHSC->getZExtValue();
5978 // Watch out for shift count overflow though.
5979 if (Amt >= Mask.getBitWidth()) break;
5980 APInt NewMask = Mask << Amt;
5981 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5982 if (SimplifyLHS.getNode())
5983 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5984 SimplifyLHS, V.getOperand(1));
5990 /// If the result of a wider load is shifted to right of N bits and then
5991 /// truncated to a narrower type and where N is a multiple of number of bits of
5992 /// the narrower type, transform it to a narrower load from address + N / num of
5993 /// bits of new type. If the result is to be extended, also fold the extension
5994 /// to form a extending load.
5995 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5996 unsigned Opc = N->getOpcode();
5998 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5999 SDValue N0 = N->getOperand(0);
6000 EVT VT = N->getValueType(0);
6003 // This transformation isn't valid for vector loads.
6007 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6009 if (Opc == ISD::SIGN_EXTEND_INREG) {
6010 ExtType = ISD::SEXTLOAD;
6011 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6012 } else if (Opc == ISD::SRL) {
6013 // Another special-case: SRL is basically zero-extending a narrower value.
6014 ExtType = ISD::ZEXTLOAD;
6016 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6017 if (!N01) return SDValue();
6018 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6019 VT.getSizeInBits() - N01->getZExtValue());
6021 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6024 unsigned EVTBits = ExtVT.getSizeInBits();
6026 // Do not generate loads of non-round integer types since these can
6027 // be expensive (and would be wrong if the type is not byte sized).
6028 if (!ExtVT.isRound())
6032 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6033 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6034 ShAmt = N01->getZExtValue();
6035 // Is the shift amount a multiple of size of VT?
6036 if ((ShAmt & (EVTBits-1)) == 0) {
6037 N0 = N0.getOperand(0);
6038 // Is the load width a multiple of size of VT?
6039 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6043 // At this point, we must have a load or else we can't do the transform.
6044 if (!isa<LoadSDNode>(N0)) return SDValue();
6046 // Because a SRL must be assumed to *need* to zero-extend the high bits
6047 // (as opposed to anyext the high bits), we can't combine the zextload
6048 // lowering of SRL and an sextload.
6049 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6052 // If the shift amount is larger than the input type then we're not
6053 // accessing any of the loaded bytes. If the load was a zextload/extload
6054 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6055 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6060 // If the load is shifted left (and the result isn't shifted back right),
6061 // we can fold the truncate through the shift.
6062 unsigned ShLeftAmt = 0;
6063 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6064 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6065 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6066 ShLeftAmt = N01->getZExtValue();
6067 N0 = N0.getOperand(0);
6071 // If we haven't found a load, we can't narrow it. Don't transform one with
6072 // multiple uses, this would require adding a new load.
6073 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6076 // Don't change the width of a volatile load.
6077 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6078 if (LN0->isVolatile())
6081 // Verify that we are actually reducing a load width here.
6082 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6085 // For the transform to be legal, the load must produce only two values
6086 // (the value loaded and the chain). Don't transform a pre-increment
6087 // load, for example, which produces an extra value. Otherwise the
6088 // transformation is not equivalent, and the downstream logic to replace
6089 // uses gets things wrong.
6090 if (LN0->getNumValues() > 2)
6093 // If the load that we're shrinking is an extload and we're not just
6094 // discarding the extension we can't simply shrink the load. Bail.
6095 // TODO: It would be possible to merge the extensions in some cases.
6096 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6097 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6100 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6103 EVT PtrType = N0.getOperand(1).getValueType();
6105 if (PtrType == MVT::Untyped || PtrType.isExtended())
6106 // It's not possible to generate a constant of extended or untyped type.
6109 // For big endian targets, we need to adjust the offset to the pointer to
6110 // load the correct bytes.
6111 if (TLI.isBigEndian()) {
6112 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6113 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6114 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6117 uint64_t PtrOff = ShAmt / 8;
6118 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6119 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6120 PtrType, LN0->getBasePtr(),
6121 DAG.getConstant(PtrOff, PtrType));
6122 AddToWorklist(NewPtr.getNode());
6125 if (ExtType == ISD::NON_EXTLOAD)
6126 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6127 LN0->getPointerInfo().getWithOffset(PtrOff),
6128 LN0->isVolatile(), LN0->isNonTemporal(),
6129 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6131 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6132 LN0->getPointerInfo().getWithOffset(PtrOff),
6133 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6134 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6136 // Replace the old load's chain with the new load's chain.
6137 WorklistRemover DeadNodes(*this);
6138 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6140 // Shift the result left, if we've swallowed a left shift.
6141 SDValue Result = Load;
6142 if (ShLeftAmt != 0) {
6143 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6144 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6146 // If the shift amount is as large as the result size (but, presumably,
6147 // no larger than the source) then the useful bits of the result are
6148 // zero; we can't simply return the shortened shift, because the result
6149 // of that operation is undefined.
6150 if (ShLeftAmt >= VT.getSizeInBits())
6151 Result = DAG.getConstant(0, VT);
6153 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6154 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6157 // Return the new loaded value.
6161 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6162 SDValue N0 = N->getOperand(0);
6163 SDValue N1 = N->getOperand(1);
6164 EVT VT = N->getValueType(0);
6165 EVT EVT = cast<VTSDNode>(N1)->getVT();
6166 unsigned VTBits = VT.getScalarType().getSizeInBits();
6167 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6169 // fold (sext_in_reg c1) -> c1
6170 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6171 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6173 // If the input is already sign extended, just drop the extension.
6174 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6177 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6178 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6179 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6180 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6181 N0.getOperand(0), N1);
6183 // fold (sext_in_reg (sext x)) -> (sext x)
6184 // fold (sext_in_reg (aext x)) -> (sext x)
6185 // if x is small enough.
6186 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6187 SDValue N00 = N0.getOperand(0);
6188 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6189 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6190 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6193 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6194 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6195 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6197 // fold operands of sext_in_reg based on knowledge that the top bits are not
6199 if (SimplifyDemandedBits(SDValue(N, 0)))
6200 return SDValue(N, 0);
6202 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6203 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6204 SDValue NarrowLoad = ReduceLoadWidth(N);
6205 if (NarrowLoad.getNode())
6208 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6209 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6210 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6211 if (N0.getOpcode() == ISD::SRL) {
6212 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6213 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6214 // We can turn this into an SRA iff the input to the SRL is already sign
6216 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6217 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6218 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6219 N0.getOperand(0), N0.getOperand(1));
6223 // fold (sext_inreg (extload x)) -> (sextload x)
6224 if (ISD::isEXTLoad(N0.getNode()) &&
6225 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6226 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6227 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6228 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6229 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6230 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6232 LN0->getBasePtr(), EVT,
6233 LN0->getMemOperand());
6234 CombineTo(N, ExtLoad);
6235 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6236 AddToWorklist(ExtLoad.getNode());
6237 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6239 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6240 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6242 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6243 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6244 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6245 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6246 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6248 LN0->getBasePtr(), EVT,
6249 LN0->getMemOperand());
6250 CombineTo(N, ExtLoad);
6251 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6252 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6255 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6256 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6257 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6258 N0.getOperand(1), false);
6259 if (BSwap.getNode())
6260 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6264 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6265 // into a build_vector.
6266 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6267 SmallVector<SDValue, 8> Elts;
6268 unsigned NumElts = N0->getNumOperands();
6269 unsigned ShAmt = VTBits - EVTBits;
6271 for (unsigned i = 0; i != NumElts; ++i) {
6272 SDValue Op = N0->getOperand(i);
6273 if (Op->getOpcode() == ISD::UNDEF) {
6278 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6279 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6280 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6281 Op.getValueType()));
6284 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6290 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6291 SDValue N0 = N->getOperand(0);
6292 EVT VT = N->getValueType(0);
6293 bool isLE = TLI.isLittleEndian();
6296 if (N0.getValueType() == N->getValueType(0))
6298 // fold (truncate c1) -> c1
6299 if (isa<ConstantSDNode>(N0))
6300 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6301 // fold (truncate (truncate x)) -> (truncate x)
6302 if (N0.getOpcode() == ISD::TRUNCATE)
6303 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6304 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6305 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6306 N0.getOpcode() == ISD::SIGN_EXTEND ||
6307 N0.getOpcode() == ISD::ANY_EXTEND) {
6308 if (N0.getOperand(0).getValueType().bitsLT(VT))
6309 // if the source is smaller than the dest, we still need an extend
6310 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6312 if (N0.getOperand(0).getValueType().bitsGT(VT))
6313 // if the source is larger than the dest, than we just need the truncate
6314 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6315 // if the source and dest are the same type, we can drop both the extend
6316 // and the truncate.
6317 return N0.getOperand(0);
6320 // Fold extract-and-trunc into a narrow extract. For example:
6321 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6322 // i32 y = TRUNCATE(i64 x)
6324 // v16i8 b = BITCAST (v2i64 val)
6325 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6327 // Note: We only run this optimization after type legalization (which often
6328 // creates this pattern) and before operation legalization after which
6329 // we need to be more careful about the vector instructions that we generate.
6330 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6331 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6333 EVT VecTy = N0.getOperand(0).getValueType();
6334 EVT ExTy = N0.getValueType();
6335 EVT TrTy = N->getValueType(0);
6337 unsigned NumElem = VecTy.getVectorNumElements();
6338 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6340 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6341 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6343 SDValue EltNo = N0->getOperand(1);
6344 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6345 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6346 EVT IndexTy = TLI.getVectorIdxTy();
6347 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6349 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6350 NVT, N0.getOperand(0));
6352 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6354 DAG.getConstant(Index, IndexTy));
6358 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6359 if (N0.getOpcode() == ISD::SELECT) {
6360 EVT SrcVT = N0.getValueType();
6361 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6362 TLI.isTruncateFree(SrcVT, VT)) {
6364 SDValue Cond = N0.getOperand(0);
6365 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6366 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6367 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6371 // Fold a series of buildvector, bitcast, and truncate if possible.
6373 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6374 // (2xi32 (buildvector x, y)).
6375 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6376 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6377 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6378 N0.getOperand(0).hasOneUse()) {
6380 SDValue BuildVect = N0.getOperand(0);
6381 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6382 EVT TruncVecEltTy = VT.getVectorElementType();
6384 // Check that the element types match.
6385 if (BuildVectEltTy == TruncVecEltTy) {
6386 // Now we only need to compute the offset of the truncated elements.
6387 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6388 unsigned TruncVecNumElts = VT.getVectorNumElements();
6389 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6391 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6392 "Invalid number of elements");
6394 SmallVector<SDValue, 8> Opnds;
6395 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6396 Opnds.push_back(BuildVect.getOperand(i));
6398 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6402 // See if we can simplify the input to this truncate through knowledge that
6403 // only the low bits are being used.
6404 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6405 // Currently we only perform this optimization on scalars because vectors
6406 // may have different active low bits.
6407 if (!VT.isVector()) {
6409 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6410 VT.getSizeInBits()));
6411 if (Shorter.getNode())
6412 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6414 // fold (truncate (load x)) -> (smaller load x)
6415 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6416 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6417 SDValue Reduced = ReduceLoadWidth(N);
6418 if (Reduced.getNode())
6420 // Handle the case where the load remains an extending load even
6421 // after truncation.
6422 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6423 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6424 if (!LN0->isVolatile() &&
6425 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6426 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6427 VT, LN0->getChain(), LN0->getBasePtr(),
6429 LN0->getMemOperand());
6430 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6435 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6436 // where ... are all 'undef'.
6437 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6438 SmallVector<EVT, 8> VTs;
6441 unsigned NumDefs = 0;
6443 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6444 SDValue X = N0.getOperand(i);
6445 if (X.getOpcode() != ISD::UNDEF) {
6450 // Stop if more than one members are non-undef.
6453 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6454 VT.getVectorElementType(),
6455 X.getValueType().getVectorNumElements()));
6459 return DAG.getUNDEF(VT);
6462 assert(V.getNode() && "The single defined operand is empty!");
6463 SmallVector<SDValue, 8> Opnds;
6464 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6466 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6469 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6470 AddToWorklist(NV.getNode());
6471 Opnds.push_back(NV);
6473 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6477 // Simplify the operands using demanded-bits information.
6478 if (!VT.isVector() &&
6479 SimplifyDemandedBits(SDValue(N, 0)))
6480 return SDValue(N, 0);
6485 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6486 SDValue Elt = N->getOperand(i);
6487 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6488 return Elt.getNode();
6489 return Elt.getOperand(Elt.getResNo()).getNode();
6492 /// build_pair (load, load) -> load
6493 /// if load locations are consecutive.
6494 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6495 assert(N->getOpcode() == ISD::BUILD_PAIR);
6497 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6498 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6499 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6500 LD1->getAddressSpace() != LD2->getAddressSpace())
6502 EVT LD1VT = LD1->getValueType(0);
6504 if (ISD::isNON_EXTLoad(LD2) &&
6506 // If both are volatile this would reduce the number of volatile loads.
6507 // If one is volatile it might be ok, but play conservative and bail out.
6508 !LD1->isVolatile() &&
6509 !LD2->isVolatile() &&
6510 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6511 unsigned Align = LD1->getAlignment();
6512 unsigned NewAlign = TLI.getDataLayout()->
6513 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6515 if (NewAlign <= Align &&
6516 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6517 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6518 LD1->getBasePtr(), LD1->getPointerInfo(),
6519 false, false, false, Align);
6525 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6526 SDValue N0 = N->getOperand(0);
6527 EVT VT = N->getValueType(0);
6529 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6530 // Only do this before legalize, since afterward the target may be depending
6531 // on the bitconvert.
6532 // First check to see if this is all constant.
6534 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6536 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6538 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6539 assert(!DestEltVT.isVector() &&
6540 "Element type of vector ValueType must not be vector!");
6542 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6545 // If the input is a constant, let getNode fold it.
6546 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6547 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6548 if (Res.getNode() != N) {
6549 if (!LegalOperations ||
6550 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6553 // Folding it resulted in an illegal node, and it's too late to
6554 // do that. Clean up the old node and forego the transformation.
6555 // Ideally this won't happen very often, because instcombine
6556 // and the earlier dagcombine runs (where illegal nodes are
6557 // permitted) should have folded most of them already.
6558 deleteAndRecombine(Res.getNode());
6562 // (conv (conv x, t1), t2) -> (conv x, t2)
6563 if (N0.getOpcode() == ISD::BITCAST)
6564 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6567 // fold (conv (load x)) -> (load (conv*)x)
6568 // If the resultant load doesn't need a higher alignment than the original!
6569 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6570 // Do not change the width of a volatile load.
6571 !cast<LoadSDNode>(N0)->isVolatile() &&
6572 // Do not remove the cast if the types differ in endian layout.
6573 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6574 TLI.hasBigEndianPartOrdering(VT) &&
6575 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6576 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6577 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6578 unsigned Align = TLI.getDataLayout()->
6579 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6580 unsigned OrigAlign = LN0->getAlignment();
6582 if (Align <= OrigAlign) {
6583 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6584 LN0->getBasePtr(), LN0->getPointerInfo(),
6585 LN0->isVolatile(), LN0->isNonTemporal(),
6586 LN0->isInvariant(), OrigAlign,
6588 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6593 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6594 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6595 // This often reduces constant pool loads.
6596 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6597 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6598 N0.getNode()->hasOneUse() && VT.isInteger() &&
6599 !VT.isVector() && !N0.getValueType().isVector()) {
6600 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6602 AddToWorklist(NewConv.getNode());
6604 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6605 if (N0.getOpcode() == ISD::FNEG)
6606 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6607 NewConv, DAG.getConstant(SignBit, VT));
6608 assert(N0.getOpcode() == ISD::FABS);
6609 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6610 NewConv, DAG.getConstant(~SignBit, VT));
6613 // fold (bitconvert (fcopysign cst, x)) ->
6614 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6615 // Note that we don't handle (copysign x, cst) because this can always be
6616 // folded to an fneg or fabs.
6617 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6618 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6619 VT.isInteger() && !VT.isVector()) {
6620 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6621 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6622 if (isTypeLegal(IntXVT)) {
6623 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6624 IntXVT, N0.getOperand(1));
6625 AddToWorklist(X.getNode());
6627 // If X has a different width than the result/lhs, sext it or truncate it.
6628 unsigned VTWidth = VT.getSizeInBits();
6629 if (OrigXWidth < VTWidth) {
6630 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6631 AddToWorklist(X.getNode());
6632 } else if (OrigXWidth > VTWidth) {
6633 // To get the sign bit in the right place, we have to shift it right
6634 // before truncating.
6635 X = DAG.getNode(ISD::SRL, SDLoc(X),
6636 X.getValueType(), X,
6637 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6638 AddToWorklist(X.getNode());
6639 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6640 AddToWorklist(X.getNode());
6643 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6644 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6645 X, DAG.getConstant(SignBit, VT));
6646 AddToWorklist(X.getNode());
6648 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6649 VT, N0.getOperand(0));
6650 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6651 Cst, DAG.getConstant(~SignBit, VT));
6652 AddToWorklist(Cst.getNode());
6654 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6658 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6659 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6660 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6661 if (CombineLD.getNode())
6668 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6669 EVT VT = N->getValueType(0);
6670 return CombineConsecutiveLoads(N, VT);
6673 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6674 /// operands. DstEltVT indicates the destination element value type.
6675 SDValue DAGCombiner::
6676 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6677 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6679 // If this is already the right type, we're done.
6680 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6682 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6683 unsigned DstBitSize = DstEltVT.getSizeInBits();
6685 // If this is a conversion of N elements of one type to N elements of another
6686 // type, convert each element. This handles FP<->INT cases.
6687 if (SrcBitSize == DstBitSize) {
6688 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6689 BV->getValueType(0).getVectorNumElements());
6691 // Due to the FP element handling below calling this routine recursively,
6692 // we can end up with a scalar-to-vector node here.
6693 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6694 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6695 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6696 DstEltVT, BV->getOperand(0)));
6698 SmallVector<SDValue, 8> Ops;
6699 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6700 SDValue Op = BV->getOperand(i);
6701 // If the vector element type is not legal, the BUILD_VECTOR operands
6702 // are promoted and implicitly truncated. Make that explicit here.
6703 if (Op.getValueType() != SrcEltVT)
6704 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6705 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6707 AddToWorklist(Ops.back().getNode());
6709 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6712 // Otherwise, we're growing or shrinking the elements. To avoid having to
6713 // handle annoying details of growing/shrinking FP values, we convert them to
6715 if (SrcEltVT.isFloatingPoint()) {
6716 // Convert the input float vector to a int vector where the elements are the
6718 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6719 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6723 // Now we know the input is an integer vector. If the output is a FP type,
6724 // convert to integer first, then to FP of the right size.
6725 if (DstEltVT.isFloatingPoint()) {
6726 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6727 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6729 // Next, convert to FP elements of the same size.
6730 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6733 // Okay, we know the src/dst types are both integers of differing types.
6734 // Handling growing first.
6735 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6736 if (SrcBitSize < DstBitSize) {
6737 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6739 SmallVector<SDValue, 8> Ops;
6740 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6741 i += NumInputsPerOutput) {
6742 bool isLE = TLI.isLittleEndian();
6743 APInt NewBits = APInt(DstBitSize, 0);
6744 bool EltIsUndef = true;
6745 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6746 // Shift the previously computed bits over.
6747 NewBits <<= SrcBitSize;
6748 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6749 if (Op.getOpcode() == ISD::UNDEF) continue;
6752 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6753 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6757 Ops.push_back(DAG.getUNDEF(DstEltVT));
6759 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6762 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6763 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6766 // Finally, this must be the case where we are shrinking elements: each input
6767 // turns into multiple outputs.
6768 bool isS2V = ISD::isScalarToVector(BV);
6769 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6770 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6771 NumOutputsPerInput*BV->getNumOperands());
6772 SmallVector<SDValue, 8> Ops;
6774 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6775 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6776 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6777 Ops.push_back(DAG.getUNDEF(DstEltVT));
6781 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6782 getAPIntValue().zextOrTrunc(SrcBitSize);
6784 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6785 APInt ThisVal = OpVal.trunc(DstBitSize);
6786 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6787 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6788 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6789 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6791 OpVal = OpVal.lshr(DstBitSize);
6794 // For big endian targets, swap the order of the pieces of each element.
6795 if (TLI.isBigEndian())
6796 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6799 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6802 SDValue DAGCombiner::visitFADD(SDNode *N) {
6803 SDValue N0 = N->getOperand(0);
6804 SDValue N1 = N->getOperand(1);
6805 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6806 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6807 EVT VT = N->getValueType(0);
6808 const TargetOptions &Options = DAG.getTarget().Options;
6811 if (VT.isVector()) {
6812 SDValue FoldedVOp = SimplifyVBinOp(N);
6813 if (FoldedVOp.getNode()) return FoldedVOp;
6816 // fold (fadd c1, c2) -> c1 + c2
6818 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6820 // canonicalize constant to RHS
6821 if (N0CFP && !N1CFP)
6822 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6824 // fold (fadd A, (fneg B)) -> (fsub A, B)
6825 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6826 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6827 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6828 GetNegatedExpression(N1, DAG, LegalOperations));
6830 // fold (fadd (fneg A), B) -> (fsub B, A)
6831 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6832 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6833 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6834 GetNegatedExpression(N0, DAG, LegalOperations));
6836 // If 'unsafe math' is enabled, fold lots of things.
6837 if (Options.UnsafeFPMath) {
6838 // No FP constant should be created after legalization as Instruction
6839 // Selection pass has a hard time dealing with FP constants.
6840 bool AllowNewConst = (Level < AfterLegalizeDAG);
6842 // fold (fadd A, 0) -> A
6843 if (N1CFP && N1CFP->getValueAPF().isZero())
6846 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6847 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6848 isa<ConstantFPSDNode>(N0.getOperand(1)))
6849 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6850 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6851 N0.getOperand(1), N1));
6853 // If allowed, fold (fadd (fneg x), x) -> 0.0
6854 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6855 return DAG.getConstantFP(0.0, VT);
6857 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6858 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6859 return DAG.getConstantFP(0.0, VT);
6861 // We can fold chains of FADD's of the same value into multiplications.
6862 // This transform is not safe in general because we are reducing the number
6863 // of rounding steps.
6864 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6865 if (N0.getOpcode() == ISD::FMUL) {
6866 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6867 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6869 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6870 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6871 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6873 DAG.getConstantFP(1.0, VT));
6874 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6877 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6878 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6879 N1.getOperand(0) == N1.getOperand(1) &&
6880 N0.getOperand(0) == N1.getOperand(0)) {
6881 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6883 DAG.getConstantFP(2.0, VT));
6884 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6885 N0.getOperand(0), NewCFP);
6889 if (N1.getOpcode() == ISD::FMUL) {
6890 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6891 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6893 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6894 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6895 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6897 DAG.getConstantFP(1.0, VT));
6898 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6901 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6902 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6903 N0.getOperand(0) == N0.getOperand(1) &&
6904 N1.getOperand(0) == N0.getOperand(0)) {
6905 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6907 DAG.getConstantFP(2.0, VT));
6908 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6912 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6913 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6914 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6915 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6916 (N0.getOperand(0) == N1))
6917 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6918 N1, DAG.getConstantFP(3.0, VT));
6921 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6922 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6923 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6924 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6925 N1.getOperand(0) == N0)
6926 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6927 N0, DAG.getConstantFP(3.0, VT));
6930 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6931 if (AllowNewConst &&
6932 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6933 N0.getOperand(0) == N0.getOperand(1) &&
6934 N1.getOperand(0) == N1.getOperand(1) &&
6935 N0.getOperand(0) == N1.getOperand(0))
6936 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6937 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6939 } // enable-unsafe-fp-math
6941 // FADD -> FMA combines:
6942 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6943 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6944 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6946 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6947 if (N0.getOpcode() == ISD::FMUL &&
6948 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6949 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6950 N0.getOperand(0), N0.getOperand(1), N1);
6952 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6953 // Note: Commutes FADD operands.
6954 if (N1.getOpcode() == ISD::FMUL &&
6955 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6956 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6957 N1.getOperand(0), N1.getOperand(1), N0);
6959 // When FP_EXTEND nodes are free on the target, and there is an opportunity
6960 // to combine into FMA, arrange such nodes accordingly.
6961 if (TLI.isFPExtFree(VT)) {
6963 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
6964 if (N0.getOpcode() == ISD::FP_EXTEND) {
6965 SDValue N00 = N0.getOperand(0);
6966 if (N00.getOpcode() == ISD::FMUL)
6967 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6968 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6970 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6971 N00.getOperand(1)), N1);
6974 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
6975 // Note: Commutes FADD operands.
6976 if (N1.getOpcode() == ISD::FP_EXTEND) {
6977 SDValue N10 = N1.getOperand(0);
6978 if (N10.getOpcode() == ISD::FMUL)
6979 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6980 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6982 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6983 N10.getOperand(1)), N0);
6987 // More folding opportunities when target permits.
6988 if (TLI.enableAggressiveFMAFusion(VT)) {
6990 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
6991 if (N0.getOpcode() == ISD::FMA &&
6992 N0.getOperand(2).getOpcode() == ISD::FMUL)
6993 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6994 N0.getOperand(0), N0.getOperand(1),
6995 DAG.getNode(ISD::FMA, SDLoc(N), VT,
6996 N0.getOperand(2).getOperand(0),
6997 N0.getOperand(2).getOperand(1),
7000 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7001 if (N1->getOpcode() == ISD::FMA &&
7002 N1.getOperand(2).getOpcode() == ISD::FMUL)
7003 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7004 N1.getOperand(0), N1.getOperand(1),
7005 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7006 N1.getOperand(2).getOperand(0),
7007 N1.getOperand(2).getOperand(1),
7015 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7016 SDValue N0 = N->getOperand(0);
7017 SDValue N1 = N->getOperand(1);
7018 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7019 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7020 EVT VT = N->getValueType(0);
7022 const TargetOptions &Options = DAG.getTarget().Options;
7025 if (VT.isVector()) {
7026 SDValue FoldedVOp = SimplifyVBinOp(N);
7027 if (FoldedVOp.getNode()) return FoldedVOp;
7030 // fold (fsub c1, c2) -> c1-c2
7032 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7034 // fold (fsub A, (fneg B)) -> (fadd A, B)
7035 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7036 return DAG.getNode(ISD::FADD, dl, VT, N0,
7037 GetNegatedExpression(N1, DAG, LegalOperations));
7039 // If 'unsafe math' is enabled, fold lots of things.
7040 if (Options.UnsafeFPMath) {
7042 if (N1CFP && N1CFP->getValueAPF().isZero())
7045 // (fsub 0, B) -> -B
7046 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7047 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7048 return GetNegatedExpression(N1, DAG, LegalOperations);
7049 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7050 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7053 // (fsub x, x) -> 0.0
7055 return DAG.getConstantFP(0.0f, VT);
7057 // (fsub x, (fadd x, y)) -> (fneg y)
7058 // (fsub x, (fadd y, x)) -> (fneg y)
7059 if (N1.getOpcode() == ISD::FADD) {
7060 SDValue N10 = N1->getOperand(0);
7061 SDValue N11 = N1->getOperand(1);
7063 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7064 return GetNegatedExpression(N11, DAG, LegalOperations);
7066 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7067 return GetNegatedExpression(N10, DAG, LegalOperations);
7071 // FSUB -> FMA combines:
7072 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7073 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7074 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7076 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7077 if (N0.getOpcode() == ISD::FMUL &&
7078 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7079 return DAG.getNode(ISD::FMA, dl, VT,
7080 N0.getOperand(0), N0.getOperand(1),
7081 DAG.getNode(ISD::FNEG, dl, VT, N1));
7083 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7084 // Note: Commutes FSUB operands.
7085 if (N1.getOpcode() == ISD::FMUL &&
7086 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7087 return DAG.getNode(ISD::FMA, dl, VT,
7088 DAG.getNode(ISD::FNEG, dl, VT,
7090 N1.getOperand(1), N0);
7092 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7093 if (N0.getOpcode() == ISD::FNEG &&
7094 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7095 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
7096 TLI.enableAggressiveFMAFusion(VT))) {
7097 SDValue N00 = N0.getOperand(0).getOperand(0);
7098 SDValue N01 = N0.getOperand(0).getOperand(1);
7099 return DAG.getNode(ISD::FMA, dl, VT,
7100 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
7101 DAG.getNode(ISD::FNEG, dl, VT, N1));
7104 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7105 // to combine into FMA, arrange such nodes accordingly.
7106 if (TLI.isFPExtFree(VT)) {
7108 // fold (fsub (fpext (fmul x, y)), z)
7109 // -> (fma (fpext x), (fpext y), (fneg z))
7110 if (N0.getOpcode() == ISD::FP_EXTEND) {
7111 SDValue N00 = N0.getOperand(0);
7112 if (N00.getOpcode() == ISD::FMUL)
7113 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7114 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7116 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7118 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7121 // fold (fsub x, (fpext (fmul y, z)))
7122 // -> (fma (fneg (fpext y)), (fpext z), x)
7123 // Note: Commutes FSUB operands.
7124 if (N1.getOpcode() == ISD::FP_EXTEND) {
7125 SDValue N10 = N1.getOperand(0);
7126 if (N10.getOpcode() == ISD::FMUL)
7127 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7128 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7129 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7130 VT, N10.getOperand(0))),
7131 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7136 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7137 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7138 if (N0.getOpcode() == ISD::FP_EXTEND) {
7139 SDValue N00 = N0.getOperand(0);
7140 if (N00.getOpcode() == ISD::FNEG) {
7141 SDValue N000 = N00.getOperand(0);
7142 if (N000.getOpcode() == ISD::FMUL) {
7143 return DAG.getNode(ISD::FMA, dl, VT,
7144 DAG.getNode(ISD::FNEG, dl, VT,
7145 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7146 VT, N000.getOperand(0))),
7147 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7148 N000.getOperand(1)),
7149 DAG.getNode(ISD::FNEG, dl, VT, N1));
7154 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7155 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7156 if (N0.getOpcode() == ISD::FNEG) {
7157 SDValue N00 = N0.getOperand(0);
7158 if (N00.getOpcode() == ISD::FP_EXTEND) {
7159 SDValue N000 = N00.getOperand(0);
7160 if (N000.getOpcode() == ISD::FMUL) {
7161 return DAG.getNode(ISD::FMA, dl, VT,
7162 DAG.getNode(ISD::FNEG, dl, VT,
7163 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7164 VT, N000.getOperand(0))),
7165 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7166 N000.getOperand(1)),
7167 DAG.getNode(ISD::FNEG, dl, VT, N1));
7173 // More folding opportunities when target permits.
7174 if (TLI.enableAggressiveFMAFusion(VT)) {
7176 // fold (fsub (fma x, y, (fmul u, v)), z)
7177 // -> (fma x, y (fma u, v, (fneg z)))
7178 if (N0.getOpcode() == ISD::FMA &&
7179 N0.getOperand(2).getOpcode() == ISD::FMUL)
7180 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7181 N0.getOperand(0), N0.getOperand(1),
7182 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7183 N0.getOperand(2).getOperand(0),
7184 N0.getOperand(2).getOperand(1),
7185 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7188 // fold (fsub x, (fma y, z, (fmul u, v)))
7189 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7190 if (N1.getOpcode() == ISD::FMA &&
7191 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7192 SDValue N20 = N1.getOperand(2).getOperand(0);
7193 SDValue N21 = N1.getOperand(2).getOperand(1);
7194 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7195 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7198 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7199 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7209 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7210 SDValue N0 = N->getOperand(0);
7211 SDValue N1 = N->getOperand(1);
7212 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7213 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7214 EVT VT = N->getValueType(0);
7215 const TargetOptions &Options = DAG.getTarget().Options;
7218 if (VT.isVector()) {
7219 // This just handles C1 * C2 for vectors. Other vector folds are below.
7220 SDValue FoldedVOp = SimplifyVBinOp(N);
7221 if (FoldedVOp.getNode())
7223 // Canonicalize vector constant to RHS.
7224 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7225 N1.getOpcode() != ISD::BUILD_VECTOR)
7226 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7227 if (BV0->isConstant())
7228 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7231 // fold (fmul c1, c2) -> c1*c2
7233 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7235 // canonicalize constant to RHS
7236 if (N0CFP && !N1CFP)
7237 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7239 // fold (fmul A, 1.0) -> A
7240 if (N1CFP && N1CFP->isExactlyValue(1.0))
7243 if (Options.UnsafeFPMath) {
7244 // fold (fmul A, 0) -> 0
7245 if (N1CFP && N1CFP->getValueAPF().isZero())
7248 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7249 if (N0.getOpcode() == ISD::FMUL) {
7250 // Fold scalars or any vector constants (not just splats).
7251 // This fold is done in general by InstCombine, but extra fmul insts
7252 // may have been generated during lowering.
7253 SDValue N01 = N0.getOperand(1);
7254 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7255 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7256 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7257 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7259 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7260 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7264 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7265 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7266 // during an early run of DAGCombiner can prevent folding with fmuls
7267 // inserted during lowering.
7268 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7270 const SDValue Two = DAG.getConstantFP(2.0, VT);
7271 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7272 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7276 // fold (fmul X, 2.0) -> (fadd X, X)
7277 if (N1CFP && N1CFP->isExactlyValue(+2.0))
7278 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7280 // fold (fmul X, -1.0) -> (fneg X)
7281 if (N1CFP && N1CFP->isExactlyValue(-1.0))
7282 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7283 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7285 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7286 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7287 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7288 // Both can be negated for free, check to see if at least one is cheaper
7290 if (LHSNeg == 2 || RHSNeg == 2)
7291 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7292 GetNegatedExpression(N0, DAG, LegalOperations),
7293 GetNegatedExpression(N1, DAG, LegalOperations));
7300 SDValue DAGCombiner::visitFMA(SDNode *N) {
7301 SDValue N0 = N->getOperand(0);
7302 SDValue N1 = N->getOperand(1);
7303 SDValue N2 = N->getOperand(2);
7304 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7305 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7306 EVT VT = N->getValueType(0);
7308 const TargetOptions &Options = DAG.getTarget().Options;
7310 // Constant fold FMA.
7311 if (isa<ConstantFPSDNode>(N0) &&
7312 isa<ConstantFPSDNode>(N1) &&
7313 isa<ConstantFPSDNode>(N2)) {
7314 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7317 if (Options.UnsafeFPMath) {
7318 if (N0CFP && N0CFP->isZero())
7320 if (N1CFP && N1CFP->isZero())
7323 if (N0CFP && N0CFP->isExactlyValue(1.0))
7324 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7325 if (N1CFP && N1CFP->isExactlyValue(1.0))
7326 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7328 // Canonicalize (fma c, x, y) -> (fma x, c, y)
7329 if (N0CFP && !N1CFP)
7330 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7332 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7333 if (Options.UnsafeFPMath && N1CFP &&
7334 N2.getOpcode() == ISD::FMUL &&
7335 N0 == N2.getOperand(0) &&
7336 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7337 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7338 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7342 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7343 if (Options.UnsafeFPMath &&
7344 N0.getOpcode() == ISD::FMUL && N1CFP &&
7345 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7346 return DAG.getNode(ISD::FMA, dl, VT,
7348 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7352 // (fma x, 1, y) -> (fadd x, y)
7353 // (fma x, -1, y) -> (fadd (fneg x), y)
7355 if (N1CFP->isExactlyValue(1.0))
7356 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7358 if (N1CFP->isExactlyValue(-1.0) &&
7359 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7360 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7361 AddToWorklist(RHSNeg.getNode());
7362 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7366 // (fma x, c, x) -> (fmul x, (c+1))
7367 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7368 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7369 DAG.getNode(ISD::FADD, dl, VT,
7370 N1, DAG.getConstantFP(1.0, VT)));
7372 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7373 if (Options.UnsafeFPMath && N1CFP &&
7374 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7375 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7376 DAG.getNode(ISD::FADD, dl, VT,
7377 N1, DAG.getConstantFP(-1.0, VT)));
7383 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7384 SDValue N0 = N->getOperand(0);
7385 SDValue N1 = N->getOperand(1);
7386 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7387 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7388 EVT VT = N->getValueType(0);
7390 const TargetOptions &Options = DAG.getTarget().Options;
7393 if (VT.isVector()) {
7394 SDValue FoldedVOp = SimplifyVBinOp(N);
7395 if (FoldedVOp.getNode()) return FoldedVOp;
7398 // fold (fdiv c1, c2) -> c1/c2
7400 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7402 if (Options.UnsafeFPMath) {
7403 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7405 // Compute the reciprocal 1.0 / c2.
7406 APFloat N1APF = N1CFP->getValueAPF();
7407 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7408 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7409 // Only do the transform if the reciprocal is a legal fp immediate that
7410 // isn't too nasty (eg NaN, denormal, ...).
7411 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7412 (!LegalOperations ||
7413 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7414 // backend)... we should handle this gracefully after Legalize.
7415 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7416 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7417 TLI.isFPImmLegal(Recip, VT)))
7418 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7419 DAG.getConstantFP(Recip, VT));
7422 // If this FDIV is part of a reciprocal square root, it may be folded
7423 // into a target-specific square root estimate instruction.
7424 if (N1.getOpcode() == ISD::FSQRT) {
7425 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7426 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7428 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7429 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7430 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7431 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7432 AddToWorklist(RV.getNode());
7433 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7435 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7436 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7437 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7438 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7439 AddToWorklist(RV.getNode());
7440 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7442 } else if (N1.getOpcode() == ISD::FMUL) {
7443 // Look through an FMUL. Even though this won't remove the FDIV directly,
7444 // it's still worthwhile to get rid of the FSQRT if possible.
7447 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7448 SqrtOp = N1.getOperand(0);
7449 OtherOp = N1.getOperand(1);
7450 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7451 SqrtOp = N1.getOperand(1);
7452 OtherOp = N1.getOperand(0);
7454 if (SqrtOp.getNode()) {
7455 // We found a FSQRT, so try to make this fold:
7456 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7457 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7458 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7459 AddToWorklist(RV.getNode());
7460 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7465 // Fold into a reciprocal estimate and multiply instead of a real divide.
7466 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7467 AddToWorklist(RV.getNode());
7468 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7472 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7473 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7474 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7475 // Both can be negated for free, check to see if at least one is cheaper
7477 if (LHSNeg == 2 || RHSNeg == 2)
7478 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7479 GetNegatedExpression(N0, DAG, LegalOperations),
7480 GetNegatedExpression(N1, DAG, LegalOperations));
7484 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7486 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7487 // Notice that this is not always beneficial. One reason is different target
7488 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7489 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7490 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7491 if (Options.UnsafeFPMath) {
7492 // Skip if current node is a reciprocal.
7493 if (N0CFP && N0CFP->isExactlyValue(1.0))
7496 SmallVector<SDNode *, 4> Users;
7497 // Find all FDIV users of the same divisor.
7498 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7499 UE = N1.getNode()->use_end();
7501 SDNode *User = UI.getUse().getUser();
7502 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7503 Users.push_back(User);
7506 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7507 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7508 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7510 // Dividend / Divisor -> Dividend * Reciprocal
7511 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7512 if ((*I)->getOperand(0) != FPOne) {
7513 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7514 (*I)->getOperand(0), Reciprocal);
7515 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7525 SDValue DAGCombiner::visitFREM(SDNode *N) {
7526 SDValue N0 = N->getOperand(0);
7527 SDValue N1 = N->getOperand(1);
7528 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7529 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7530 EVT VT = N->getValueType(0);
7532 // fold (frem c1, c2) -> fmod(c1,c2)
7534 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7539 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7540 if (DAG.getTarget().Options.UnsafeFPMath &&
7541 !TLI.isFsqrtCheap()) {
7542 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7543 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7544 EVT VT = RV.getValueType();
7545 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7546 AddToWorklist(RV.getNode());
7548 // Unfortunately, RV is now NaN if the input was exactly 0.
7549 // Select out this case and force the answer to 0.
7550 SDValue Zero = DAG.getConstantFP(0.0, VT);
7552 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7553 N->getOperand(0), Zero, ISD::SETEQ);
7554 AddToWorklist(ZeroCmp.getNode());
7555 AddToWorklist(RV.getNode());
7557 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7558 SDLoc(N), VT, ZeroCmp, Zero, RV);
7565 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7566 SDValue N0 = N->getOperand(0);
7567 SDValue N1 = N->getOperand(1);
7568 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7569 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7570 EVT VT = N->getValueType(0);
7572 if (N0CFP && N1CFP) // Constant fold
7573 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7576 const APFloat& V = N1CFP->getValueAPF();
7577 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7578 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7579 if (!V.isNegative()) {
7580 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7581 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7583 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7584 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7585 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7589 // copysign(fabs(x), y) -> copysign(x, y)
7590 // copysign(fneg(x), y) -> copysign(x, y)
7591 // copysign(copysign(x,z), y) -> copysign(x, y)
7592 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7593 N0.getOpcode() == ISD::FCOPYSIGN)
7594 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7595 N0.getOperand(0), N1);
7597 // copysign(x, abs(y)) -> abs(x)
7598 if (N1.getOpcode() == ISD::FABS)
7599 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7601 // copysign(x, copysign(y,z)) -> copysign(x, z)
7602 if (N1.getOpcode() == ISD::FCOPYSIGN)
7603 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7604 N0, N1.getOperand(1));
7606 // copysign(x, fp_extend(y)) -> copysign(x, y)
7607 // copysign(x, fp_round(y)) -> copysign(x, y)
7608 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7609 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7610 N0, N1.getOperand(0));
7615 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7616 SDValue N0 = N->getOperand(0);
7617 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7618 EVT VT = N->getValueType(0);
7619 EVT OpVT = N0.getValueType();
7621 // fold (sint_to_fp c1) -> c1fp
7623 // ...but only if the target supports immediate floating-point values
7624 (!LegalOperations ||
7625 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7626 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7628 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7629 // but UINT_TO_FP is legal on this target, try to convert.
7630 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7631 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7632 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7633 if (DAG.SignBitIsZero(N0))
7634 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7637 // The next optimizations are desirable only if SELECT_CC can be lowered.
7638 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7639 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7640 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7642 (!LegalOperations ||
7643 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7645 { N0.getOperand(0), N0.getOperand(1),
7646 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7648 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7651 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7652 // (select_cc x, y, 1.0, 0.0,, cc)
7653 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7654 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7655 (!LegalOperations ||
7656 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7658 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7659 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7660 N0.getOperand(0).getOperand(2) };
7661 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7668 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7669 SDValue N0 = N->getOperand(0);
7670 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7671 EVT VT = N->getValueType(0);
7672 EVT OpVT = N0.getValueType();
7674 // fold (uint_to_fp c1) -> c1fp
7676 // ...but only if the target supports immediate floating-point values
7677 (!LegalOperations ||
7678 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7679 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7681 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7682 // but SINT_TO_FP is legal on this target, try to convert.
7683 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7684 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7685 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7686 if (DAG.SignBitIsZero(N0))
7687 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7690 // The next optimizations are desirable only if SELECT_CC can be lowered.
7691 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7692 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7694 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7695 (!LegalOperations ||
7696 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7698 { N0.getOperand(0), N0.getOperand(1),
7699 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7701 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7708 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7709 SDValue N0 = N->getOperand(0);
7710 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7711 EVT VT = N->getValueType(0);
7713 // fold (fp_to_sint c1fp) -> c1
7715 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7720 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7721 SDValue N0 = N->getOperand(0);
7722 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7723 EVT VT = N->getValueType(0);
7725 // fold (fp_to_uint c1fp) -> c1
7727 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7732 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7733 SDValue N0 = N->getOperand(0);
7734 SDValue N1 = N->getOperand(1);
7735 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7736 EVT VT = N->getValueType(0);
7738 // fold (fp_round c1fp) -> c1fp
7740 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7742 // fold (fp_round (fp_extend x)) -> x
7743 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7744 return N0.getOperand(0);
7746 // fold (fp_round (fp_round x)) -> (fp_round x)
7747 if (N0.getOpcode() == ISD::FP_ROUND) {
7748 // This is a value preserving truncation if both round's are.
7749 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7750 N0.getNode()->getConstantOperandVal(1) == 1;
7751 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7752 DAG.getIntPtrConstant(IsTrunc));
7755 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7756 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7757 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7758 N0.getOperand(0), N1);
7759 AddToWorklist(Tmp.getNode());
7760 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7761 Tmp, N0.getOperand(1));
7767 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7768 SDValue N0 = N->getOperand(0);
7769 EVT VT = N->getValueType(0);
7770 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7771 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7773 // fold (fp_round_inreg c1fp) -> c1fp
7774 if (N0CFP && isTypeLegal(EVT)) {
7775 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7776 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7782 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7783 SDValue N0 = N->getOperand(0);
7784 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7785 EVT VT = N->getValueType(0);
7787 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7788 if (N->hasOneUse() &&
7789 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7792 // fold (fp_extend c1fp) -> c1fp
7794 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7796 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7798 if (N0.getOpcode() == ISD::FP_ROUND
7799 && N0.getNode()->getConstantOperandVal(1) == 1) {
7800 SDValue In = N0.getOperand(0);
7801 if (In.getValueType() == VT) return In;
7802 if (VT.bitsLT(In.getValueType()))
7803 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7804 In, N0.getOperand(1));
7805 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7808 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7809 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7810 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7811 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7812 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7814 LN0->getBasePtr(), N0.getValueType(),
7815 LN0->getMemOperand());
7816 CombineTo(N, ExtLoad);
7817 CombineTo(N0.getNode(),
7818 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7819 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7820 ExtLoad.getValue(1));
7821 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7827 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7828 SDValue N0 = N->getOperand(0);
7829 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7830 EVT VT = N->getValueType(0);
7832 // fold (fceil c1) -> fceil(c1)
7834 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7839 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7840 SDValue N0 = N->getOperand(0);
7841 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7842 EVT VT = N->getValueType(0);
7844 // fold (ftrunc c1) -> ftrunc(c1)
7846 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7851 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7852 SDValue N0 = N->getOperand(0);
7853 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7854 EVT VT = N->getValueType(0);
7856 // fold (ffloor c1) -> ffloor(c1)
7858 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7863 // FIXME: FNEG and FABS have a lot in common; refactor.
7864 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7865 SDValue N0 = N->getOperand(0);
7866 EVT VT = N->getValueType(0);
7868 if (VT.isVector()) {
7869 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7870 if (FoldedVOp.getNode()) return FoldedVOp;
7873 // Constant fold FNEG.
7874 if (isa<ConstantFPSDNode>(N0))
7875 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7877 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7878 &DAG.getTarget().Options))
7879 return GetNegatedExpression(N0, DAG, LegalOperations);
7881 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7882 // constant pool values.
7883 if (!TLI.isFNegFree(VT) &&
7884 N0.getOpcode() == ISD::BITCAST &&
7885 N0.getNode()->hasOneUse()) {
7886 SDValue Int = N0.getOperand(0);
7887 EVT IntVT = Int.getValueType();
7888 if (IntVT.isInteger() && !IntVT.isVector()) {
7890 if (N0.getValueType().isVector()) {
7891 // For a vector, get a mask such as 0x80... per scalar element
7893 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7894 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7896 // For a scalar, just generate 0x80...
7897 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7899 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7900 DAG.getConstant(SignMask, IntVT));
7901 AddToWorklist(Int.getNode());
7902 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7906 // (fneg (fmul c, x)) -> (fmul -c, x)
7907 if (N0.getOpcode() == ISD::FMUL) {
7908 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7910 APFloat CVal = CFP1->getValueAPF();
7912 if (Level >= AfterLegalizeDAG &&
7913 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7914 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7916 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7917 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7924 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7925 SDValue N0 = N->getOperand(0);
7926 SDValue N1 = N->getOperand(1);
7927 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7928 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7930 if (N0CFP && N1CFP) {
7931 const APFloat &C0 = N0CFP->getValueAPF();
7932 const APFloat &C1 = N1CFP->getValueAPF();
7933 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7937 EVT VT = N->getValueType(0);
7938 // Canonicalize to constant on RHS.
7939 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7945 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7946 SDValue N0 = N->getOperand(0);
7947 SDValue N1 = N->getOperand(1);
7948 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7949 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7951 if (N0CFP && N1CFP) {
7952 const APFloat &C0 = N0CFP->getValueAPF();
7953 const APFloat &C1 = N1CFP->getValueAPF();
7954 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7958 EVT VT = N->getValueType(0);
7959 // Canonicalize to constant on RHS.
7960 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7966 SDValue DAGCombiner::visitFABS(SDNode *N) {
7967 SDValue N0 = N->getOperand(0);
7968 EVT VT = N->getValueType(0);
7970 if (VT.isVector()) {
7971 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7972 if (FoldedVOp.getNode()) return FoldedVOp;
7975 // fold (fabs c1) -> fabs(c1)
7976 if (isa<ConstantFPSDNode>(N0))
7977 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7979 // fold (fabs (fabs x)) -> (fabs x)
7980 if (N0.getOpcode() == ISD::FABS)
7981 return N->getOperand(0);
7983 // fold (fabs (fneg x)) -> (fabs x)
7984 // fold (fabs (fcopysign x, y)) -> (fabs x)
7985 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7986 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7988 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7989 // constant pool values.
7990 if (!TLI.isFAbsFree(VT) &&
7991 N0.getOpcode() == ISD::BITCAST &&
7992 N0.getNode()->hasOneUse()) {
7993 SDValue Int = N0.getOperand(0);
7994 EVT IntVT = Int.getValueType();
7995 if (IntVT.isInteger() && !IntVT.isVector()) {
7997 if (N0.getValueType().isVector()) {
7998 // For a vector, get a mask such as 0x7f... per scalar element
8000 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8001 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8003 // For a scalar, just generate 0x7f...
8004 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8006 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8007 DAG.getConstant(SignMask, IntVT));
8008 AddToWorklist(Int.getNode());
8009 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8016 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8017 SDValue Chain = N->getOperand(0);
8018 SDValue N1 = N->getOperand(1);
8019 SDValue N2 = N->getOperand(2);
8021 // If N is a constant we could fold this into a fallthrough or unconditional
8022 // branch. However that doesn't happen very often in normal code, because
8023 // Instcombine/SimplifyCFG should have handled the available opportunities.
8024 // If we did this folding here, it would be necessary to update the
8025 // MachineBasicBlock CFG, which is awkward.
8027 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8029 if (N1.getOpcode() == ISD::SETCC &&
8030 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8031 N1.getOperand(0).getValueType())) {
8032 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8033 Chain, N1.getOperand(2),
8034 N1.getOperand(0), N1.getOperand(1), N2);
8037 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8038 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8039 (N1.getOperand(0).hasOneUse() &&
8040 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8041 SDNode *Trunc = nullptr;
8042 if (N1.getOpcode() == ISD::TRUNCATE) {
8043 // Look pass the truncate.
8044 Trunc = N1.getNode();
8045 N1 = N1.getOperand(0);
8048 // Match this pattern so that we can generate simpler code:
8051 // %b = and i32 %a, 2
8052 // %c = srl i32 %b, 1
8053 // brcond i32 %c ...
8058 // %b = and i32 %a, 2
8059 // %c = setcc eq %b, 0
8062 // This applies only when the AND constant value has one bit set and the
8063 // SRL constant is equal to the log2 of the AND constant. The back-end is
8064 // smart enough to convert the result into a TEST/JMP sequence.
8065 SDValue Op0 = N1.getOperand(0);
8066 SDValue Op1 = N1.getOperand(1);
8068 if (Op0.getOpcode() == ISD::AND &&
8069 Op1.getOpcode() == ISD::Constant) {
8070 SDValue AndOp1 = Op0.getOperand(1);
8072 if (AndOp1.getOpcode() == ISD::Constant) {
8073 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8075 if (AndConst.isPowerOf2() &&
8076 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8078 DAG.getSetCC(SDLoc(N),
8079 getSetCCResultType(Op0.getValueType()),
8080 Op0, DAG.getConstant(0, Op0.getValueType()),
8083 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8084 MVT::Other, Chain, SetCC, N2);
8085 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8086 // will convert it back to (X & C1) >> C2.
8087 CombineTo(N, NewBRCond, false);
8088 // Truncate is dead.
8090 deleteAndRecombine(Trunc);
8091 // Replace the uses of SRL with SETCC
8092 WorklistRemover DeadNodes(*this);
8093 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8094 deleteAndRecombine(N1.getNode());
8095 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8101 // Restore N1 if the above transformation doesn't match.
8102 N1 = N->getOperand(1);
8105 // Transform br(xor(x, y)) -> br(x != y)
8106 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8107 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8108 SDNode *TheXor = N1.getNode();
8109 SDValue Op0 = TheXor->getOperand(0);
8110 SDValue Op1 = TheXor->getOperand(1);
8111 if (Op0.getOpcode() == Op1.getOpcode()) {
8112 // Avoid missing important xor optimizations.
8113 SDValue Tmp = visitXOR(TheXor);
8114 if (Tmp.getNode()) {
8115 if (Tmp.getNode() != TheXor) {
8116 DEBUG(dbgs() << "\nReplacing.8 ";
8118 dbgs() << "\nWith: ";
8119 Tmp.getNode()->dump(&DAG);
8121 WorklistRemover DeadNodes(*this);
8122 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8123 deleteAndRecombine(TheXor);
8124 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8125 MVT::Other, Chain, Tmp, N2);
8128 // visitXOR has changed XOR's operands or replaced the XOR completely,
8130 return SDValue(N, 0);
8134 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8136 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8137 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8138 Op0.getOpcode() == ISD::XOR) {
8139 TheXor = Op0.getNode();
8143 EVT SetCCVT = N1.getValueType();
8145 SetCCVT = getSetCCResultType(SetCCVT);
8146 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8149 Equal ? ISD::SETEQ : ISD::SETNE);
8150 // Replace the uses of XOR with SETCC
8151 WorklistRemover DeadNodes(*this);
8152 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8153 deleteAndRecombine(N1.getNode());
8154 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8155 MVT::Other, Chain, SetCC, N2);
8162 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8164 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8165 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8166 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8168 // If N is a constant we could fold this into a fallthrough or unconditional
8169 // branch. However that doesn't happen very often in normal code, because
8170 // Instcombine/SimplifyCFG should have handled the available opportunities.
8171 // If we did this folding here, it would be necessary to update the
8172 // MachineBasicBlock CFG, which is awkward.
8174 // Use SimplifySetCC to simplify SETCC's.
8175 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8176 CondLHS, CondRHS, CC->get(), SDLoc(N),
8178 if (Simp.getNode()) AddToWorklist(Simp.getNode());
8180 // fold to a simpler setcc
8181 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8182 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8183 N->getOperand(0), Simp.getOperand(2),
8184 Simp.getOperand(0), Simp.getOperand(1),
8190 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8191 /// and that N may be folded in the load / store addressing mode.
8192 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8194 const TargetLowering &TLI) {
8196 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8197 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8199 VT = Use->getValueType(0);
8200 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8201 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8203 VT = ST->getValue().getValueType();
8207 TargetLowering::AddrMode AM;
8208 if (N->getOpcode() == ISD::ADD) {
8209 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8212 AM.BaseOffs = Offset->getSExtValue();
8216 } else if (N->getOpcode() == ISD::SUB) {
8217 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8220 AM.BaseOffs = -Offset->getSExtValue();
8227 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8230 /// Try turning a load/store into a pre-indexed load/store when the base
8231 /// pointer is an add or subtract and it has other uses besides the load/store.
8232 /// After the transformation, the new indexed load/store has effectively folded
8233 /// the add/subtract in and all of its other uses are redirected to the
8235 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8236 if (Level < AfterLegalizeDAG)
8242 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8243 if (LD->isIndexed())
8245 VT = LD->getMemoryVT();
8246 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8247 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8249 Ptr = LD->getBasePtr();
8250 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8251 if (ST->isIndexed())
8253 VT = ST->getMemoryVT();
8254 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8255 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8257 Ptr = ST->getBasePtr();
8263 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8264 // out. There is no reason to make this a preinc/predec.
8265 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8266 Ptr.getNode()->hasOneUse())
8269 // Ask the target to do addressing mode selection.
8272 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8273 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8276 // Backends without true r+i pre-indexed forms may need to pass a
8277 // constant base with a variable offset so that constant coercion
8278 // will work with the patterns in canonical form.
8279 bool Swapped = false;
8280 if (isa<ConstantSDNode>(BasePtr)) {
8281 std::swap(BasePtr, Offset);
8285 // Don't create a indexed load / store with zero offset.
8286 if (isa<ConstantSDNode>(Offset) &&
8287 cast<ConstantSDNode>(Offset)->isNullValue())
8290 // Try turning it into a pre-indexed load / store except when:
8291 // 1) The new base ptr is a frame index.
8292 // 2) If N is a store and the new base ptr is either the same as or is a
8293 // predecessor of the value being stored.
8294 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8295 // that would create a cycle.
8296 // 4) All uses are load / store ops that use it as old base ptr.
8298 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8299 // (plus the implicit offset) to a register to preinc anyway.
8300 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8305 SDValue Val = cast<StoreSDNode>(N)->getValue();
8306 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8310 // If the offset is a constant, there may be other adds of constants that
8311 // can be folded with this one. We should do this to avoid having to keep
8312 // a copy of the original base pointer.
8313 SmallVector<SDNode *, 16> OtherUses;
8314 if (isa<ConstantSDNode>(Offset))
8315 for (SDNode *Use : BasePtr.getNode()->uses()) {
8316 if (Use == Ptr.getNode())
8319 if (Use->isPredecessorOf(N))
8322 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8327 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8328 if (Op1.getNode() == BasePtr.getNode())
8329 std::swap(Op0, Op1);
8330 assert(Op0.getNode() == BasePtr.getNode() &&
8331 "Use of ADD/SUB but not an operand");
8333 if (!isa<ConstantSDNode>(Op1)) {
8338 // FIXME: In some cases, we can be smarter about this.
8339 if (Op1.getValueType() != Offset.getValueType()) {
8344 OtherUses.push_back(Use);
8348 std::swap(BasePtr, Offset);
8350 // Now check for #3 and #4.
8351 bool RealUse = false;
8353 // Caches for hasPredecessorHelper
8354 SmallPtrSet<const SDNode *, 32> Visited;
8355 SmallVector<const SDNode *, 16> Worklist;
8357 for (SDNode *Use : Ptr.getNode()->uses()) {
8360 if (N->hasPredecessorHelper(Use, Visited, Worklist))
8363 // If Ptr may be folded in addressing mode of other use, then it's
8364 // not profitable to do this transformation.
8365 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8374 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8375 BasePtr, Offset, AM);
8377 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8378 BasePtr, Offset, AM);
8381 DEBUG(dbgs() << "\nReplacing.4 ";
8383 dbgs() << "\nWith: ";
8384 Result.getNode()->dump(&DAG);
8386 WorklistRemover DeadNodes(*this);
8388 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8389 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8391 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8394 // Finally, since the node is now dead, remove it from the graph.
8395 deleteAndRecombine(N);
8398 std::swap(BasePtr, Offset);
8400 // Replace other uses of BasePtr that can be updated to use Ptr
8401 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8402 unsigned OffsetIdx = 1;
8403 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8405 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8406 BasePtr.getNode() && "Expected BasePtr operand");
8408 // We need to replace ptr0 in the following expression:
8409 // x0 * offset0 + y0 * ptr0 = t0
8411 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8413 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8414 // indexed load/store and the expresion that needs to be re-written.
8416 // Therefore, we have:
8417 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8419 ConstantSDNode *CN =
8420 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8422 APInt Offset0 = CN->getAPIntValue();
8423 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8425 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8426 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8427 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8428 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8430 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8432 APInt CNV = Offset0;
8433 if (X0 < 0) CNV = -CNV;
8434 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8435 else CNV = CNV - Offset1;
8437 // We can now generate the new expression.
8438 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8439 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8441 SDValue NewUse = DAG.getNode(Opcode,
8442 SDLoc(OtherUses[i]),
8443 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8444 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8445 deleteAndRecombine(OtherUses[i]);
8448 // Replace the uses of Ptr with uses of the updated base value.
8449 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8450 deleteAndRecombine(Ptr.getNode());
8455 /// Try to combine a load/store with a add/sub of the base pointer node into a
8456 /// post-indexed load/store. The transformation folded the add/subtract into the
8457 /// new indexed load/store effectively and all of its uses are redirected to the
8459 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8460 if (Level < AfterLegalizeDAG)
8466 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8467 if (LD->isIndexed())
8469 VT = LD->getMemoryVT();
8470 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8471 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8473 Ptr = LD->getBasePtr();
8474 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8475 if (ST->isIndexed())
8477 VT = ST->getMemoryVT();
8478 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8479 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8481 Ptr = ST->getBasePtr();
8487 if (Ptr.getNode()->hasOneUse())
8490 for (SDNode *Op : Ptr.getNode()->uses()) {
8492 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8497 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8498 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8499 // Don't create a indexed load / store with zero offset.
8500 if (isa<ConstantSDNode>(Offset) &&
8501 cast<ConstantSDNode>(Offset)->isNullValue())
8504 // Try turning it into a post-indexed load / store except when
8505 // 1) All uses are load / store ops that use it as base ptr (and
8506 // it may be folded as addressing mmode).
8507 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8508 // nor a successor of N. Otherwise, if Op is folded that would
8511 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8515 bool TryNext = false;
8516 for (SDNode *Use : BasePtr.getNode()->uses()) {
8517 if (Use == Ptr.getNode())
8520 // If all the uses are load / store addresses, then don't do the
8522 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8523 bool RealUse = false;
8524 for (SDNode *UseUse : Use->uses()) {
8525 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8540 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8541 SDValue Result = isLoad
8542 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8543 BasePtr, Offset, AM)
8544 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8545 BasePtr, Offset, AM);
8548 DEBUG(dbgs() << "\nReplacing.5 ";
8550 dbgs() << "\nWith: ";
8551 Result.getNode()->dump(&DAG);
8553 WorklistRemover DeadNodes(*this);
8555 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8556 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8558 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8561 // Finally, since the node is now dead, remove it from the graph.
8562 deleteAndRecombine(N);
8564 // Replace the uses of Use with uses of the updated base value.
8565 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8566 Result.getValue(isLoad ? 1 : 0));
8567 deleteAndRecombine(Op);
8576 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8577 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8578 ISD::MemIndexedMode AM = LD->getAddressingMode();
8579 assert(AM != ISD::UNINDEXED);
8580 SDValue BP = LD->getOperand(1);
8581 SDValue Inc = LD->getOperand(2);
8583 // Some backends use TargetConstants for load offsets, but don't expect
8584 // TargetConstants in general ADD nodes. We can convert these constants into
8585 // regular Constants (if the constant is not opaque).
8586 assert((Inc.getOpcode() != ISD::TargetConstant ||
8587 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8588 "Cannot split out indexing using opaque target constants");
8589 if (Inc.getOpcode() == ISD::TargetConstant) {
8590 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8591 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8592 ConstInc->getValueType(0));
8596 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8597 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8600 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8601 LoadSDNode *LD = cast<LoadSDNode>(N);
8602 SDValue Chain = LD->getChain();
8603 SDValue Ptr = LD->getBasePtr();
8605 // If load is not volatile and there are no uses of the loaded value (and
8606 // the updated indexed value in case of indexed loads), change uses of the
8607 // chain value into uses of the chain input (i.e. delete the dead load).
8608 if (!LD->isVolatile()) {
8609 if (N->getValueType(1) == MVT::Other) {
8611 if (!N->hasAnyUseOfValue(0)) {
8612 // It's not safe to use the two value CombineTo variant here. e.g.
8613 // v1, chain2 = load chain1, loc
8614 // v2, chain3 = load chain2, loc
8616 // Now we replace use of chain2 with chain1. This makes the second load
8617 // isomorphic to the one we are deleting, and thus makes this load live.
8618 DEBUG(dbgs() << "\nReplacing.6 ";
8620 dbgs() << "\nWith chain: ";
8621 Chain.getNode()->dump(&DAG);
8623 WorklistRemover DeadNodes(*this);
8624 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8627 deleteAndRecombine(N);
8629 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8633 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8635 // If this load has an opaque TargetConstant offset, then we cannot split
8636 // the indexing into an add/sub directly (that TargetConstant may not be
8637 // valid for a different type of node, and we cannot convert an opaque
8638 // target constant into a regular constant).
8639 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8640 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8642 if (!N->hasAnyUseOfValue(0) &&
8643 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8644 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8646 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8647 Index = SplitIndexingFromLoad(LD);
8648 // Try to fold the base pointer arithmetic into subsequent loads and
8650 AddUsersToWorklist(N);
8652 Index = DAG.getUNDEF(N->getValueType(1));
8653 DEBUG(dbgs() << "\nReplacing.7 ";
8655 dbgs() << "\nWith: ";
8656 Undef.getNode()->dump(&DAG);
8657 dbgs() << " and 2 other values\n");
8658 WorklistRemover DeadNodes(*this);
8659 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8660 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8661 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8662 deleteAndRecombine(N);
8663 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8668 // If this load is directly stored, replace the load value with the stored
8670 // TODO: Handle store large -> read small portion.
8671 // TODO: Handle TRUNCSTORE/LOADEXT
8672 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8673 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8674 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8675 if (PrevST->getBasePtr() == Ptr &&
8676 PrevST->getValue().getValueType() == N->getValueType(0))
8677 return CombineTo(N, Chain.getOperand(1), Chain);
8681 // Try to infer better alignment information than the load already has.
8682 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8683 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8684 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8686 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8687 LD->getValueType(0),
8688 Chain, Ptr, LD->getPointerInfo(),
8690 LD->isVolatile(), LD->isNonTemporal(),
8691 LD->isInvariant(), Align, LD->getAAInfo());
8692 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8697 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8698 : DAG.getSubtarget().useAA();
8700 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8701 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8704 if (UseAA && LD->isUnindexed()) {
8705 // Walk up chain skipping non-aliasing memory nodes.
8706 SDValue BetterChain = FindBetterChain(N, Chain);
8708 // If there is a better chain.
8709 if (Chain != BetterChain) {
8712 // Replace the chain to void dependency.
8713 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8714 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8715 BetterChain, Ptr, LD->getMemOperand());
8717 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8718 LD->getValueType(0),
8719 BetterChain, Ptr, LD->getMemoryVT(),
8720 LD->getMemOperand());
8723 // Create token factor to keep old chain connected.
8724 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8725 MVT::Other, Chain, ReplLoad.getValue(1));
8727 // Make sure the new and old chains are cleaned up.
8728 AddToWorklist(Token.getNode());
8730 // Replace uses with load result and token factor. Don't add users
8732 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8736 // Try transforming N to an indexed load.
8737 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8738 return SDValue(N, 0);
8740 // Try to slice up N to more direct loads if the slices are mapped to
8741 // different register banks or pairing can take place.
8743 return SDValue(N, 0);
8749 /// \brief Helper structure used to slice a load in smaller loads.
8750 /// Basically a slice is obtained from the following sequence:
8751 /// Origin = load Ty1, Base
8752 /// Shift = srl Ty1 Origin, CstTy Amount
8753 /// Inst = trunc Shift to Ty2
8755 /// Then, it will be rewriten into:
8756 /// Slice = load SliceTy, Base + SliceOffset
8757 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8759 /// SliceTy is deduced from the number of bits that are actually used to
8761 struct LoadedSlice {
8762 /// \brief Helper structure used to compute the cost of a slice.
8764 /// Are we optimizing for code size.
8769 unsigned CrossRegisterBanksCopies;
8773 Cost(bool ForCodeSize = false)
8774 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8775 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8777 /// \brief Get the cost of one isolated slice.
8778 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8779 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8780 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8781 EVT TruncType = LS.Inst->getValueType(0);
8782 EVT LoadedType = LS.getLoadedType();
8783 if (TruncType != LoadedType &&
8784 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8788 /// \brief Account for slicing gain in the current cost.
8789 /// Slicing provide a few gains like removing a shift or a
8790 /// truncate. This method allows to grow the cost of the original
8791 /// load with the gain from this slice.
8792 void addSliceGain(const LoadedSlice &LS) {
8793 // Each slice saves a truncate.
8794 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8795 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8796 LS.Inst->getOperand(0).getValueType()))
8798 // If there is a shift amount, this slice gets rid of it.
8801 // If this slice can merge a cross register bank copy, account for it.
8802 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8803 ++CrossRegisterBanksCopies;
8806 Cost &operator+=(const Cost &RHS) {
8808 Truncates += RHS.Truncates;
8809 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8815 bool operator==(const Cost &RHS) const {
8816 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8817 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8818 ZExts == RHS.ZExts && Shift == RHS.Shift;
8821 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8823 bool operator<(const Cost &RHS) const {
8824 // Assume cross register banks copies are as expensive as loads.
8825 // FIXME: Do we want some more target hooks?
8826 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8827 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8828 // Unless we are optimizing for code size, consider the
8829 // expensive operation first.
8830 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8831 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8832 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8833 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8836 bool operator>(const Cost &RHS) const { return RHS < *this; }
8838 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8840 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8842 // The last instruction that represent the slice. This should be a
8843 // truncate instruction.
8845 // The original load instruction.
8847 // The right shift amount in bits from the original load.
8849 // The DAG from which Origin came from.
8850 // This is used to get some contextual information about legal types, etc.
8853 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8854 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8855 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8857 LoadedSlice(const LoadedSlice &LS)
8858 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8860 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8861 /// \return Result is \p BitWidth and has used bits set to 1 and
8862 /// not used bits set to 0.
8863 APInt getUsedBits() const {
8864 // Reproduce the trunc(lshr) sequence:
8865 // - Start from the truncated value.
8866 // - Zero extend to the desired bit width.
8868 assert(Origin && "No original load to compare against.");
8869 unsigned BitWidth = Origin->getValueSizeInBits(0);
8870 assert(Inst && "This slice is not bound to an instruction");
8871 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8872 "Extracted slice is bigger than the whole type!");
8873 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8874 UsedBits.setAllBits();
8875 UsedBits = UsedBits.zext(BitWidth);
8880 /// \brief Get the size of the slice to be loaded in bytes.
8881 unsigned getLoadedSize() const {
8882 unsigned SliceSize = getUsedBits().countPopulation();
8883 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8884 return SliceSize / 8;
8887 /// \brief Get the type that will be loaded for this slice.
8888 /// Note: This may not be the final type for the slice.
8889 EVT getLoadedType() const {
8890 assert(DAG && "Missing context");
8891 LLVMContext &Ctxt = *DAG->getContext();
8892 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8895 /// \brief Get the alignment of the load used for this slice.
8896 unsigned getAlignment() const {
8897 unsigned Alignment = Origin->getAlignment();
8898 unsigned Offset = getOffsetFromBase();
8900 Alignment = MinAlign(Alignment, Alignment + Offset);
8904 /// \brief Check if this slice can be rewritten with legal operations.
8905 bool isLegal() const {
8906 // An invalid slice is not legal.
8907 if (!Origin || !Inst || !DAG)
8910 // Offsets are for indexed load only, we do not handle that.
8911 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8914 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8916 // Check that the type is legal.
8917 EVT SliceType = getLoadedType();
8918 if (!TLI.isTypeLegal(SliceType))
8921 // Check that the load is legal for this type.
8922 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8925 // Check that the offset can be computed.
8926 // 1. Check its type.
8927 EVT PtrType = Origin->getBasePtr().getValueType();
8928 if (PtrType == MVT::Untyped || PtrType.isExtended())
8931 // 2. Check that it fits in the immediate.
8932 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8935 // 3. Check that the computation is legal.
8936 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8939 // Check that the zext is legal if it needs one.
8940 EVT TruncateType = Inst->getValueType(0);
8941 if (TruncateType != SliceType &&
8942 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8948 /// \brief Get the offset in bytes of this slice in the original chunk of
8950 /// \pre DAG != nullptr.
8951 uint64_t getOffsetFromBase() const {
8952 assert(DAG && "Missing context.");
8954 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8955 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8956 uint64_t Offset = Shift / 8;
8957 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8958 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8959 "The size of the original loaded type is not a multiple of a"
8961 // If Offset is bigger than TySizeInBytes, it means we are loading all
8962 // zeros. This should have been optimized before in the process.
8963 assert(TySizeInBytes > Offset &&
8964 "Invalid shift amount for given loaded size");
8966 Offset = TySizeInBytes - Offset - getLoadedSize();
8970 /// \brief Generate the sequence of instructions to load the slice
8971 /// represented by this object and redirect the uses of this slice to
8972 /// this new sequence of instructions.
8973 /// \pre this->Inst && this->Origin are valid Instructions and this
8974 /// object passed the legal check: LoadedSlice::isLegal returned true.
8975 /// \return The last instruction of the sequence used to load the slice.
8976 SDValue loadSlice() const {
8977 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8978 const SDValue &OldBaseAddr = Origin->getBasePtr();
8979 SDValue BaseAddr = OldBaseAddr;
8980 // Get the offset in that chunk of bytes w.r.t. the endianess.
8981 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8982 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8984 // BaseAddr = BaseAddr + Offset.
8985 EVT ArithType = BaseAddr.getValueType();
8986 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8987 DAG->getConstant(Offset, ArithType));
8990 // Create the type of the loaded slice according to its size.
8991 EVT SliceType = getLoadedType();
8993 // Create the load for the slice.
8994 SDValue LastInst = DAG->getLoad(
8995 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8996 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8997 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8998 // If the final type is not the same as the loaded type, this means that
8999 // we have to pad with zero. Create a zero extend for that.
9000 EVT FinalType = Inst->getValueType(0);
9001 if (SliceType != FinalType)
9003 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9007 /// \brief Check if this slice can be merged with an expensive cross register
9008 /// bank copy. E.g.,
9010 /// f = bitcast i32 i to float
9011 bool canMergeExpensiveCrossRegisterBankCopy() const {
9012 if (!Inst || !Inst->hasOneUse())
9014 SDNode *Use = *Inst->use_begin();
9015 if (Use->getOpcode() != ISD::BITCAST)
9017 assert(DAG && "Missing context");
9018 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9019 EVT ResVT = Use->getValueType(0);
9020 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9021 const TargetRegisterClass *ArgRC =
9022 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9023 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9026 // At this point, we know that we perform a cross-register-bank copy.
9027 // Check if it is expensive.
9028 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9029 // Assume bitcasts are cheap, unless both register classes do not
9030 // explicitly share a common sub class.
9031 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9034 // Check if it will be merged with the load.
9035 // 1. Check the alignment constraint.
9036 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9037 ResVT.getTypeForEVT(*DAG->getContext()));
9039 if (RequiredAlignment > getAlignment())
9042 // 2. Check that the load is a legal operation for that type.
9043 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9046 // 3. Check that we do not have a zext in the way.
9047 if (Inst->getValueType(0) != getLoadedType())
9055 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9056 /// \p UsedBits looks like 0..0 1..1 0..0.
9057 static bool areUsedBitsDense(const APInt &UsedBits) {
9058 // If all the bits are one, this is dense!
9059 if (UsedBits.isAllOnesValue())
9062 // Get rid of the unused bits on the right.
9063 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9064 // Get rid of the unused bits on the left.
9065 if (NarrowedUsedBits.countLeadingZeros())
9066 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9067 // Check that the chunk of bits is completely used.
9068 return NarrowedUsedBits.isAllOnesValue();
9071 /// \brief Check whether or not \p First and \p Second are next to each other
9072 /// in memory. This means that there is no hole between the bits loaded
9073 /// by \p First and the bits loaded by \p Second.
9074 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9075 const LoadedSlice &Second) {
9076 assert(First.Origin == Second.Origin && First.Origin &&
9077 "Unable to match different memory origins.");
9078 APInt UsedBits = First.getUsedBits();
9079 assert((UsedBits & Second.getUsedBits()) == 0 &&
9080 "Slices are not supposed to overlap.");
9081 UsedBits |= Second.getUsedBits();
9082 return areUsedBitsDense(UsedBits);
9085 /// \brief Adjust the \p GlobalLSCost according to the target
9086 /// paring capabilities and the layout of the slices.
9087 /// \pre \p GlobalLSCost should account for at least as many loads as
9088 /// there is in the slices in \p LoadedSlices.
9089 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9090 LoadedSlice::Cost &GlobalLSCost) {
9091 unsigned NumberOfSlices = LoadedSlices.size();
9092 // If there is less than 2 elements, no pairing is possible.
9093 if (NumberOfSlices < 2)
9096 // Sort the slices so that elements that are likely to be next to each
9097 // other in memory are next to each other in the list.
9098 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9099 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9100 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9101 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9103 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9104 // First (resp. Second) is the first (resp. Second) potentially candidate
9105 // to be placed in a paired load.
9106 const LoadedSlice *First = nullptr;
9107 const LoadedSlice *Second = nullptr;
9108 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9109 // Set the beginning of the pair.
9112 Second = &LoadedSlices[CurrSlice];
9114 // If First is NULL, it means we start a new pair.
9115 // Get to the next slice.
9119 EVT LoadedType = First->getLoadedType();
9121 // If the types of the slices are different, we cannot pair them.
9122 if (LoadedType != Second->getLoadedType())
9125 // Check if the target supplies paired loads for this type.
9126 unsigned RequiredAlignment = 0;
9127 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9128 // move to the next pair, this type is hopeless.
9132 // Check if we meet the alignment requirement.
9133 if (RequiredAlignment > First->getAlignment())
9136 // Check that both loads are next to each other in memory.
9137 if (!areSlicesNextToEachOther(*First, *Second))
9140 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9141 --GlobalLSCost.Loads;
9142 // Move to the next pair.
9147 /// \brief Check the profitability of all involved LoadedSlice.
9148 /// Currently, it is considered profitable if there is exactly two
9149 /// involved slices (1) which are (2) next to each other in memory, and
9150 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9152 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9153 /// the elements themselves.
9155 /// FIXME: When the cost model will be mature enough, we can relax
9156 /// constraints (1) and (2).
9157 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9158 const APInt &UsedBits, bool ForCodeSize) {
9159 unsigned NumberOfSlices = LoadedSlices.size();
9160 if (StressLoadSlicing)
9161 return NumberOfSlices > 1;
9164 if (NumberOfSlices != 2)
9168 if (!areUsedBitsDense(UsedBits))
9172 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9173 // The original code has one big load.
9175 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9176 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9177 // Accumulate the cost of all the slices.
9178 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9179 GlobalSlicingCost += SliceCost;
9181 // Account as cost in the original configuration the gain obtained
9182 // with the current slices.
9183 OrigCost.addSliceGain(LS);
9186 // If the target supports paired load, adjust the cost accordingly.
9187 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9188 return OrigCost > GlobalSlicingCost;
9191 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9192 /// operations, split it in the various pieces being extracted.
9194 /// This sort of thing is introduced by SROA.
9195 /// This slicing takes care not to insert overlapping loads.
9196 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9197 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9198 if (Level < AfterLegalizeDAG)
9201 LoadSDNode *LD = cast<LoadSDNode>(N);
9202 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9203 !LD->getValueType(0).isInteger())
9206 // Keep track of already used bits to detect overlapping values.
9207 // In that case, we will just abort the transformation.
9208 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9210 SmallVector<LoadedSlice, 4> LoadedSlices;
9212 // Check if this load is used as several smaller chunks of bits.
9213 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9214 // of computation for each trunc.
9215 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9216 UI != UIEnd; ++UI) {
9217 // Skip the uses of the chain.
9218 if (UI.getUse().getResNo() != 0)
9224 // Check if this is a trunc(lshr).
9225 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9226 isa<ConstantSDNode>(User->getOperand(1))) {
9227 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9228 User = *User->use_begin();
9231 // At this point, User is a Truncate, iff we encountered, trunc or
9233 if (User->getOpcode() != ISD::TRUNCATE)
9236 // The width of the type must be a power of 2 and greater than 8-bits.
9237 // Otherwise the load cannot be represented in LLVM IR.
9238 // Moreover, if we shifted with a non-8-bits multiple, the slice
9239 // will be across several bytes. We do not support that.
9240 unsigned Width = User->getValueSizeInBits(0);
9241 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9244 // Build the slice for this chain of computations.
9245 LoadedSlice LS(User, LD, Shift, &DAG);
9246 APInt CurrentUsedBits = LS.getUsedBits();
9248 // Check if this slice overlaps with another.
9249 if ((CurrentUsedBits & UsedBits) != 0)
9251 // Update the bits used globally.
9252 UsedBits |= CurrentUsedBits;
9254 // Check if the new slice would be legal.
9258 // Record the slice.
9259 LoadedSlices.push_back(LS);
9262 // Abort slicing if it does not seem to be profitable.
9263 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9268 // Rewrite each chain to use an independent load.
9269 // By construction, each chain can be represented by a unique load.
9271 // Prepare the argument for the new token factor for all the slices.
9272 SmallVector<SDValue, 8> ArgChains;
9273 for (SmallVectorImpl<LoadedSlice>::const_iterator
9274 LSIt = LoadedSlices.begin(),
9275 LSItEnd = LoadedSlices.end();
9276 LSIt != LSItEnd; ++LSIt) {
9277 SDValue SliceInst = LSIt->loadSlice();
9278 CombineTo(LSIt->Inst, SliceInst, true);
9279 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9280 SliceInst = SliceInst.getOperand(0);
9281 assert(SliceInst->getOpcode() == ISD::LOAD &&
9282 "It takes more than a zext to get to the loaded slice!!");
9283 ArgChains.push_back(SliceInst.getValue(1));
9286 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9288 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9292 /// Check to see if V is (and load (ptr), imm), where the load is having
9293 /// specific bytes cleared out. If so, return the byte size being masked out
9294 /// and the shift amount.
9295 static std::pair<unsigned, unsigned>
9296 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9297 std::pair<unsigned, unsigned> Result(0, 0);
9299 // Check for the structure we're looking for.
9300 if (V->getOpcode() != ISD::AND ||
9301 !isa<ConstantSDNode>(V->getOperand(1)) ||
9302 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9305 // Check the chain and pointer.
9306 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9307 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
9309 // The store should be chained directly to the load or be an operand of a
9311 if (LD == Chain.getNode())
9313 else if (Chain->getOpcode() != ISD::TokenFactor)
9314 return Result; // Fail.
9317 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9318 if (Chain->getOperand(i).getNode() == LD) {
9322 if (!isOk) return Result;
9325 // This only handles simple types.
9326 if (V.getValueType() != MVT::i16 &&
9327 V.getValueType() != MVT::i32 &&
9328 V.getValueType() != MVT::i64)
9331 // Check the constant mask. Invert it so that the bits being masked out are
9332 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9333 // follow the sign bit for uniformity.
9334 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9335 unsigned NotMaskLZ = countLeadingZeros(NotMask);
9336 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
9337 unsigned NotMaskTZ = countTrailingZeros(NotMask);
9338 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9339 if (NotMaskLZ == 64) return Result; // All zero mask.
9341 // See if we have a continuous run of bits. If so, we have 0*1+0*
9342 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9345 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9346 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9347 NotMaskLZ -= 64-V.getValueSizeInBits();
9349 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9350 switch (MaskedBytes) {
9354 default: return Result; // All one mask, or 5-byte mask.
9357 // Verify that the first bit starts at a multiple of mask so that the access
9358 // is aligned the same as the access width.
9359 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9361 Result.first = MaskedBytes;
9362 Result.second = NotMaskTZ/8;
9367 /// Check to see if IVal is something that provides a value as specified by
9368 /// MaskInfo. If so, replace the specified store with a narrower store of
9371 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9372 SDValue IVal, StoreSDNode *St,
9374 unsigned NumBytes = MaskInfo.first;
9375 unsigned ByteShift = MaskInfo.second;
9376 SelectionDAG &DAG = DC->getDAG();
9378 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9379 // that uses this. If not, this is not a replacement.
9380 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9381 ByteShift*8, (ByteShift+NumBytes)*8);
9382 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9384 // Check that it is legal on the target to do this. It is legal if the new
9385 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9387 MVT VT = MVT::getIntegerVT(NumBytes*8);
9388 if (!DC->isTypeLegal(VT))
9391 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9392 // shifted by ByteShift and truncated down to NumBytes.
9394 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9395 DAG.getConstant(ByteShift*8,
9396 DC->getShiftAmountTy(IVal.getValueType())));
9398 // Figure out the offset for the store and the alignment of the access.
9400 unsigned NewAlign = St->getAlignment();
9402 if (DAG.getTargetLoweringInfo().isLittleEndian())
9403 StOffset = ByteShift;
9405 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9407 SDValue Ptr = St->getBasePtr();
9409 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9410 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9411 NewAlign = MinAlign(NewAlign, StOffset);
9414 // Truncate down to the new size.
9415 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9418 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9419 St->getPointerInfo().getWithOffset(StOffset),
9420 false, false, NewAlign).getNode();
9424 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9425 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9426 /// narrowing the load and store if it would end up being a win for performance
9428 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9429 StoreSDNode *ST = cast<StoreSDNode>(N);
9430 if (ST->isVolatile())
9433 SDValue Chain = ST->getChain();
9434 SDValue Value = ST->getValue();
9435 SDValue Ptr = ST->getBasePtr();
9436 EVT VT = Value.getValueType();
9438 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9441 unsigned Opc = Value.getOpcode();
9443 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9444 // is a byte mask indicating a consecutive number of bytes, check to see if
9445 // Y is known to provide just those bytes. If so, we try to replace the
9446 // load + replace + store sequence with a single (narrower) store, which makes
9448 if (Opc == ISD::OR) {
9449 std::pair<unsigned, unsigned> MaskedLoad;
9450 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9451 if (MaskedLoad.first)
9452 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9453 Value.getOperand(1), ST,this))
9454 return SDValue(NewST, 0);
9456 // Or is commutative, so try swapping X and Y.
9457 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9458 if (MaskedLoad.first)
9459 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9460 Value.getOperand(0), ST,this))
9461 return SDValue(NewST, 0);
9464 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9465 Value.getOperand(1).getOpcode() != ISD::Constant)
9468 SDValue N0 = Value.getOperand(0);
9469 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9470 Chain == SDValue(N0.getNode(), 1)) {
9471 LoadSDNode *LD = cast<LoadSDNode>(N0);
9472 if (LD->getBasePtr() != Ptr ||
9473 LD->getPointerInfo().getAddrSpace() !=
9474 ST->getPointerInfo().getAddrSpace())
9477 // Find the type to narrow it the load / op / store to.
9478 SDValue N1 = Value.getOperand(1);
9479 unsigned BitWidth = N1.getValueSizeInBits();
9480 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9481 if (Opc == ISD::AND)
9482 Imm ^= APInt::getAllOnesValue(BitWidth);
9483 if (Imm == 0 || Imm.isAllOnesValue())
9485 unsigned ShAmt = Imm.countTrailingZeros();
9486 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9487 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9488 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9489 while (NewBW < BitWidth &&
9490 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9491 TLI.isNarrowingProfitable(VT, NewVT))) {
9492 NewBW = NextPowerOf2(NewBW);
9493 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9495 if (NewBW >= BitWidth)
9498 // If the lsb changed does not start at the type bitwidth boundary,
9499 // start at the previous one.
9501 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9502 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9503 std::min(BitWidth, ShAmt + NewBW));
9504 if ((Imm & Mask) == Imm) {
9505 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9506 if (Opc == ISD::AND)
9507 NewImm ^= APInt::getAllOnesValue(NewBW);
9508 uint64_t PtrOff = ShAmt / 8;
9509 // For big endian targets, we need to adjust the offset to the pointer to
9510 // load the correct bytes.
9511 if (TLI.isBigEndian())
9512 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9514 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9515 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9516 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9519 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9520 Ptr.getValueType(), Ptr,
9521 DAG.getConstant(PtrOff, Ptr.getValueType()));
9522 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9523 LD->getChain(), NewPtr,
9524 LD->getPointerInfo().getWithOffset(PtrOff),
9525 LD->isVolatile(), LD->isNonTemporal(),
9526 LD->isInvariant(), NewAlign,
9528 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9529 DAG.getConstant(NewImm, NewVT));
9530 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9532 ST->getPointerInfo().getWithOffset(PtrOff),
9533 false, false, NewAlign);
9535 AddToWorklist(NewPtr.getNode());
9536 AddToWorklist(NewLD.getNode());
9537 AddToWorklist(NewVal.getNode());
9538 WorklistRemover DeadNodes(*this);
9539 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9548 /// For a given floating point load / store pair, if the load value isn't used
9549 /// by any other operations, then consider transforming the pair to integer
9550 /// load / store operations if the target deems the transformation profitable.
9551 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9552 StoreSDNode *ST = cast<StoreSDNode>(N);
9553 SDValue Chain = ST->getChain();
9554 SDValue Value = ST->getValue();
9555 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9556 Value.hasOneUse() &&
9557 Chain == SDValue(Value.getNode(), 1)) {
9558 LoadSDNode *LD = cast<LoadSDNode>(Value);
9559 EVT VT = LD->getMemoryVT();
9560 if (!VT.isFloatingPoint() ||
9561 VT != ST->getMemoryVT() ||
9562 LD->isNonTemporal() ||
9563 ST->isNonTemporal() ||
9564 LD->getPointerInfo().getAddrSpace() != 0 ||
9565 ST->getPointerInfo().getAddrSpace() != 0)
9568 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9569 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9570 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9571 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9572 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9575 unsigned LDAlign = LD->getAlignment();
9576 unsigned STAlign = ST->getAlignment();
9577 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9578 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9579 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9582 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9583 LD->getChain(), LD->getBasePtr(),
9584 LD->getPointerInfo(),
9585 false, false, false, LDAlign);
9587 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9588 NewLD, ST->getBasePtr(),
9589 ST->getPointerInfo(),
9590 false, false, STAlign);
9592 AddToWorklist(NewLD.getNode());
9593 AddToWorklist(NewST.getNode());
9594 WorklistRemover DeadNodes(*this);
9595 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9603 /// Helper struct to parse and store a memory address as base + index + offset.
9604 /// We ignore sign extensions when it is safe to do so.
9605 /// The following two expressions are not equivalent. To differentiate we need
9606 /// to store whether there was a sign extension involved in the index
9608 /// (load (i64 add (i64 copyfromreg %c)
9609 /// (i64 signextend (add (i8 load %index)
9613 /// (load (i64 add (i64 copyfromreg %c)
9614 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9616 struct BaseIndexOffset {
9620 bool IsIndexSignExt;
9622 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9624 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9625 bool IsIndexSignExt) :
9626 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9628 bool equalBaseIndex(const BaseIndexOffset &Other) {
9629 return Other.Base == Base && Other.Index == Index &&
9630 Other.IsIndexSignExt == IsIndexSignExt;
9633 /// Parses tree in Ptr for base, index, offset addresses.
9634 static BaseIndexOffset match(SDValue Ptr) {
9635 bool IsIndexSignExt = false;
9637 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9638 // instruction, then it could be just the BASE or everything else we don't
9639 // know how to handle. Just use Ptr as BASE and give up.
9640 if (Ptr->getOpcode() != ISD::ADD)
9641 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9643 // We know that we have at least an ADD instruction. Try to pattern match
9644 // the simple case of BASE + OFFSET.
9645 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9646 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9647 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9651 // Inside a loop the current BASE pointer is calculated using an ADD and a
9652 // MUL instruction. In this case Ptr is the actual BASE pointer.
9653 // (i64 add (i64 %array_ptr)
9654 // (i64 mul (i64 %induction_var)
9655 // (i64 %element_size)))
9656 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9657 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9659 // Look at Base + Index + Offset cases.
9660 SDValue Base = Ptr->getOperand(0);
9661 SDValue IndexOffset = Ptr->getOperand(1);
9663 // Skip signextends.
9664 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9665 IndexOffset = IndexOffset->getOperand(0);
9666 IsIndexSignExt = true;
9669 // Either the case of Base + Index (no offset) or something else.
9670 if (IndexOffset->getOpcode() != ISD::ADD)
9671 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9673 // Now we have the case of Base + Index + offset.
9674 SDValue Index = IndexOffset->getOperand(0);
9675 SDValue Offset = IndexOffset->getOperand(1);
9677 if (!isa<ConstantSDNode>(Offset))
9678 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9680 // Ignore signextends.
9681 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9682 Index = Index->getOperand(0);
9683 IsIndexSignExt = true;
9684 } else IsIndexSignExt = false;
9686 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9687 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9691 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9692 /// is located in a sequence of memory operations connected by a chain.
9694 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9695 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9696 // Ptr to the mem node.
9697 LSBaseSDNode *MemNode;
9698 // Offset from the base ptr.
9699 int64_t OffsetFromBase;
9700 // What is the sequence number of this mem node.
9701 // Lowest mem operand in the DAG starts at zero.
9702 unsigned SequenceNum;
9705 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9706 EVT MemVT = St->getMemoryVT();
9707 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9708 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9709 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9711 // Don't merge vectors into wider inputs.
9712 if (MemVT.isVector() || !MemVT.isSimple())
9715 // Perform an early exit check. Do not bother looking at stored values that
9716 // are not constants or loads.
9717 SDValue StoredVal = St->getValue();
9718 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9719 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9723 // Only look at ends of store sequences.
9724 SDValue Chain = SDValue(St, 0);
9725 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9728 // This holds the base pointer, index, and the offset in bytes from the base
9730 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9732 // We must have a base and an offset.
9733 if (!BasePtr.Base.getNode())
9736 // Do not handle stores to undef base pointers.
9737 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9740 // Save the LoadSDNodes that we find in the chain.
9741 // We need to make sure that these nodes do not interfere with
9742 // any of the store nodes.
9743 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9745 // Save the StoreSDNodes that we find in the chain.
9746 SmallVector<MemOpLink, 8> StoreNodes;
9748 // Walk up the chain and look for nodes with offsets from the same
9749 // base pointer. Stop when reaching an instruction with a different kind
9750 // or instruction which has a different base pointer.
9752 StoreSDNode *Index = St;
9754 // If the chain has more than one use, then we can't reorder the mem ops.
9755 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9758 // Find the base pointer and offset for this memory node.
9759 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9761 // Check that the base pointer is the same as the original one.
9762 if (!Ptr.equalBaseIndex(BasePtr))
9765 // Check that the alignment is the same.
9766 if (Index->getAlignment() != St->getAlignment())
9769 // The memory operands must not be volatile.
9770 if (Index->isVolatile() || Index->isIndexed())
9774 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9775 if (St->isTruncatingStore())
9778 // The stored memory type must be the same.
9779 if (Index->getMemoryVT() != MemVT)
9782 // We do not allow unaligned stores because we want to prevent overriding
9784 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9787 // We found a potential memory operand to merge.
9788 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9790 // Find the next memory operand in the chain. If the next operand in the
9791 // chain is a store then move up and continue the scan with the next
9792 // memory operand. If the next operand is a load save it and use alias
9793 // information to check if it interferes with anything.
9794 SDNode *NextInChain = Index->getChain().getNode();
9796 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9797 // We found a store node. Use it for the next iteration.
9800 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9801 if (Ldn->isVolatile()) {
9806 // Save the load node for later. Continue the scan.
9807 AliasLoadNodes.push_back(Ldn);
9808 NextInChain = Ldn->getChain().getNode();
9817 // Check if there is anything to merge.
9818 if (StoreNodes.size() < 2)
9821 // Sort the memory operands according to their distance from the base pointer.
9822 std::sort(StoreNodes.begin(), StoreNodes.end(),
9823 [](MemOpLink LHS, MemOpLink RHS) {
9824 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9825 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9826 LHS.SequenceNum > RHS.SequenceNum);
9829 // Scan the memory operations on the chain and find the first non-consecutive
9830 // store memory address.
9831 unsigned LastConsecutiveStore = 0;
9832 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9833 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9835 // Check that the addresses are consecutive starting from the second
9836 // element in the list of stores.
9838 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9839 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9844 // Check if this store interferes with any of the loads that we found.
9845 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9846 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9850 // We found a load that alias with this store. Stop the sequence.
9854 // Mark this node as useful.
9855 LastConsecutiveStore = i;
9858 // The node with the lowest store address.
9859 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9861 // Store the constants into memory as one consecutive store.
9863 unsigned LastLegalType = 0;
9864 unsigned LastLegalVectorType = 0;
9865 bool NonZero = false;
9866 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9867 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9868 SDValue StoredVal = St->getValue();
9870 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9871 NonZero |= !C->isNullValue();
9872 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9873 NonZero |= !C->getConstantFPValue()->isNullValue();
9879 // Find a legal type for the constant store.
9880 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9881 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9882 if (TLI.isTypeLegal(StoreTy))
9883 LastLegalType = i+1;
9884 // Or check whether a truncstore is legal.
9885 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9886 TargetLowering::TypePromoteInteger) {
9887 EVT LegalizedStoredValueTy =
9888 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9889 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9890 LastLegalType = i+1;
9893 // Find a legal type for the vector store.
9894 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9895 if (TLI.isTypeLegal(Ty))
9896 LastLegalVectorType = i + 1;
9899 // We only use vectors if the constant is known to be zero and the
9900 // function is not marked with the noimplicitfloat attribute.
9901 if (NonZero || NoVectors)
9902 LastLegalVectorType = 0;
9904 // Check if we found a legal integer type to store.
9905 if (LastLegalType == 0 && LastLegalVectorType == 0)
9908 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9909 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9911 // Make sure we have something to merge.
9915 unsigned EarliestNodeUsed = 0;
9916 for (unsigned i=0; i < NumElem; ++i) {
9917 // Find a chain for the new wide-store operand. Notice that some
9918 // of the store nodes that we found may not be selected for inclusion
9919 // in the wide store. The chain we use needs to be the chain of the
9920 // earliest store node which is *used* and replaced by the wide store.
9921 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9922 EarliestNodeUsed = i;
9925 // The earliest Node in the DAG.
9926 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9927 SDLoc DL(StoreNodes[0].MemNode);
9931 // Find a legal type for the vector store.
9932 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9933 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9934 StoredVal = DAG.getConstant(0, Ty);
9936 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9937 APInt StoreInt(StoreBW, 0);
9939 // Construct a single integer constant which is made of the smaller
9941 bool IsLE = TLI.isLittleEndian();
9942 for (unsigned i = 0; i < NumElem ; ++i) {
9943 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9944 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9945 SDValue Val = St->getValue();
9946 StoreInt<<=ElementSizeBytes*8;
9947 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9948 StoreInt|=C->getAPIntValue().zext(StoreBW);
9949 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9950 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9952 llvm_unreachable("Invalid constant element type");
9956 // Create the new Load and Store operations.
9957 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9958 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9961 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9962 FirstInChain->getBasePtr(),
9963 FirstInChain->getPointerInfo(),
9965 FirstInChain->getAlignment());
9967 // Replace the first store with the new store
9968 CombineTo(EarliestOp, NewStore);
9969 // Erase all other stores.
9970 for (unsigned i = 0; i < NumElem ; ++i) {
9971 if (StoreNodes[i].MemNode == EarliestOp)
9973 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9974 // ReplaceAllUsesWith will replace all uses that existed when it was
9975 // called, but graph optimizations may cause new ones to appear. For
9976 // example, the case in pr14333 looks like
9978 // St's chain -> St -> another store -> X
9980 // And the only difference from St to the other store is the chain.
9981 // When we change it's chain to be St's chain they become identical,
9982 // get CSEed and the net result is that X is now a use of St.
9983 // Since we know that St is redundant, just iterate.
9984 while (!St->use_empty())
9985 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9986 deleteAndRecombine(St);
9992 // Below we handle the case of multiple consecutive stores that
9993 // come from multiple consecutive loads. We merge them into a single
9994 // wide load and a single wide store.
9996 // Look for load nodes which are used by the stored values.
9997 SmallVector<MemOpLink, 8> LoadNodes;
9999 // Find acceptable loads. Loads need to have the same chain (token factor),
10000 // must not be zext, volatile, indexed, and they must be consecutive.
10001 BaseIndexOffset LdBasePtr;
10002 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10003 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10004 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10007 // Loads must only have one use.
10008 if (!Ld->hasNUsesOfValue(1, 0))
10011 // Check that the alignment is the same as the stores.
10012 if (Ld->getAlignment() != St->getAlignment())
10015 // The memory operands must not be volatile.
10016 if (Ld->isVolatile() || Ld->isIndexed())
10019 // We do not accept ext loads.
10020 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10023 // The stored memory type must be the same.
10024 if (Ld->getMemoryVT() != MemVT)
10027 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10028 // If this is not the first ptr that we check.
10029 if (LdBasePtr.Base.getNode()) {
10030 // The base ptr must be the same.
10031 if (!LdPtr.equalBaseIndex(LdBasePtr))
10034 // Check that all other base pointers are the same as this one.
10038 // We found a potential memory operand to merge.
10039 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10042 if (LoadNodes.size() < 2)
10045 // If we have load/store pair instructions and we only have two values,
10047 unsigned RequiredAlignment;
10048 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10049 St->getAlignment() >= RequiredAlignment)
10052 // Scan the memory operations on the chain and find the first non-consecutive
10053 // load memory address. These variables hold the index in the store node
10055 unsigned LastConsecutiveLoad = 0;
10056 // This variable refers to the size and not index in the array.
10057 unsigned LastLegalVectorType = 0;
10058 unsigned LastLegalIntegerType = 0;
10059 StartAddress = LoadNodes[0].OffsetFromBase;
10060 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10061 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10062 // All loads much share the same chain.
10063 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10066 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10067 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10069 LastConsecutiveLoad = i;
10071 // Find a legal type for the vector store.
10072 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10073 if (TLI.isTypeLegal(StoreTy))
10074 LastLegalVectorType = i + 1;
10076 // Find a legal type for the integer store.
10077 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10078 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10079 if (TLI.isTypeLegal(StoreTy))
10080 LastLegalIntegerType = i + 1;
10081 // Or check whether a truncstore and extload is legal.
10082 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10083 TargetLowering::TypePromoteInteger) {
10084 EVT LegalizedStoredValueTy =
10085 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10086 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10087 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10088 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10089 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10090 LastLegalIntegerType = i+1;
10094 // Only use vector types if the vector type is larger than the integer type.
10095 // If they are the same, use integers.
10096 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10097 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10099 // We add +1 here because the LastXXX variables refer to location while
10100 // the NumElem refers to array/index size.
10101 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10102 NumElem = std::min(LastLegalType, NumElem);
10107 // The earliest Node in the DAG.
10108 unsigned EarliestNodeUsed = 0;
10109 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10110 for (unsigned i=1; i<NumElem; ++i) {
10111 // Find a chain for the new wide-store operand. Notice that some
10112 // of the store nodes that we found may not be selected for inclusion
10113 // in the wide store. The chain we use needs to be the chain of the
10114 // earliest store node which is *used* and replaced by the wide store.
10115 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10116 EarliestNodeUsed = i;
10119 // Find if it is better to use vectors or integers to load and store
10123 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10125 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10126 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10129 SDLoc LoadDL(LoadNodes[0].MemNode);
10130 SDLoc StoreDL(StoreNodes[0].MemNode);
10132 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10133 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10134 FirstLoad->getChain(),
10135 FirstLoad->getBasePtr(),
10136 FirstLoad->getPointerInfo(),
10137 false, false, false,
10138 FirstLoad->getAlignment());
10140 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10141 FirstInChain->getBasePtr(),
10142 FirstInChain->getPointerInfo(), false, false,
10143 FirstInChain->getAlignment());
10145 // Replace one of the loads with the new load.
10146 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10147 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10148 SDValue(NewLoad.getNode(), 1));
10150 // Remove the rest of the load chains.
10151 for (unsigned i = 1; i < NumElem ; ++i) {
10152 // Replace all chain users of the old load nodes with the chain of the new
10154 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10155 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10158 // Replace the first store with the new store.
10159 CombineTo(EarliestOp, NewStore);
10160 // Erase all other stores.
10161 for (unsigned i = 0; i < NumElem ; ++i) {
10162 // Remove all Store nodes.
10163 if (StoreNodes[i].MemNode == EarliestOp)
10165 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10166 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10167 deleteAndRecombine(St);
10173 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10174 StoreSDNode *ST = cast<StoreSDNode>(N);
10175 SDValue Chain = ST->getChain();
10176 SDValue Value = ST->getValue();
10177 SDValue Ptr = ST->getBasePtr();
10179 // If this is a store of a bit convert, store the input value if the
10180 // resultant store does not need a higher alignment than the original.
10181 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10182 ST->isUnindexed()) {
10183 unsigned OrigAlign = ST->getAlignment();
10184 EVT SVT = Value.getOperand(0).getValueType();
10185 unsigned Align = TLI.getDataLayout()->
10186 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10187 if (Align <= OrigAlign &&
10188 ((!LegalOperations && !ST->isVolatile()) ||
10189 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10190 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10191 Ptr, ST->getPointerInfo(), ST->isVolatile(),
10192 ST->isNonTemporal(), OrigAlign,
10196 // Turn 'store undef, Ptr' -> nothing.
10197 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10200 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10201 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10202 // NOTE: If the original store is volatile, this transform must not increase
10203 // the number of stores. For example, on x86-32 an f64 can be stored in one
10204 // processor operation but an i64 (which is not legal) requires two. So the
10205 // transform should not be done in this case.
10206 if (Value.getOpcode() != ISD::TargetConstantFP) {
10208 switch (CFP->getSimpleValueType(0).SimpleTy) {
10209 default: llvm_unreachable("Unknown FP type");
10210 case MVT::f16: // We don't do this for these yet.
10216 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10217 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10218 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10219 bitcastToAPInt().getZExtValue(), MVT::i32);
10220 return DAG.getStore(Chain, SDLoc(N), Tmp,
10221 Ptr, ST->getMemOperand());
10225 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10226 !ST->isVolatile()) ||
10227 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10228 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10229 getZExtValue(), MVT::i64);
10230 return DAG.getStore(Chain, SDLoc(N), Tmp,
10231 Ptr, ST->getMemOperand());
10234 if (!ST->isVolatile() &&
10235 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10236 // Many FP stores are not made apparent until after legalize, e.g. for
10237 // argument passing. Since this is so common, custom legalize the
10238 // 64-bit integer store into two 32-bit stores.
10239 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10240 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10241 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10242 if (TLI.isBigEndian()) std::swap(Lo, Hi);
10244 unsigned Alignment = ST->getAlignment();
10245 bool isVolatile = ST->isVolatile();
10246 bool isNonTemporal = ST->isNonTemporal();
10247 AAMDNodes AAInfo = ST->getAAInfo();
10249 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10250 Ptr, ST->getPointerInfo(),
10251 isVolatile, isNonTemporal,
10252 ST->getAlignment(), AAInfo);
10253 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10254 DAG.getConstant(4, Ptr.getValueType()));
10255 Alignment = MinAlign(Alignment, 4U);
10256 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10257 Ptr, ST->getPointerInfo().getWithOffset(4),
10258 isVolatile, isNonTemporal,
10259 Alignment, AAInfo);
10260 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10269 // Try to infer better alignment information than the store already has.
10270 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10271 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10272 if (Align > ST->getAlignment())
10273 return DAG.getTruncStore(Chain, SDLoc(N), Value,
10274 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10275 ST->isVolatile(), ST->isNonTemporal(), Align,
10280 // Try transforming a pair floating point load / store ops to integer
10281 // load / store ops.
10282 SDValue NewST = TransformFPLoadStorePair(N);
10283 if (NewST.getNode())
10286 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10287 : DAG.getSubtarget().useAA();
10289 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10290 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10293 if (UseAA && ST->isUnindexed()) {
10294 // Walk up chain skipping non-aliasing memory nodes.
10295 SDValue BetterChain = FindBetterChain(N, Chain);
10297 // If there is a better chain.
10298 if (Chain != BetterChain) {
10301 // Replace the chain to avoid dependency.
10302 if (ST->isTruncatingStore()) {
10303 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10304 ST->getMemoryVT(), ST->getMemOperand());
10306 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10307 ST->getMemOperand());
10310 // Create token to keep both nodes around.
10311 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10312 MVT::Other, Chain, ReplStore);
10314 // Make sure the new and old chains are cleaned up.
10315 AddToWorklist(Token.getNode());
10317 // Don't add users to work list.
10318 return CombineTo(N, Token, false);
10322 // Try transforming N to an indexed store.
10323 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10324 return SDValue(N, 0);
10326 // FIXME: is there such a thing as a truncating indexed store?
10327 if (ST->isTruncatingStore() && ST->isUnindexed() &&
10328 Value.getValueType().isInteger()) {
10329 // See if we can simplify the input to this truncstore with knowledge that
10330 // only the low bits are being used. For example:
10331 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
10333 GetDemandedBits(Value,
10334 APInt::getLowBitsSet(
10335 Value.getValueType().getScalarType().getSizeInBits(),
10336 ST->getMemoryVT().getScalarType().getSizeInBits()));
10337 AddToWorklist(Value.getNode());
10338 if (Shorter.getNode())
10339 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10340 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10342 // Otherwise, see if we can simplify the operation with
10343 // SimplifyDemandedBits, which only works if the value has a single use.
10344 if (SimplifyDemandedBits(Value,
10345 APInt::getLowBitsSet(
10346 Value.getValueType().getScalarType().getSizeInBits(),
10347 ST->getMemoryVT().getScalarType().getSizeInBits())))
10348 return SDValue(N, 0);
10351 // If this is a load followed by a store to the same location, then the store
10353 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10354 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10355 ST->isUnindexed() && !ST->isVolatile() &&
10356 // There can't be any side effects between the load and store, such as
10357 // a call or store.
10358 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10359 // The store is dead, remove it.
10364 // If this is a store followed by a store with the same value to the same
10365 // location, then the store is dead/noop.
10366 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10367 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10368 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10369 ST1->isUnindexed() && !ST1->isVolatile()) {
10370 // The store is dead, remove it.
10375 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10376 // truncating store. We can do this even if this is already a truncstore.
10377 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10378 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10379 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10380 ST->getMemoryVT())) {
10381 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10382 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10385 // Only perform this optimization before the types are legal, because we
10386 // don't want to perform this optimization on every DAGCombine invocation.
10388 bool EverChanged = false;
10391 // There can be multiple store sequences on the same chain.
10392 // Keep trying to merge store sequences until we are unable to do so
10393 // or until we merge the last store on the chain.
10394 bool Changed = MergeConsecutiveStores(ST);
10395 EverChanged |= Changed;
10396 if (!Changed) break;
10397 } while (ST->getOpcode() != ISD::DELETED_NODE);
10400 return SDValue(N, 0);
10403 return ReduceLoadOpStoreWidth(N);
10406 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10407 SDValue InVec = N->getOperand(0);
10408 SDValue InVal = N->getOperand(1);
10409 SDValue EltNo = N->getOperand(2);
10412 // If the inserted element is an UNDEF, just use the input vector.
10413 if (InVal.getOpcode() == ISD::UNDEF)
10416 EVT VT = InVec.getValueType();
10418 // If we can't generate a legal BUILD_VECTOR, exit
10419 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10422 // Check that we know which element is being inserted
10423 if (!isa<ConstantSDNode>(EltNo))
10425 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10427 // Canonicalize insert_vector_elt dag nodes.
10429 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10430 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10432 // Do this only if the child insert_vector node has one use; also
10433 // do this only if indices are both constants and Idx1 < Idx0.
10434 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10435 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10436 unsigned OtherElt =
10437 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10438 if (Elt < OtherElt) {
10440 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10441 InVec.getOperand(0), InVal, EltNo);
10442 AddToWorklist(NewOp.getNode());
10443 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10444 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10448 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10449 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10450 // vector elements.
10451 SmallVector<SDValue, 8> Ops;
10452 // Do not combine these two vectors if the output vector will not replace
10453 // the input vector.
10454 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10455 Ops.append(InVec.getNode()->op_begin(),
10456 InVec.getNode()->op_end());
10457 } else if (InVec.getOpcode() == ISD::UNDEF) {
10458 unsigned NElts = VT.getVectorNumElements();
10459 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10464 // Insert the element
10465 if (Elt < Ops.size()) {
10466 // All the operands of BUILD_VECTOR must have the same type;
10467 // we enforce that here.
10468 EVT OpVT = Ops[0].getValueType();
10469 if (InVal.getValueType() != OpVT)
10470 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10471 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10472 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10476 // Return the new vector
10477 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10480 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10481 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10482 EVT ResultVT = EVE->getValueType(0);
10483 EVT VecEltVT = InVecVT.getVectorElementType();
10484 unsigned Align = OriginalLoad->getAlignment();
10485 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10486 VecEltVT.getTypeForEVT(*DAG.getContext()));
10488 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10493 SDValue NewPtr = OriginalLoad->getBasePtr();
10495 EVT PtrType = NewPtr.getValueType();
10496 MachinePointerInfo MPI;
10497 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10498 int Elt = ConstEltNo->getZExtValue();
10499 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10500 if (TLI.isBigEndian())
10501 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10502 Offset = DAG.getConstant(PtrOff, PtrType);
10503 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10505 Offset = DAG.getNode(
10506 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10507 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10508 if (TLI.isBigEndian())
10509 Offset = DAG.getNode(
10510 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10511 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10512 MPI = OriginalLoad->getPointerInfo();
10514 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10516 // The replacement we need to do here is a little tricky: we need to
10517 // replace an extractelement of a load with a load.
10518 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10519 // Note that this replacement assumes that the extractvalue is the only
10520 // use of the load; that's okay because we don't want to perform this
10521 // transformation in other cases anyway.
10524 if (ResultVT.bitsGT(VecEltVT)) {
10525 // If the result type of vextract is wider than the load, then issue an
10526 // extending load instead.
10527 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10531 Load = DAG.getExtLoad(
10532 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10533 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10534 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10535 Chain = Load.getValue(1);
10537 Load = DAG.getLoad(
10538 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10539 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10540 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10541 Chain = Load.getValue(1);
10542 if (ResultVT.bitsLT(VecEltVT))
10543 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10545 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10547 WorklistRemover DeadNodes(*this);
10548 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10549 SDValue To[] = { Load, Chain };
10550 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10551 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10552 // worklist explicitly as well.
10553 AddToWorklist(Load.getNode());
10554 AddUsersToWorklist(Load.getNode()); // Add users too
10555 // Make sure to revisit this node to clean it up; it will usually be dead.
10556 AddToWorklist(EVE);
10558 return SDValue(EVE, 0);
10561 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10562 // (vextract (scalar_to_vector val, 0) -> val
10563 SDValue InVec = N->getOperand(0);
10564 EVT VT = InVec.getValueType();
10565 EVT NVT = N->getValueType(0);
10567 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10568 // Check if the result type doesn't match the inserted element type. A
10569 // SCALAR_TO_VECTOR may truncate the inserted element and the
10570 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10571 SDValue InOp = InVec.getOperand(0);
10572 if (InOp.getValueType() != NVT) {
10573 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10574 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10579 SDValue EltNo = N->getOperand(1);
10580 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10582 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10583 // We only perform this optimization before the op legalization phase because
10584 // we may introduce new vector instructions which are not backed by TD
10585 // patterns. For example on AVX, extracting elements from a wide vector
10586 // without using extract_subvector. However, if we can find an underlying
10587 // scalar value, then we can always use that.
10588 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10590 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10591 int NumElem = VT.getVectorNumElements();
10592 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10593 // Find the new index to extract from.
10594 int OrigElt = SVOp->getMaskElt(Elt);
10596 // Extracting an undef index is undef.
10598 return DAG.getUNDEF(NVT);
10600 // Select the right vector half to extract from.
10602 if (OrigElt < NumElem) {
10603 SVInVec = InVec->getOperand(0);
10605 SVInVec = InVec->getOperand(1);
10606 OrigElt -= NumElem;
10609 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10610 SDValue InOp = SVInVec.getOperand(OrigElt);
10611 if (InOp.getValueType() != NVT) {
10612 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10613 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10619 // FIXME: We should handle recursing on other vector shuffles and
10620 // scalar_to_vector here as well.
10622 if (!LegalOperations) {
10623 EVT IndexTy = TLI.getVectorIdxTy();
10624 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10625 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10629 bool BCNumEltsChanged = false;
10630 EVT ExtVT = VT.getVectorElementType();
10633 // If the result of load has to be truncated, then it's not necessarily
10635 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10638 if (InVec.getOpcode() == ISD::BITCAST) {
10639 // Don't duplicate a load with other uses.
10640 if (!InVec.hasOneUse())
10643 EVT BCVT = InVec.getOperand(0).getValueType();
10644 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10646 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10647 BCNumEltsChanged = true;
10648 InVec = InVec.getOperand(0);
10649 ExtVT = BCVT.getVectorElementType();
10652 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10653 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10654 ISD::isNormalLoad(InVec.getNode()) &&
10655 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10656 SDValue Index = N->getOperand(1);
10657 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10658 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10662 // Perform only after legalization to ensure build_vector / vector_shuffle
10663 // optimizations have already been done.
10664 if (!LegalOperations) return SDValue();
10666 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10667 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10668 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10671 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10673 LoadSDNode *LN0 = nullptr;
10674 const ShuffleVectorSDNode *SVN = nullptr;
10675 if (ISD::isNormalLoad(InVec.getNode())) {
10676 LN0 = cast<LoadSDNode>(InVec);
10677 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10678 InVec.getOperand(0).getValueType() == ExtVT &&
10679 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10680 // Don't duplicate a load with other uses.
10681 if (!InVec.hasOneUse())
10684 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10685 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10686 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10688 // (load $addr+1*size)
10690 // Don't duplicate a load with other uses.
10691 if (!InVec.hasOneUse())
10694 // If the bit convert changed the number of elements, it is unsafe
10695 // to examine the mask.
10696 if (BCNumEltsChanged)
10699 // Select the input vector, guarding against out of range extract vector.
10700 unsigned NumElems = VT.getVectorNumElements();
10701 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10702 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10704 if (InVec.getOpcode() == ISD::BITCAST) {
10705 // Don't duplicate a load with other uses.
10706 if (!InVec.hasOneUse())
10709 InVec = InVec.getOperand(0);
10711 if (ISD::isNormalLoad(InVec.getNode())) {
10712 LN0 = cast<LoadSDNode>(InVec);
10713 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10714 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10718 // Make sure we found a non-volatile load and the extractelement is
10720 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10723 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10725 return DAG.getUNDEF(LVT);
10727 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10733 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10734 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10735 // We perform this optimization post type-legalization because
10736 // the type-legalizer often scalarizes integer-promoted vectors.
10737 // Performing this optimization before may create bit-casts which
10738 // will be type-legalized to complex code sequences.
10739 // We perform this optimization only before the operation legalizer because we
10740 // may introduce illegal operations.
10741 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10744 unsigned NumInScalars = N->getNumOperands();
10746 EVT VT = N->getValueType(0);
10748 // Check to see if this is a BUILD_VECTOR of a bunch of values
10749 // which come from any_extend or zero_extend nodes. If so, we can create
10750 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10751 // optimizations. We do not handle sign-extend because we can't fill the sign
10753 EVT SourceType = MVT::Other;
10754 bool AllAnyExt = true;
10756 for (unsigned i = 0; i != NumInScalars; ++i) {
10757 SDValue In = N->getOperand(i);
10758 // Ignore undef inputs.
10759 if (In.getOpcode() == ISD::UNDEF) continue;
10761 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10762 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10764 // Abort if the element is not an extension.
10765 if (!ZeroExt && !AnyExt) {
10766 SourceType = MVT::Other;
10770 // The input is a ZeroExt or AnyExt. Check the original type.
10771 EVT InTy = In.getOperand(0).getValueType();
10773 // Check that all of the widened source types are the same.
10774 if (SourceType == MVT::Other)
10777 else if (InTy != SourceType) {
10778 // Multiple income types. Abort.
10779 SourceType = MVT::Other;
10783 // Check if all of the extends are ANY_EXTENDs.
10784 AllAnyExt &= AnyExt;
10787 // In order to have valid types, all of the inputs must be extended from the
10788 // same source type and all of the inputs must be any or zero extend.
10789 // Scalar sizes must be a power of two.
10790 EVT OutScalarTy = VT.getScalarType();
10791 bool ValidTypes = SourceType != MVT::Other &&
10792 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10793 isPowerOf2_32(SourceType.getSizeInBits());
10795 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10796 // turn into a single shuffle instruction.
10800 bool isLE = TLI.isLittleEndian();
10801 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10802 assert(ElemRatio > 1 && "Invalid element size ratio");
10803 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10804 DAG.getConstant(0, SourceType);
10806 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10807 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10809 // Populate the new build_vector
10810 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10811 SDValue Cast = N->getOperand(i);
10812 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10813 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10814 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10816 if (Cast.getOpcode() == ISD::UNDEF)
10817 In = DAG.getUNDEF(SourceType);
10819 In = Cast->getOperand(0);
10820 unsigned Index = isLE ? (i * ElemRatio) :
10821 (i * ElemRatio + (ElemRatio - 1));
10823 assert(Index < Ops.size() && "Invalid index");
10827 // The type of the new BUILD_VECTOR node.
10828 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10829 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10830 "Invalid vector size");
10831 // Check if the new vector type is legal.
10832 if (!isTypeLegal(VecVT)) return SDValue();
10834 // Make the new BUILD_VECTOR.
10835 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10837 // The new BUILD_VECTOR node has the potential to be further optimized.
10838 AddToWorklist(BV.getNode());
10839 // Bitcast to the desired type.
10840 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10843 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10844 EVT VT = N->getValueType(0);
10846 unsigned NumInScalars = N->getNumOperands();
10849 EVT SrcVT = MVT::Other;
10850 unsigned Opcode = ISD::DELETED_NODE;
10851 unsigned NumDefs = 0;
10853 for (unsigned i = 0; i != NumInScalars; ++i) {
10854 SDValue In = N->getOperand(i);
10855 unsigned Opc = In.getOpcode();
10857 if (Opc == ISD::UNDEF)
10860 // If all scalar values are floats and converted from integers.
10861 if (Opcode == ISD::DELETED_NODE &&
10862 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10869 EVT InVT = In.getOperand(0).getValueType();
10871 // If all scalar values are typed differently, bail out. It's chosen to
10872 // simplify BUILD_VECTOR of integer types.
10873 if (SrcVT == MVT::Other)
10880 // If the vector has just one element defined, it's not worth to fold it into
10881 // a vectorized one.
10885 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10886 && "Should only handle conversion from integer to float.");
10887 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10889 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10891 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10894 SmallVector<SDValue, 8> Opnds;
10895 for (unsigned i = 0; i != NumInScalars; ++i) {
10896 SDValue In = N->getOperand(i);
10898 if (In.getOpcode() == ISD::UNDEF)
10899 Opnds.push_back(DAG.getUNDEF(SrcVT));
10901 Opnds.push_back(In.getOperand(0));
10903 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10904 AddToWorklist(BV.getNode());
10906 return DAG.getNode(Opcode, dl, VT, BV);
10909 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10910 unsigned NumInScalars = N->getNumOperands();
10912 EVT VT = N->getValueType(0);
10914 // A vector built entirely of undefs is undef.
10915 if (ISD::allOperandsUndef(N))
10916 return DAG.getUNDEF(VT);
10918 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10922 V = reduceBuildVecConvertToConvertBuildVec(N);
10926 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10927 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10928 // at most two distinct vectors, turn this into a shuffle node.
10930 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10931 if (!isTypeLegal(VT))
10934 // May only combine to shuffle after legalize if shuffle is legal.
10935 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10938 SDValue VecIn1, VecIn2;
10939 bool UsesZeroVector = false;
10940 for (unsigned i = 0; i != NumInScalars; ++i) {
10941 SDValue Op = N->getOperand(i);
10942 // Ignore undef inputs.
10943 if (Op.getOpcode() == ISD::UNDEF) continue;
10945 // See if we can combine this build_vector into a blend with a zero vector.
10946 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10947 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10948 (Op.getOpcode() == ISD::ConstantFP &&
10949 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10950 UsesZeroVector = true;
10954 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10955 // constant index, bail out.
10956 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10957 !isa<ConstantSDNode>(Op.getOperand(1))) {
10958 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10962 // We allow up to two distinct input vectors.
10963 SDValue ExtractedFromVec = Op.getOperand(0);
10964 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10967 if (!VecIn1.getNode()) {
10968 VecIn1 = ExtractedFromVec;
10969 } else if (!VecIn2.getNode() && !UsesZeroVector) {
10970 VecIn2 = ExtractedFromVec;
10972 // Too many inputs.
10973 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10978 // If everything is good, we can make a shuffle operation.
10979 if (VecIn1.getNode()) {
10980 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
10981 SmallVector<int, 8> Mask;
10982 for (unsigned i = 0; i != NumInScalars; ++i) {
10983 unsigned Opcode = N->getOperand(i).getOpcode();
10984 if (Opcode == ISD::UNDEF) {
10985 Mask.push_back(-1);
10989 // Operands can also be zero.
10990 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
10991 assert(UsesZeroVector &&
10992 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
10993 "Unexpected node found!");
10994 Mask.push_back(NumInScalars+i);
10998 // If extracting from the first vector, just use the index directly.
10999 SDValue Extract = N->getOperand(i);
11000 SDValue ExtVal = Extract.getOperand(1);
11001 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11002 if (Extract.getOperand(0) == VecIn1) {
11003 Mask.push_back(ExtIndex);
11007 // Otherwise, use InIdx + InputVecSize
11008 Mask.push_back(InNumElements + ExtIndex);
11011 // Avoid introducing illegal shuffles with zero.
11012 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11015 // We can't generate a shuffle node with mismatched input and output types.
11016 // Attempt to transform a single input vector to the correct type.
11017 if ((VT != VecIn1.getValueType())) {
11018 // If the input vector type has a different base type to the output
11019 // vector type, bail out.
11020 EVT VTElemType = VT.getVectorElementType();
11021 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11022 (VecIn2.getNode() &&
11023 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11026 // If the input vector is too small, widen it.
11027 // We only support widening of vectors which are half the size of the
11028 // output registers. For example XMM->YMM widening on X86 with AVX.
11029 EVT VecInT = VecIn1.getValueType();
11030 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11031 // If we only have one small input, widen it by adding undef values.
11032 if (!VecIn2.getNode())
11033 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11034 DAG.getUNDEF(VecIn1.getValueType()));
11035 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11036 // If we have two small inputs of the same type, try to concat them.
11037 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11038 VecIn2 = SDValue(nullptr, 0);
11041 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11042 // If the input vector is too large, try to split it.
11043 // We don't support having two input vectors that are too large.
11044 if (VecIn2.getNode())
11047 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11050 // Try to replace VecIn1 with two extract_subvectors
11051 // No need to update the masks, they should still be correct.
11052 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11053 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11054 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11055 DAG.getConstant(0, TLI.getVectorIdxTy()));
11056 UsesZeroVector = false;
11061 if (UsesZeroVector)
11062 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11063 DAG.getConstantFP(0.0, VT);
11065 // If VecIn2 is unused then change it to undef.
11066 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11068 // Check that we were able to transform all incoming values to the same
11070 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11071 VecIn1.getValueType() != VT)
11074 // Return the new VECTOR_SHUFFLE node.
11078 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11084 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11085 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11086 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11087 // inputs come from at most two distinct vectors, turn this into a shuffle
11090 // If we only have one input vector, we don't need to do any concatenation.
11091 if (N->getNumOperands() == 1)
11092 return N->getOperand(0);
11094 // Check if all of the operands are undefs.
11095 EVT VT = N->getValueType(0);
11096 if (ISD::allOperandsUndef(N))
11097 return DAG.getUNDEF(VT);
11099 // Optimize concat_vectors where one of the vectors is undef.
11100 if (N->getNumOperands() == 2 &&
11101 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11102 SDValue In = N->getOperand(0);
11103 assert(In.getValueType().isVector() && "Must concat vectors");
11105 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11106 if (In->getOpcode() == ISD::BITCAST &&
11107 !In->getOperand(0)->getValueType(0).isVector()) {
11108 SDValue Scalar = In->getOperand(0);
11109 EVT SclTy = Scalar->getValueType(0);
11111 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11114 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11115 VT.getSizeInBits() / SclTy.getSizeInBits());
11116 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11119 SDLoc dl = SDLoc(N);
11120 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11121 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11125 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11126 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11127 if (N->getNumOperands() == 2 &&
11128 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
11129 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
11130 EVT VT = N->getValueType(0);
11131 SDValue N0 = N->getOperand(0);
11132 SDValue N1 = N->getOperand(1);
11133 SmallVector<SDValue, 8> Opnds;
11134 unsigned BuildVecNumElts = N0.getNumOperands();
11136 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
11137 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
11138 if (SclTy0.isFloatingPoint()) {
11139 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11140 Opnds.push_back(N0.getOperand(i));
11141 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11142 Opnds.push_back(N1.getOperand(i));
11144 // If BUILD_VECTOR are from built from integer, they may have different
11145 // operand types. Get the smaller type and truncate all operands to it.
11146 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
11147 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11148 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11149 N0.getOperand(i)));
11150 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11151 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11152 N1.getOperand(i)));
11155 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11158 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11159 // nodes often generate nop CONCAT_VECTOR nodes.
11160 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11161 // place the incoming vectors at the exact same location.
11162 SDValue SingleSource = SDValue();
11163 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11165 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11166 SDValue Op = N->getOperand(i);
11168 if (Op.getOpcode() == ISD::UNDEF)
11171 // Check if this is the identity extract:
11172 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11175 // Find the single incoming vector for the extract_subvector.
11176 if (SingleSource.getNode()) {
11177 if (Op.getOperand(0) != SingleSource)
11180 SingleSource = Op.getOperand(0);
11182 // Check the source type is the same as the type of the result.
11183 // If not, this concat may extend the vector, so we can not
11184 // optimize it away.
11185 if (SingleSource.getValueType() != N->getValueType(0))
11189 unsigned IdentityIndex = i * PartNumElem;
11190 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11191 // The extract index must be constant.
11195 // Check that we are reading from the identity index.
11196 if (CS->getZExtValue() != IdentityIndex)
11200 if (SingleSource.getNode())
11201 return SingleSource;
11206 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11207 EVT NVT = N->getValueType(0);
11208 SDValue V = N->getOperand(0);
11210 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11212 // (extract_subvec (concat V1, V2, ...), i)
11215 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11217 if (V->getOperand(0).getValueType() != NVT)
11219 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11220 unsigned NumElems = NVT.getVectorNumElements();
11221 assert((Idx % NumElems) == 0 &&
11222 "IDX in concat is not a multiple of the result vector length.");
11223 return V->getOperand(Idx / NumElems);
11227 if (V->getOpcode() == ISD::BITCAST)
11228 V = V.getOperand(0);
11230 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11232 // Handle only simple case where vector being inserted and vector
11233 // being extracted are of same type, and are half size of larger vectors.
11234 EVT BigVT = V->getOperand(0).getValueType();
11235 EVT SmallVT = V->getOperand(1).getValueType();
11236 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11239 // Only handle cases where both indexes are constants with the same type.
11240 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11241 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11243 if (InsIdx && ExtIdx &&
11244 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11245 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11247 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11249 // indices are equal or bit offsets are equal => V1
11250 // otherwise => (extract_subvec V1, ExtIdx)
11251 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11252 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11253 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11254 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11255 DAG.getNode(ISD::BITCAST, dl,
11256 N->getOperand(0).getValueType(),
11257 V->getOperand(0)), N->getOperand(1));
11264 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11265 SDValue V, SelectionDAG &DAG) {
11267 EVT VT = V.getValueType();
11269 switch (V.getOpcode()) {
11273 case ISD::CONCAT_VECTORS: {
11274 EVT OpVT = V->getOperand(0).getValueType();
11275 int OpSize = OpVT.getVectorNumElements();
11276 SmallBitVector OpUsedElements(OpSize, false);
11277 bool FoundSimplification = false;
11278 SmallVector<SDValue, 4> NewOps;
11279 NewOps.reserve(V->getNumOperands());
11280 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11281 SDValue Op = V->getOperand(i);
11282 bool OpUsed = false;
11283 for (int j = 0; j < OpSize; ++j)
11284 if (UsedElements[i * OpSize + j]) {
11285 OpUsedElements[j] = true;
11289 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11290 : DAG.getUNDEF(OpVT));
11291 FoundSimplification |= Op == NewOps.back();
11292 OpUsedElements.reset();
11294 if (FoundSimplification)
11295 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11299 case ISD::INSERT_SUBVECTOR: {
11300 SDValue BaseV = V->getOperand(0);
11301 SDValue SubV = V->getOperand(1);
11302 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11306 int SubSize = SubV.getValueType().getVectorNumElements();
11307 int Idx = IdxN->getZExtValue();
11308 bool SubVectorUsed = false;
11309 SmallBitVector SubUsedElements(SubSize, false);
11310 for (int i = 0; i < SubSize; ++i)
11311 if (UsedElements[i + Idx]) {
11312 SubVectorUsed = true;
11313 SubUsedElements[i] = true;
11314 UsedElements[i + Idx] = false;
11317 // Now recurse on both the base and sub vectors.
11318 SDValue SimplifiedSubV =
11320 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11321 : DAG.getUNDEF(SubV.getValueType());
11322 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11323 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11324 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11325 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11331 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11332 SDValue N1, SelectionDAG &DAG) {
11333 EVT VT = SVN->getValueType(0);
11334 int NumElts = VT.getVectorNumElements();
11335 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11336 for (int M : SVN->getMask())
11337 if (M >= 0 && M < NumElts)
11338 N0UsedElements[M] = true;
11339 else if (M >= NumElts)
11340 N1UsedElements[M - NumElts] = true;
11342 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11343 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11344 if (S0 == N0 && S1 == N1)
11347 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11350 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11351 // or turn a shuffle of a single concat into simpler shuffle then concat.
11352 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11353 EVT VT = N->getValueType(0);
11354 unsigned NumElts = VT.getVectorNumElements();
11356 SDValue N0 = N->getOperand(0);
11357 SDValue N1 = N->getOperand(1);
11358 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11360 SmallVector<SDValue, 4> Ops;
11361 EVT ConcatVT = N0.getOperand(0).getValueType();
11362 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11363 unsigned NumConcats = NumElts / NumElemsPerConcat;
11365 // Special case: shuffle(concat(A,B)) can be more efficiently represented
11366 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11367 // half vector elements.
11368 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11369 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11370 SVN->getMask().end(), [](int i) { return i == -1; })) {
11371 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11372 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11373 N1 = DAG.getUNDEF(ConcatVT);
11374 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11377 // Look at every vector that's inserted. We're looking for exact
11378 // subvector-sized copies from a concatenated vector
11379 for (unsigned I = 0; I != NumConcats; ++I) {
11380 // Make sure we're dealing with a copy.
11381 unsigned Begin = I * NumElemsPerConcat;
11382 bool AllUndef = true, NoUndef = true;
11383 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11384 if (SVN->getMaskElt(J) >= 0)
11391 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11394 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11395 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11398 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11399 if (FirstElt < N0.getNumOperands())
11400 Ops.push_back(N0.getOperand(FirstElt));
11402 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11404 } else if (AllUndef) {
11405 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11406 } else { // Mixed with general masks and undefs, can't do optimization.
11411 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11414 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11415 EVT VT = N->getValueType(0);
11416 unsigned NumElts = VT.getVectorNumElements();
11418 SDValue N0 = N->getOperand(0);
11419 SDValue N1 = N->getOperand(1);
11421 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11423 // Canonicalize shuffle undef, undef -> undef
11424 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11425 return DAG.getUNDEF(VT);
11427 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11429 // Canonicalize shuffle v, v -> v, undef
11431 SmallVector<int, 8> NewMask;
11432 for (unsigned i = 0; i != NumElts; ++i) {
11433 int Idx = SVN->getMaskElt(i);
11434 if (Idx >= (int)NumElts) Idx -= NumElts;
11435 NewMask.push_back(Idx);
11437 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11441 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11442 if (N0.getOpcode() == ISD::UNDEF) {
11443 SmallVector<int, 8> NewMask;
11444 for (unsigned i = 0; i != NumElts; ++i) {
11445 int Idx = SVN->getMaskElt(i);
11447 if (Idx >= (int)NumElts)
11450 Idx = -1; // remove reference to lhs
11452 NewMask.push_back(Idx);
11454 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11458 // Remove references to rhs if it is undef
11459 if (N1.getOpcode() == ISD::UNDEF) {
11460 bool Changed = false;
11461 SmallVector<int, 8> NewMask;
11462 for (unsigned i = 0; i != NumElts; ++i) {
11463 int Idx = SVN->getMaskElt(i);
11464 if (Idx >= (int)NumElts) {
11468 NewMask.push_back(Idx);
11471 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11474 // If it is a splat, check if the argument vector is another splat or a
11475 // build_vector with all scalar elements the same.
11476 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11477 SDNode *V = N0.getNode();
11479 // If this is a bit convert that changes the element type of the vector but
11480 // not the number of vector elements, look through it. Be careful not to
11481 // look though conversions that change things like v4f32 to v2f64.
11482 if (V->getOpcode() == ISD::BITCAST) {
11483 SDValue ConvInput = V->getOperand(0);
11484 if (ConvInput.getValueType().isVector() &&
11485 ConvInput.getValueType().getVectorNumElements() == NumElts)
11486 V = ConvInput.getNode();
11489 if (V->getOpcode() == ISD::BUILD_VECTOR) {
11490 assert(V->getNumOperands() == NumElts &&
11491 "BUILD_VECTOR has wrong number of operands");
11493 bool AllSame = true;
11494 for (unsigned i = 0; i != NumElts; ++i) {
11495 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11496 Base = V->getOperand(i);
11500 // Splat of <u, u, u, u>, return <u, u, u, u>
11501 if (!Base.getNode())
11503 for (unsigned i = 0; i != NumElts; ++i) {
11504 if (V->getOperand(i) != Base) {
11509 // Splat of <x, x, x, x>, return <x, x, x, x>
11515 // There are various patterns used to build up a vector from smaller vectors,
11516 // subvectors, or elements. Scan chains of these and replace unused insertions
11517 // or components with undef.
11518 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11521 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11522 Level < AfterLegalizeVectorOps &&
11523 (N1.getOpcode() == ISD::UNDEF ||
11524 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11525 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11526 SDValue V = partitionShuffleOfConcats(N, DAG);
11532 // Canonicalize shuffles according to rules:
11533 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11534 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11535 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11536 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11537 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11538 TLI.isTypeLegal(VT)) {
11539 // The incoming shuffle must be of the same type as the result of the
11540 // current shuffle.
11541 assert(N1->getOperand(0).getValueType() == VT &&
11542 "Shuffle types don't match");
11544 SDValue SV0 = N1->getOperand(0);
11545 SDValue SV1 = N1->getOperand(1);
11546 bool HasSameOp0 = N0 == SV0;
11547 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11548 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11549 // Commute the operands of this shuffle so that next rule
11551 return DAG.getCommutedVectorShuffle(*SVN);
11554 // Try to fold according to rules:
11555 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11556 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11557 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11558 // Don't try to fold shuffles with illegal type.
11559 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11560 TLI.isTypeLegal(VT)) {
11561 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11563 // The incoming shuffle must be of the same type as the result of the
11564 // current shuffle.
11565 assert(OtherSV->getOperand(0).getValueType() == VT &&
11566 "Shuffle types don't match");
11569 SmallVector<int, 4> Mask;
11570 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11571 // operand, and SV1 as the second operand.
11572 for (unsigned i = 0; i != NumElts; ++i) {
11573 int Idx = SVN->getMaskElt(i);
11575 // Propagate Undef.
11576 Mask.push_back(Idx);
11580 SDValue CurrentVec;
11581 if (Idx < (int)NumElts) {
11582 // This shuffle index refers to the inner shuffle N0. Lookup the inner
11583 // shuffle mask to identify which vector is actually referenced.
11584 Idx = OtherSV->getMaskElt(Idx);
11586 // Propagate Undef.
11587 Mask.push_back(Idx);
11591 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11592 : OtherSV->getOperand(1);
11594 // This shuffle index references an element within N1.
11598 // Simple case where 'CurrentVec' is UNDEF.
11599 if (CurrentVec.getOpcode() == ISD::UNDEF) {
11600 Mask.push_back(-1);
11604 // Canonicalize the shuffle index. We don't know yet if CurrentVec
11605 // will be the first or second operand of the combined shuffle.
11606 Idx = Idx % NumElts;
11607 if (!SV0.getNode() || SV0 == CurrentVec) {
11608 // Ok. CurrentVec is the left hand side.
11609 // Update the mask accordingly.
11611 Mask.push_back(Idx);
11615 // Bail out if we cannot convert the shuffle pair into a single shuffle.
11616 if (SV1.getNode() && SV1 != CurrentVec)
11619 // Ok. CurrentVec is the right hand side.
11620 // Update the mask accordingly.
11622 Mask.push_back(Idx + NumElts);
11625 // Check if all indices in Mask are Undef. In case, propagate Undef.
11626 bool isUndefMask = true;
11627 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11628 isUndefMask &= Mask[i] < 0;
11631 return DAG.getUNDEF(VT);
11633 if (!SV0.getNode())
11634 SV0 = DAG.getUNDEF(VT);
11635 if (!SV1.getNode())
11636 SV1 = DAG.getUNDEF(VT);
11638 // Avoid introducing shuffles with illegal mask.
11639 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11640 // Compute the commuted shuffle mask and test again.
11641 for (unsigned i = 0; i != NumElts; ++i) {
11645 else if (idx < (int)NumElts)
11646 Mask[i] = idx + NumElts;
11648 Mask[i] = idx - NumElts;
11651 if (!TLI.isShuffleMaskLegal(Mask, VT))
11654 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11655 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11656 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11657 std::swap(SV0, SV1);
11660 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11661 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11662 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11663 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11669 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11670 SDValue N0 = N->getOperand(0);
11671 SDValue N2 = N->getOperand(2);
11673 // If the input vector is a concatenation, and the insert replaces
11674 // one of the halves, we can optimize into a single concat_vectors.
11675 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11676 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11677 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11678 EVT VT = N->getValueType(0);
11680 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11681 // (concat_vectors Z, Y)
11683 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11684 N->getOperand(1), N0.getOperand(1));
11686 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11687 // (concat_vectors X, Z)
11688 if (InsIdx == VT.getVectorNumElements()/2)
11689 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11690 N0.getOperand(0), N->getOperand(1));
11696 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11697 /// with the destination vector and a zero vector.
11698 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11699 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11700 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11701 EVT VT = N->getValueType(0);
11703 SDValue LHS = N->getOperand(0);
11704 SDValue RHS = N->getOperand(1);
11705 if (N->getOpcode() == ISD::AND) {
11706 if (RHS.getOpcode() == ISD::BITCAST)
11707 RHS = RHS.getOperand(0);
11708 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11709 SmallVector<int, 8> Indices;
11710 unsigned NumElts = RHS.getNumOperands();
11711 for (unsigned i = 0; i != NumElts; ++i) {
11712 SDValue Elt = RHS.getOperand(i);
11713 if (!isa<ConstantSDNode>(Elt))
11716 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11717 Indices.push_back(i);
11718 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11719 Indices.push_back(NumElts+i);
11724 // Let's see if the target supports this vector_shuffle.
11725 EVT RVT = RHS.getValueType();
11726 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11729 // Return the new VECTOR_SHUFFLE node.
11730 EVT EltVT = RVT.getVectorElementType();
11731 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11732 DAG.getConstant(0, EltVT));
11733 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11734 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11735 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11736 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11743 /// Visit a binary vector operation, like ADD.
11744 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11745 assert(N->getValueType(0).isVector() &&
11746 "SimplifyVBinOp only works on vectors!");
11748 SDValue LHS = N->getOperand(0);
11749 SDValue RHS = N->getOperand(1);
11750 SDValue Shuffle = XformToShuffleWithZero(N);
11751 if (Shuffle.getNode()) return Shuffle;
11753 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11755 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11756 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11757 // Check if both vectors are constants. If not bail out.
11758 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11759 cast<BuildVectorSDNode>(RHS)->isConstant()))
11762 SmallVector<SDValue, 8> Ops;
11763 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11764 SDValue LHSOp = LHS.getOperand(i);
11765 SDValue RHSOp = RHS.getOperand(i);
11767 // Can't fold divide by zero.
11768 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11769 N->getOpcode() == ISD::FDIV) {
11770 if ((RHSOp.getOpcode() == ISD::Constant &&
11771 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11772 (RHSOp.getOpcode() == ISD::ConstantFP &&
11773 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11777 EVT VT = LHSOp.getValueType();
11778 EVT RVT = RHSOp.getValueType();
11780 // Integer BUILD_VECTOR operands may have types larger than the element
11781 // size (e.g., when the element type is not legal). Prior to type
11782 // legalization, the types may not match between the two BUILD_VECTORS.
11783 // Truncate one of the operands to make them match.
11784 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11785 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11787 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11791 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11793 if (FoldOp.getOpcode() != ISD::UNDEF &&
11794 FoldOp.getOpcode() != ISD::Constant &&
11795 FoldOp.getOpcode() != ISD::ConstantFP)
11797 Ops.push_back(FoldOp);
11798 AddToWorklist(FoldOp.getNode());
11801 if (Ops.size() == LHS.getNumOperands())
11802 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11805 // Type legalization might introduce new shuffles in the DAG.
11806 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11807 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11808 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11809 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11810 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11811 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11812 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11813 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11815 if (SVN0->getMask().equals(SVN1->getMask())) {
11816 EVT VT = N->getValueType(0);
11817 SDValue UndefVector = LHS.getOperand(1);
11818 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11819 LHS.getOperand(0), RHS.getOperand(0));
11820 AddUsersToWorklist(N);
11821 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11822 &SVN0->getMask()[0]);
11829 /// Visit a binary vector operation, like FABS/FNEG.
11830 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11831 assert(N->getValueType(0).isVector() &&
11832 "SimplifyVUnaryOp only works on vectors!");
11834 SDValue N0 = N->getOperand(0);
11836 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11839 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11840 SmallVector<SDValue, 8> Ops;
11841 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11842 SDValue Op = N0.getOperand(i);
11843 if (Op.getOpcode() != ISD::UNDEF &&
11844 Op.getOpcode() != ISD::ConstantFP)
11846 EVT EltVT = Op.getValueType();
11847 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11848 if (FoldOp.getOpcode() != ISD::UNDEF &&
11849 FoldOp.getOpcode() != ISD::ConstantFP)
11851 Ops.push_back(FoldOp);
11852 AddToWorklist(FoldOp.getNode());
11855 if (Ops.size() != N0.getNumOperands())
11858 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11861 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11862 SDValue N1, SDValue N2){
11863 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11865 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11866 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11868 // If we got a simplified select_cc node back from SimplifySelectCC, then
11869 // break it down into a new SETCC node, and a new SELECT node, and then return
11870 // the SELECT node, since we were called with a SELECT node.
11871 if (SCC.getNode()) {
11872 // Check to see if we got a select_cc back (to turn into setcc/select).
11873 // Otherwise, just return whatever node we got back, like fabs.
11874 if (SCC.getOpcode() == ISD::SELECT_CC) {
11875 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11877 SCC.getOperand(0), SCC.getOperand(1),
11878 SCC.getOperand(4));
11879 AddToWorklist(SETCC.getNode());
11880 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11881 SCC.getOperand(2), SCC.getOperand(3));
11889 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11890 /// being selected between, see if we can simplify the select. Callers of this
11891 /// should assume that TheSelect is deleted if this returns true. As such, they
11892 /// should return the appropriate thing (e.g. the node) back to the top-level of
11893 /// the DAG combiner loop to avoid it being looked at.
11894 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11897 // Cannot simplify select with vector condition
11898 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11900 // If this is a select from two identical things, try to pull the operation
11901 // through the select.
11902 if (LHS.getOpcode() != RHS.getOpcode() ||
11903 !LHS.hasOneUse() || !RHS.hasOneUse())
11906 // If this is a load and the token chain is identical, replace the select
11907 // of two loads with a load through a select of the address to load from.
11908 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11909 // constants have been dropped into the constant pool.
11910 if (LHS.getOpcode() == ISD::LOAD) {
11911 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11912 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11914 // Token chains must be identical.
11915 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11916 // Do not let this transformation reduce the number of volatile loads.
11917 LLD->isVolatile() || RLD->isVolatile() ||
11918 // If this is an EXTLOAD, the VT's must match.
11919 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11920 // If this is an EXTLOAD, the kind of extension must match.
11921 (LLD->getExtensionType() != RLD->getExtensionType() &&
11922 // The only exception is if one of the extensions is anyext.
11923 LLD->getExtensionType() != ISD::EXTLOAD &&
11924 RLD->getExtensionType() != ISD::EXTLOAD) ||
11925 // FIXME: this discards src value information. This is
11926 // over-conservative. It would be beneficial to be able to remember
11927 // both potential memory locations. Since we are discarding
11928 // src value info, don't do the transformation if the memory
11929 // locations are not in the default address space.
11930 LLD->getPointerInfo().getAddrSpace() != 0 ||
11931 RLD->getPointerInfo().getAddrSpace() != 0 ||
11932 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11933 LLD->getBasePtr().getValueType()))
11936 // Check that the select condition doesn't reach either load. If so,
11937 // folding this will induce a cycle into the DAG. If not, this is safe to
11938 // xform, so create a select of the addresses.
11940 if (TheSelect->getOpcode() == ISD::SELECT) {
11941 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11942 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11943 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11945 // The loads must not depend on one another.
11946 if (LLD->isPredecessorOf(RLD) ||
11947 RLD->isPredecessorOf(LLD))
11949 Addr = DAG.getSelect(SDLoc(TheSelect),
11950 LLD->getBasePtr().getValueType(),
11951 TheSelect->getOperand(0), LLD->getBasePtr(),
11952 RLD->getBasePtr());
11953 } else { // Otherwise SELECT_CC
11954 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11955 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11957 if ((LLD->hasAnyUseOfValue(1) &&
11958 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11959 (RLD->hasAnyUseOfValue(1) &&
11960 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11963 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11964 LLD->getBasePtr().getValueType(),
11965 TheSelect->getOperand(0),
11966 TheSelect->getOperand(1),
11967 LLD->getBasePtr(), RLD->getBasePtr(),
11968 TheSelect->getOperand(4));
11972 // It is safe to replace the two loads if they have different alignments,
11973 // but the new load must be the minimum (most restrictive) alignment of the
11975 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11976 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11977 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11978 Load = DAG.getLoad(TheSelect->getValueType(0),
11980 // FIXME: Discards pointer and AA info.
11981 LLD->getChain(), Addr, MachinePointerInfo(),
11982 LLD->isVolatile(), LLD->isNonTemporal(),
11983 isInvariant, Alignment);
11985 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11986 RLD->getExtensionType() : LLD->getExtensionType(),
11988 TheSelect->getValueType(0),
11989 // FIXME: Discards pointer and AA info.
11990 LLD->getChain(), Addr, MachinePointerInfo(),
11991 LLD->getMemoryVT(), LLD->isVolatile(),
11992 LLD->isNonTemporal(), isInvariant, Alignment);
11995 // Users of the select now use the result of the load.
11996 CombineTo(TheSelect, Load);
11998 // Users of the old loads now use the new load's chain. We know the
11999 // old-load value is dead now.
12000 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12001 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12008 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12009 /// where 'cond' is the comparison specified by CC.
12010 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12011 SDValue N2, SDValue N3,
12012 ISD::CondCode CC, bool NotExtCompare) {
12013 // (x ? y : y) -> y.
12014 if (N2 == N3) return N2;
12016 EVT VT = N2.getValueType();
12017 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12018 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12019 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12021 // Determine if the condition we're dealing with is constant
12022 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12023 N0, N1, CC, DL, false);
12024 if (SCC.getNode()) AddToWorklist(SCC.getNode());
12025 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12027 // fold select_cc true, x, y -> x
12028 if (SCCC && !SCCC->isNullValue())
12030 // fold select_cc false, x, y -> y
12031 if (SCCC && SCCC->isNullValue())
12034 // Check to see if we can simplify the select into an fabs node
12035 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12036 // Allow either -0.0 or 0.0
12037 if (CFP->getValueAPF().isZero()) {
12038 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12039 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12040 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12041 N2 == N3.getOperand(0))
12042 return DAG.getNode(ISD::FABS, DL, VT, N0);
12044 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12045 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12046 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12047 N2.getOperand(0) == N3)
12048 return DAG.getNode(ISD::FABS, DL, VT, N3);
12052 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12053 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12054 // in it. This is a win when the constant is not otherwise available because
12055 // it replaces two constant pool loads with one. We only do this if the FP
12056 // type is known to be legal, because if it isn't, then we are before legalize
12057 // types an we want the other legalization to happen first (e.g. to avoid
12058 // messing with soft float) and if the ConstantFP is not legal, because if
12059 // it is legal, we may not need to store the FP constant in a constant pool.
12060 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12061 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12062 if (TLI.isTypeLegal(N2.getValueType()) &&
12063 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12064 TargetLowering::Legal &&
12065 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12066 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12067 // If both constants have multiple uses, then we won't need to do an
12068 // extra load, they are likely around in registers for other users.
12069 (TV->hasOneUse() || FV->hasOneUse())) {
12070 Constant *Elts[] = {
12071 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12072 const_cast<ConstantFP*>(TV->getConstantFPValue())
12074 Type *FPTy = Elts[0]->getType();
12075 const DataLayout &TD = *TLI.getDataLayout();
12077 // Create a ConstantArray of the two constants.
12078 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12079 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12080 TD.getPrefTypeAlignment(FPTy));
12081 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12083 // Get the offsets to the 0 and 1 element of the array so that we can
12084 // select between them.
12085 SDValue Zero = DAG.getIntPtrConstant(0);
12086 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12087 SDValue One = DAG.getIntPtrConstant(EltSize);
12089 SDValue Cond = DAG.getSetCC(DL,
12090 getSetCCResultType(N0.getValueType()),
12092 AddToWorklist(Cond.getNode());
12093 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12095 AddToWorklist(CstOffset.getNode());
12096 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12098 AddToWorklist(CPIdx.getNode());
12099 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12100 MachinePointerInfo::getConstantPool(), false,
12101 false, false, Alignment);
12106 // Check to see if we can perform the "gzip trick", transforming
12107 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12108 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12109 (N1C->isNullValue() || // (a < 0) ? b : 0
12110 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
12111 EVT XType = N0.getValueType();
12112 EVT AType = N2.getValueType();
12113 if (XType.bitsGE(AType)) {
12114 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12115 // single-bit constant.
12116 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12117 unsigned ShCtV = N2C->getAPIntValue().logBase2();
12118 ShCtV = XType.getSizeInBits()-ShCtV-1;
12119 SDValue ShCt = DAG.getConstant(ShCtV,
12120 getShiftAmountTy(N0.getValueType()));
12121 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12123 AddToWorklist(Shift.getNode());
12125 if (XType.bitsGT(AType)) {
12126 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12127 AddToWorklist(Shift.getNode());
12130 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12133 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12135 DAG.getConstant(XType.getSizeInBits()-1,
12136 getShiftAmountTy(N0.getValueType())));
12137 AddToWorklist(Shift.getNode());
12139 if (XType.bitsGT(AType)) {
12140 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12141 AddToWorklist(Shift.getNode());
12144 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12148 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12149 // where y is has a single bit set.
12150 // A plaintext description would be, we can turn the SELECT_CC into an AND
12151 // when the condition can be materialized as an all-ones register. Any
12152 // single bit-test can be materialized as an all-ones register with
12153 // shift-left and shift-right-arith.
12154 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12155 N0->getValueType(0) == VT &&
12156 N1C && N1C->isNullValue() &&
12157 N2C && N2C->isNullValue()) {
12158 SDValue AndLHS = N0->getOperand(0);
12159 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12160 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12161 // Shift the tested bit over the sign bit.
12162 APInt AndMask = ConstAndRHS->getAPIntValue();
12164 DAG.getConstant(AndMask.countLeadingZeros(),
12165 getShiftAmountTy(AndLHS.getValueType()));
12166 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12168 // Now arithmetic right shift it all the way over, so the result is either
12169 // all-ones, or zero.
12171 DAG.getConstant(AndMask.getBitWidth()-1,
12172 getShiftAmountTy(Shl.getValueType()));
12173 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12175 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12179 // fold select C, 16, 0 -> shl C, 4
12180 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12181 TLI.getBooleanContents(N0.getValueType()) ==
12182 TargetLowering::ZeroOrOneBooleanContent) {
12184 // If the caller doesn't want us to simplify this into a zext of a compare,
12186 if (NotExtCompare && N2C->getAPIntValue() == 1)
12189 // Get a SetCC of the condition
12190 // NOTE: Don't create a SETCC if it's not legal on this target.
12191 if (!LegalOperations ||
12192 TLI.isOperationLegal(ISD::SETCC,
12193 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12195 // cast from setcc result type to select result type
12197 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12199 if (N2.getValueType().bitsLT(SCC.getValueType()))
12200 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12201 N2.getValueType());
12203 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12204 N2.getValueType(), SCC);
12206 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12207 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12208 N2.getValueType(), SCC);
12211 AddToWorklist(SCC.getNode());
12212 AddToWorklist(Temp.getNode());
12214 if (N2C->getAPIntValue() == 1)
12217 // shl setcc result by log2 n2c
12218 return DAG.getNode(
12219 ISD::SHL, DL, N2.getValueType(), Temp,
12220 DAG.getConstant(N2C->getAPIntValue().logBase2(),
12221 getShiftAmountTy(Temp.getValueType())));
12225 // Check to see if this is the equivalent of setcc
12226 // FIXME: Turn all of these into setcc if setcc if setcc is legal
12227 // otherwise, go ahead with the folds.
12228 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12229 EVT XType = N0.getValueType();
12230 if (!LegalOperations ||
12231 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12232 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12233 if (Res.getValueType() != VT)
12234 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12238 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12239 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12240 (!LegalOperations ||
12241 TLI.isOperationLegal(ISD::CTLZ, XType))) {
12242 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12243 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12244 DAG.getConstant(Log2_32(XType.getSizeInBits()),
12245 getShiftAmountTy(Ctlz.getValueType())));
12247 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12248 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12249 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12250 XType, DAG.getConstant(0, XType), N0);
12251 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12252 return DAG.getNode(ISD::SRL, DL, XType,
12253 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12254 DAG.getConstant(XType.getSizeInBits()-1,
12255 getShiftAmountTy(XType)));
12257 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12258 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12259 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12260 DAG.getConstant(XType.getSizeInBits()-1,
12261 getShiftAmountTy(N0.getValueType())));
12262 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12266 // Check to see if this is an integer abs.
12267 // select_cc setg[te] X, 0, X, -X ->
12268 // select_cc setgt X, -1, X, -X ->
12269 // select_cc setl[te] X, 0, -X, X ->
12270 // select_cc setlt X, 1, -X, X ->
12271 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12273 ConstantSDNode *SubC = nullptr;
12274 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12275 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12276 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12277 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12278 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12279 (N1C->isOne() && CC == ISD::SETLT)) &&
12280 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12281 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12283 EVT XType = N0.getValueType();
12284 if (SubC && SubC->isNullValue() && XType.isInteger()) {
12285 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12287 DAG.getConstant(XType.getSizeInBits()-1,
12288 getShiftAmountTy(N0.getValueType())));
12289 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12291 AddToWorklist(Shift.getNode());
12292 AddToWorklist(Add.getNode());
12293 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12300 /// This is a stub for TargetLowering::SimplifySetCC.
12301 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12302 SDValue N1, ISD::CondCode Cond,
12303 SDLoc DL, bool foldBooleans) {
12304 TargetLowering::DAGCombinerInfo
12305 DagCombineInfo(DAG, Level, false, this);
12306 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12309 /// Given an ISD::SDIV node expressing a divide by constant, return
12310 /// a DAG expression to select that will generate the same value by multiplying
12311 /// by a magic number.
12312 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12313 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12314 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12318 // Avoid division by zero.
12319 if (!C->getAPIntValue())
12322 std::vector<SDNode*> Built;
12324 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12326 for (SDNode *N : Built)
12331 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12332 /// DAG expression that will generate the same value by right shifting.
12333 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12334 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12338 // Avoid division by zero.
12339 if (!C->getAPIntValue())
12342 std::vector<SDNode *> Built;
12343 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12345 for (SDNode *N : Built)
12350 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12351 /// expression that will generate the same value by multiplying by a magic
12353 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12354 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12355 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12359 // Avoid division by zero.
12360 if (!C->getAPIntValue())
12363 std::vector<SDNode*> Built;
12365 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12367 for (SDNode *N : Built)
12372 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12373 if (Level >= AfterLegalizeDAG)
12376 // Expose the DAG combiner to the target combiner implementations.
12377 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12379 unsigned Iterations = 0;
12380 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12382 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12383 // For the reciprocal, we need to find the zero of the function:
12384 // F(X) = A X - 1 [which has a zero at X = 1/A]
12386 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12387 // does not require additional intermediate precision]
12388 EVT VT = Op.getValueType();
12390 SDValue FPOne = DAG.getConstantFP(1.0, VT);
12392 AddToWorklist(Est.getNode());
12394 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12395 for (unsigned i = 0; i < Iterations; ++i) {
12396 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12397 AddToWorklist(NewEst.getNode());
12399 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12400 AddToWorklist(NewEst.getNode());
12402 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12403 AddToWorklist(NewEst.getNode());
12405 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12406 AddToWorklist(Est.getNode());
12415 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12416 /// For the reciprocal sqrt, we need to find the zero of the function:
12417 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12419 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12420 /// As a result, we precompute A/2 prior to the iteration loop.
12421 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12422 unsigned Iterations) {
12423 EVT VT = Arg.getValueType();
12425 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12427 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12428 // this entire sequence requires only one FP constant.
12429 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12430 AddToWorklist(HalfArg.getNode());
12432 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12433 AddToWorklist(HalfArg.getNode());
12435 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12436 for (unsigned i = 0; i < Iterations; ++i) {
12437 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12438 AddToWorklist(NewEst.getNode());
12440 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12441 AddToWorklist(NewEst.getNode());
12443 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12444 AddToWorklist(NewEst.getNode());
12446 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12447 AddToWorklist(Est.getNode());
12452 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12453 /// For the reciprocal sqrt, we need to find the zero of the function:
12454 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12456 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12457 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12458 unsigned Iterations) {
12459 EVT VT = Arg.getValueType();
12461 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12462 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12464 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12465 for (unsigned i = 0; i < Iterations; ++i) {
12466 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12467 AddToWorklist(HalfEst.getNode());
12469 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12470 AddToWorklist(Est.getNode());
12472 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12473 AddToWorklist(Est.getNode());
12475 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12476 AddToWorklist(Est.getNode());
12478 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12479 AddToWorklist(Est.getNode());
12484 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12485 if (Level >= AfterLegalizeDAG)
12488 // Expose the DAG combiner to the target combiner implementations.
12489 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12490 unsigned Iterations = 0;
12491 bool UseOneConstNR = false;
12492 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12493 AddToWorklist(Est.getNode());
12495 Est = UseOneConstNR ?
12496 BuildRsqrtNROneConst(Op, Est, Iterations) :
12497 BuildRsqrtNRTwoConst(Op, Est, Iterations);
12505 /// Return true if base is a frame index, which is known not to alias with
12506 /// anything but itself. Provides base object and offset as results.
12507 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12508 const GlobalValue *&GV, const void *&CV) {
12509 // Assume it is a primitive operation.
12510 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12512 // If it's an adding a simple constant then integrate the offset.
12513 if (Base.getOpcode() == ISD::ADD) {
12514 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12515 Base = Base.getOperand(0);
12516 Offset += C->getZExtValue();
12520 // Return the underlying GlobalValue, and update the Offset. Return false
12521 // for GlobalAddressSDNode since the same GlobalAddress may be represented
12522 // by multiple nodes with different offsets.
12523 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12524 GV = G->getGlobal();
12525 Offset += G->getOffset();
12529 // Return the underlying Constant value, and update the Offset. Return false
12530 // for ConstantSDNodes since the same constant pool entry may be represented
12531 // by multiple nodes with different offsets.
12532 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12533 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12534 : (const void *)C->getConstVal();
12535 Offset += C->getOffset();
12538 // If it's any of the following then it can't alias with anything but itself.
12539 return isa<FrameIndexSDNode>(Base);
12542 /// Return true if there is any possibility that the two addresses overlap.
12543 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12544 // If they are the same then they must be aliases.
12545 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12547 // If they are both volatile then they cannot be reordered.
12548 if (Op0->isVolatile() && Op1->isVolatile()) return true;
12550 // Gather base node and offset information.
12551 SDValue Base1, Base2;
12552 int64_t Offset1, Offset2;
12553 const GlobalValue *GV1, *GV2;
12554 const void *CV1, *CV2;
12555 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12556 Base1, Offset1, GV1, CV1);
12557 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12558 Base2, Offset2, GV2, CV2);
12560 // If they have a same base address then check to see if they overlap.
12561 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12562 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12563 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12565 // It is possible for different frame indices to alias each other, mostly
12566 // when tail call optimization reuses return address slots for arguments.
12567 // To catch this case, look up the actual index of frame indices to compute
12568 // the real alias relationship.
12569 if (isFrameIndex1 && isFrameIndex2) {
12570 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12571 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12572 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12573 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12574 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12577 // Otherwise, if we know what the bases are, and they aren't identical, then
12578 // we know they cannot alias.
12579 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12582 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12583 // compared to the size and offset of the access, we may be able to prove they
12584 // do not alias. This check is conservative for now to catch cases created by
12585 // splitting vector types.
12586 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12587 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12588 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12589 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12590 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12591 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12592 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12594 // There is no overlap between these relatively aligned accesses of similar
12595 // size, return no alias.
12596 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12597 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12601 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12603 : DAG.getSubtarget().useAA();
12605 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12606 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12610 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12611 // Use alias analysis information.
12612 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12613 Op1->getSrcValueOffset());
12614 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12615 Op0->getSrcValueOffset() - MinOffset;
12616 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12617 Op1->getSrcValueOffset() - MinOffset;
12618 AliasAnalysis::AliasResult AAResult =
12619 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12621 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12622 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12624 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12625 if (AAResult == AliasAnalysis::NoAlias)
12629 // Otherwise we have to assume they alias.
12633 /// Walk up chain skipping non-aliasing memory nodes,
12634 /// looking for aliasing nodes and adding them to the Aliases vector.
12635 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12636 SmallVectorImpl<SDValue> &Aliases) {
12637 SmallVector<SDValue, 8> Chains; // List of chains to visit.
12638 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
12640 // Get alias information for node.
12641 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12644 Chains.push_back(OriginalChain);
12645 unsigned Depth = 0;
12647 // Look at each chain and determine if it is an alias. If so, add it to the
12648 // aliases list. If not, then continue up the chain looking for the next
12650 while (!Chains.empty()) {
12651 SDValue Chain = Chains.back();
12654 // For TokenFactor nodes, look at each operand and only continue up the
12655 // chain until we find two aliases. If we've seen two aliases, assume we'll
12656 // find more and revert to original chain since the xform is unlikely to be
12659 // FIXME: The depth check could be made to return the last non-aliasing
12660 // chain we found before we hit a tokenfactor rather than the original
12662 if (Depth > 6 || Aliases.size() == 2) {
12664 Aliases.push_back(OriginalChain);
12668 // Don't bother if we've been before.
12669 if (!Visited.insert(Chain.getNode()).second)
12672 switch (Chain.getOpcode()) {
12673 case ISD::EntryToken:
12674 // Entry token is ideal chain operand, but handled in FindBetterChain.
12679 // Get alias information for Chain.
12680 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12681 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12683 // If chain is alias then stop here.
12684 if (!(IsLoad && IsOpLoad) &&
12685 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12686 Aliases.push_back(Chain);
12688 // Look further up the chain.
12689 Chains.push_back(Chain.getOperand(0));
12695 case ISD::TokenFactor:
12696 // We have to check each of the operands of the token factor for "small"
12697 // token factors, so we queue them up. Adding the operands to the queue
12698 // (stack) in reverse order maintains the original order and increases the
12699 // likelihood that getNode will find a matching token factor (CSE.)
12700 if (Chain.getNumOperands() > 16) {
12701 Aliases.push_back(Chain);
12704 for (unsigned n = Chain.getNumOperands(); n;)
12705 Chains.push_back(Chain.getOperand(--n));
12710 // For all other instructions we will just have to take what we can get.
12711 Aliases.push_back(Chain);
12716 // We need to be careful here to also search for aliases through the
12717 // value operand of a store, etc. Consider the following situation:
12719 // L1 = load Token1, %52
12720 // S1 = store Token1, L1, %51
12721 // L2 = load Token1, %52+8
12722 // S2 = store Token1, L2, %51+8
12723 // Token2 = Token(S1, S2)
12724 // L3 = load Token2, %53
12725 // S3 = store Token2, L3, %52
12726 // L4 = load Token2, %53+8
12727 // S4 = store Token2, L4, %52+8
12728 // If we search for aliases of S3 (which loads address %52), and we look
12729 // only through the chain, then we'll miss the trivial dependence on L1
12730 // (which also loads from %52). We then might change all loads and
12731 // stores to use Token1 as their chain operand, which could result in
12732 // copying %53 into %52 before copying %52 into %51 (which should
12735 // The problem is, however, that searching for such data dependencies
12736 // can become expensive, and the cost is not directly related to the
12737 // chain depth. Instead, we'll rule out such configurations here by
12738 // insisting that we've visited all chain users (except for users
12739 // of the original chain, which is not necessary). When doing this,
12740 // we need to look through nodes we don't care about (otherwise, things
12741 // like register copies will interfere with trivial cases).
12743 SmallVector<const SDNode *, 16> Worklist;
12744 for (const SDNode *N : Visited)
12745 if (N != OriginalChain.getNode())
12746 Worklist.push_back(N);
12748 while (!Worklist.empty()) {
12749 const SDNode *M = Worklist.pop_back_val();
12751 // We have already visited M, and want to make sure we've visited any uses
12752 // of M that we care about. For uses that we've not visisted, and don't
12753 // care about, queue them to the worklist.
12755 for (SDNode::use_iterator UI = M->use_begin(),
12756 UIE = M->use_end(); UI != UIE; ++UI)
12757 if (UI.getUse().getValueType() == MVT::Other &&
12758 Visited.insert(*UI).second) {
12759 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12760 // We've not visited this use, and we care about it (it could have an
12761 // ordering dependency with the original node).
12763 Aliases.push_back(OriginalChain);
12767 // We've not visited this use, but we don't care about it. Mark it as
12768 // visited and enqueue it to the worklist.
12769 Worklist.push_back(*UI);
12774 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12775 /// (aliasing node.)
12776 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12777 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
12779 // Accumulate all the aliases to this node.
12780 GatherAllAliases(N, OldChain, Aliases);
12782 // If no operands then chain to entry token.
12783 if (Aliases.size() == 0)
12784 return DAG.getEntryNode();
12786 // If a single operand then chain to it. We don't need to revisit it.
12787 if (Aliases.size() == 1)
12790 // Construct a custom tailored token factor.
12791 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12794 /// This is the entry point for the file.
12795 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12796 CodeGenOpt::Level OptLevel) {
12797 /// This is the main entry point to this class.
12798 DAGCombiner(*this, AA, OptLevel).Run(Level);