1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitOR(SDNode *N);
250 SDValue visitXOR(SDNode *N);
251 SDValue SimplifyVBinOp(SDNode *N);
252 SDValue SimplifyVUnaryOp(SDNode *N);
253 SDValue visitSHL(SDNode *N);
254 SDValue visitSRA(SDNode *N);
255 SDValue visitSRL(SDNode *N);
256 SDValue visitRotate(SDNode *N);
257 SDValue visitCTLZ(SDNode *N);
258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259 SDValue visitCTTZ(SDNode *N);
260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTPOP(SDNode *N);
262 SDValue visitSELECT(SDNode *N);
263 SDValue visitVSELECT(SDNode *N);
264 SDValue visitSELECT_CC(SDNode *N);
265 SDValue visitSETCC(SDNode *N);
266 SDValue visitSIGN_EXTEND(SDNode *N);
267 SDValue visitZERO_EXTEND(SDNode *N);
268 SDValue visitANY_EXTEND(SDNode *N);
269 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270 SDValue visitTRUNCATE(SDNode *N);
271 SDValue visitBITCAST(SDNode *N);
272 SDValue visitBUILD_PAIR(SDNode *N);
273 SDValue visitFADD(SDNode *N);
274 SDValue visitFSUB(SDNode *N);
275 SDValue visitFMUL(SDNode *N);
276 SDValue visitFMA(SDNode *N);
277 SDValue visitFDIV(SDNode *N);
278 SDValue visitFREM(SDNode *N);
279 SDValue visitFSQRT(SDNode *N);
280 SDValue visitFCOPYSIGN(SDNode *N);
281 SDValue visitSINT_TO_FP(SDNode *N);
282 SDValue visitUINT_TO_FP(SDNode *N);
283 SDValue visitFP_TO_SINT(SDNode *N);
284 SDValue visitFP_TO_UINT(SDNode *N);
285 SDValue visitFP_ROUND(SDNode *N);
286 SDValue visitFP_ROUND_INREG(SDNode *N);
287 SDValue visitFP_EXTEND(SDNode *N);
288 SDValue visitFNEG(SDNode *N);
289 SDValue visitFABS(SDNode *N);
290 SDValue visitFCEIL(SDNode *N);
291 SDValue visitFTRUNC(SDNode *N);
292 SDValue visitFFLOOR(SDNode *N);
293 SDValue visitFMINNUM(SDNode *N);
294 SDValue visitFMAXNUM(SDNode *N);
295 SDValue visitBRCOND(SDNode *N);
296 SDValue visitBR_CC(SDNode *N);
297 SDValue visitLOAD(SDNode *N);
298 SDValue visitSTORE(SDNode *N);
299 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301 SDValue visitBUILD_VECTOR(SDNode *N);
302 SDValue visitCONCAT_VECTORS(SDNode *N);
303 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304 SDValue visitVECTOR_SHUFFLE(SDNode *N);
305 SDValue visitINSERT_SUBVECTOR(SDNode *N);
307 SDValue XformToShuffleWithZero(SDNode *N);
308 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
310 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
312 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
313 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
314 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
315 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
316 SDValue N3, ISD::CondCode CC,
317 bool NotExtCompare = false);
318 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
319 SDLoc DL, bool foldBooleans = true);
321 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
323 bool isOneUseSetCC(SDValue N) const;
325 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
327 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
328 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
329 SDValue BuildSDIV(SDNode *N);
330 SDValue BuildSDIVPow2(SDNode *N);
331 SDValue BuildUDIV(SDNode *N);
332 SDValue BuildReciprocalEstimate(SDValue Op);
333 SDValue BuildRsqrtEstimate(SDValue Op);
334 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
335 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
336 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
337 bool DemandHighBits = true);
338 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
339 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
340 SDValue InnerPos, SDValue InnerNeg,
341 unsigned PosOpcode, unsigned NegOpcode,
343 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
344 SDValue ReduceLoadWidth(SDNode *N);
345 SDValue ReduceLoadOpStoreWidth(SDNode *N);
346 SDValue TransformFPLoadStorePair(SDNode *N);
347 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
348 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
350 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
352 /// Walk up chain skipping non-aliasing memory nodes,
353 /// looking for aliasing nodes and adding them to the Aliases vector.
354 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
355 SmallVectorImpl<SDValue> &Aliases);
357 /// Return true if there is any possibility that the two addresses overlap.
358 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
360 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
361 /// chain (aliasing node.)
362 SDValue FindBetterChain(SDNode *N, SDValue Chain);
364 /// Merge consecutive store operations into a wide store.
365 /// This optimization uses wide integers or vectors when possible.
366 /// \return True if some memory operations were changed.
367 bool MergeConsecutiveStores(StoreSDNode *N);
369 /// \brief Try to transform a truncation where C is a constant:
370 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
372 /// \p N needs to be a truncation and its first operand an AND. Other
373 /// requirements are checked by the function (e.g. that trunc is
374 /// single-use) and if missed an empty SDValue is returned.
375 SDValue distributeTruncateThroughAnd(SDNode *N);
378 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
379 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
380 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
381 AttributeSet FnAttrs =
382 DAG.getMachineFunction().getFunction()->getAttributes();
384 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
385 Attribute::OptimizeForSize) ||
386 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
389 /// Runs the dag combiner on all nodes in the work list
390 void Run(CombineLevel AtLevel);
392 SelectionDAG &getDAG() const { return DAG; }
394 /// Returns a type large enough to hold any valid shift amount - before type
395 /// legalization these can be huge.
396 EVT getShiftAmountTy(EVT LHSTy) {
397 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
398 if (LHSTy.isVector())
400 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
401 : TLI.getPointerTy();
404 /// This method returns true if we are running before type legalization or
405 /// if the specified VT is legal.
406 bool isTypeLegal(const EVT &VT) {
407 if (!LegalTypes) return true;
408 return TLI.isTypeLegal(VT);
411 /// Convenience wrapper around TargetLowering::getSetCCResultType
412 EVT getSetCCResultType(EVT VT) const {
413 return TLI.getSetCCResultType(*DAG.getContext(), VT);
420 /// This class is a DAGUpdateListener that removes any deleted
421 /// nodes from the worklist.
422 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
425 explicit WorklistRemover(DAGCombiner &dc)
426 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
428 void NodeDeleted(SDNode *N, SDNode *E) override {
429 DC.removeFromWorklist(N);
434 //===----------------------------------------------------------------------===//
435 // TargetLowering::DAGCombinerInfo implementation
436 //===----------------------------------------------------------------------===//
438 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
439 ((DAGCombiner*)DC)->AddToWorklist(N);
442 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
443 ((DAGCombiner*)DC)->removeFromWorklist(N);
446 SDValue TargetLowering::DAGCombinerInfo::
447 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
448 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
451 SDValue TargetLowering::DAGCombinerInfo::
452 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
453 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
457 SDValue TargetLowering::DAGCombinerInfo::
458 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
459 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
462 void TargetLowering::DAGCombinerInfo::
463 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
464 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
467 //===----------------------------------------------------------------------===//
469 //===----------------------------------------------------------------------===//
471 void DAGCombiner::deleteAndRecombine(SDNode *N) {
472 removeFromWorklist(N);
474 // If the operands of this node are only used by the node, they will now be
475 // dead. Make sure to re-visit them and recursively delete dead nodes.
476 for (const SDValue &Op : N->ops())
477 // For an operand generating multiple values, one of the values may
478 // become dead allowing further simplification (e.g. split index
479 // arithmetic from an indexed load).
480 if (Op->hasOneUse() || Op->getNumValues() > 1)
481 AddToWorklist(Op.getNode());
486 /// Return 1 if we can compute the negated form of the specified expression for
487 /// the same cost as the expression itself, or 2 if we can compute the negated
488 /// form more cheaply than the expression itself.
489 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
490 const TargetLowering &TLI,
491 const TargetOptions *Options,
492 unsigned Depth = 0) {
493 // fneg is removable even if it has multiple uses.
494 if (Op.getOpcode() == ISD::FNEG) return 2;
496 // Don't allow anything with multiple uses.
497 if (!Op.hasOneUse()) return 0;
499 // Don't recurse exponentially.
500 if (Depth > 6) return 0;
502 switch (Op.getOpcode()) {
503 default: return false;
504 case ISD::ConstantFP:
505 // Don't invert constant FP values after legalize. The negated constant
506 // isn't necessarily legal.
507 return LegalOperations ? 0 : 1;
509 // FIXME: determine better conditions for this xform.
510 if (!Options->UnsafeFPMath) return 0;
512 // After operation legalization, it might not be legal to create new FSUBs.
513 if (LegalOperations &&
514 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
517 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
518 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
521 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
522 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
525 // We can't turn -(A-B) into B-A when we honor signed zeros.
526 if (!Options->UnsafeFPMath) return 0;
528 // fold (fneg (fsub A, B)) -> (fsub B, A)
533 if (Options->HonorSignDependentRoundingFPMath()) return 0;
535 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
536 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
540 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
546 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
551 /// If isNegatibleForFree returns true, return the newly negated expression.
552 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
553 bool LegalOperations, unsigned Depth = 0) {
554 const TargetOptions &Options = DAG.getTarget().Options;
555 // fneg is removable even if it has multiple uses.
556 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
558 // Don't allow anything with multiple uses.
559 assert(Op.hasOneUse() && "Unknown reuse!");
561 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
562 switch (Op.getOpcode()) {
563 default: llvm_unreachable("Unknown code");
564 case ISD::ConstantFP: {
565 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
567 return DAG.getConstantFP(V, Op.getValueType());
570 // FIXME: determine better conditions for this xform.
571 assert(Options.UnsafeFPMath);
573 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
574 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
575 DAG.getTargetLoweringInfo(), &Options, Depth+1))
576 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
577 GetNegatedExpression(Op.getOperand(0), DAG,
578 LegalOperations, Depth+1),
580 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
581 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
582 GetNegatedExpression(Op.getOperand(1), DAG,
583 LegalOperations, Depth+1),
586 // We can't turn -(A-B) into B-A when we honor signed zeros.
587 assert(Options.UnsafeFPMath);
589 // fold (fneg (fsub 0, B)) -> B
590 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
591 if (N0CFP->getValueAPF().isZero())
592 return Op.getOperand(1);
594 // fold (fneg (fsub A, B)) -> (fsub B, A)
595 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
596 Op.getOperand(1), Op.getOperand(0));
600 assert(!Options.HonorSignDependentRoundingFPMath());
602 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
603 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
604 DAG.getTargetLoweringInfo(), &Options, Depth+1))
605 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
606 GetNegatedExpression(Op.getOperand(0), DAG,
607 LegalOperations, Depth+1),
610 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
611 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
613 GetNegatedExpression(Op.getOperand(1), DAG,
614 LegalOperations, Depth+1));
618 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
619 GetNegatedExpression(Op.getOperand(0), DAG,
620 LegalOperations, Depth+1));
622 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
623 GetNegatedExpression(Op.getOperand(0), DAG,
624 LegalOperations, Depth+1),
629 // Return true if this node is a setcc, or is a select_cc
630 // that selects between the target values used for true and false, making it
631 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
632 // the appropriate nodes based on the type of node we are checking. This
633 // simplifies life a bit for the callers.
634 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
636 if (N.getOpcode() == ISD::SETCC) {
637 LHS = N.getOperand(0);
638 RHS = N.getOperand(1);
639 CC = N.getOperand(2);
643 if (N.getOpcode() != ISD::SELECT_CC ||
644 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
645 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
648 LHS = N.getOperand(0);
649 RHS = N.getOperand(1);
650 CC = N.getOperand(4);
654 /// Return true if this is a SetCC-equivalent operation with only one use.
655 /// If this is true, it allows the users to invert the operation for free when
656 /// it is profitable to do so.
657 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
659 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
664 /// Returns true if N is a BUILD_VECTOR node whose
665 /// elements are all the same constant or undefined.
666 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
667 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
672 unsigned SplatBitSize;
674 EVT EltVT = N->getValueType(0).getVectorElementType();
675 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
677 EltVT.getSizeInBits() >= SplatBitSize);
680 // \brief Returns the SDNode if it is a constant BuildVector or constant.
681 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
682 if (isa<ConstantSDNode>(N))
684 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
685 if (BV && BV->isConstant())
690 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
692 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
693 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
696 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
697 BitVector UndefElements;
698 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
700 // BuildVectors can truncate their operands. Ignore that case here.
701 // FIXME: We blindly ignore splats which include undef which is overly
703 if (CN && UndefElements.none() &&
704 CN->getValueType(0) == N.getValueType().getScalarType())
711 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
713 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
714 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
717 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
718 BitVector UndefElements;
719 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
721 if (CN && UndefElements.none())
728 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
729 SDValue N0, SDValue N1) {
730 EVT VT = N0.getValueType();
731 if (N0.getOpcode() == Opc) {
732 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
733 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
734 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
735 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
736 if (!OpNode.getNode())
738 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
740 if (N0.hasOneUse()) {
741 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
743 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
744 if (!OpNode.getNode())
746 AddToWorklist(OpNode.getNode());
747 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
752 if (N1.getOpcode() == Opc) {
753 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
754 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
755 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
756 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
757 if (!OpNode.getNode())
759 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
761 if (N1.hasOneUse()) {
762 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
764 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
765 if (!OpNode.getNode())
767 AddToWorklist(OpNode.getNode());
768 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
776 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
778 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
780 DEBUG(dbgs() << "\nReplacing.1 ";
782 dbgs() << "\nWith: ";
783 To[0].getNode()->dump(&DAG);
784 dbgs() << " and " << NumTo-1 << " other values\n";
785 for (unsigned i = 0, e = NumTo; i != e; ++i)
786 assert((!To[i].getNode() ||
787 N->getValueType(i) == To[i].getValueType()) &&
788 "Cannot combine value to value of different type!"));
789 WorklistRemover DeadNodes(*this);
790 DAG.ReplaceAllUsesWith(N, To);
792 // Push the new nodes and any users onto the worklist
793 for (unsigned i = 0, e = NumTo; i != e; ++i) {
794 if (To[i].getNode()) {
795 AddToWorklist(To[i].getNode());
796 AddUsersToWorklist(To[i].getNode());
801 // Finally, if the node is now dead, remove it from the graph. The node
802 // may not be dead if the replacement process recursively simplified to
803 // something else needing this node.
805 deleteAndRecombine(N);
806 return SDValue(N, 0);
810 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
811 // Replace all uses. If any nodes become isomorphic to other nodes and
812 // are deleted, make sure to remove them from our worklist.
813 WorklistRemover DeadNodes(*this);
814 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
816 // Push the new node and any (possibly new) users onto the worklist.
817 AddToWorklist(TLO.New.getNode());
818 AddUsersToWorklist(TLO.New.getNode());
820 // Finally, if the node is now dead, remove it from the graph. The node
821 // may not be dead if the replacement process recursively simplified to
822 // something else needing this node.
823 if (TLO.Old.getNode()->use_empty())
824 deleteAndRecombine(TLO.Old.getNode());
827 /// Check the specified integer node value to see if it can be simplified or if
828 /// things it uses can be simplified by bit propagation. If so, return true.
829 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
830 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
831 APInt KnownZero, KnownOne;
832 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
836 AddToWorklist(Op.getNode());
838 // Replace the old value with the new one.
840 DEBUG(dbgs() << "\nReplacing.2 ";
841 TLO.Old.getNode()->dump(&DAG);
842 dbgs() << "\nWith: ";
843 TLO.New.getNode()->dump(&DAG);
846 CommitTargetLoweringOpt(TLO);
850 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
852 EVT VT = Load->getValueType(0);
853 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
855 DEBUG(dbgs() << "\nReplacing.9 ";
857 dbgs() << "\nWith: ";
858 Trunc.getNode()->dump(&DAG);
860 WorklistRemover DeadNodes(*this);
861 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
862 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
863 deleteAndRecombine(Load);
864 AddToWorklist(Trunc.getNode());
867 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
870 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
871 EVT MemVT = LD->getMemoryVT();
872 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
873 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
875 : LD->getExtensionType();
877 return DAG.getExtLoad(ExtType, dl, PVT,
878 LD->getChain(), LD->getBasePtr(),
879 MemVT, LD->getMemOperand());
882 unsigned Opc = Op.getOpcode();
885 case ISD::AssertSext:
886 return DAG.getNode(ISD::AssertSext, dl, PVT,
887 SExtPromoteOperand(Op.getOperand(0), PVT),
889 case ISD::AssertZext:
890 return DAG.getNode(ISD::AssertZext, dl, PVT,
891 ZExtPromoteOperand(Op.getOperand(0), PVT),
893 case ISD::Constant: {
895 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
896 return DAG.getNode(ExtOpc, dl, PVT, Op);
900 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
902 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
905 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
906 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
908 EVT OldVT = Op.getValueType();
910 bool Replace = false;
911 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
912 if (!NewOp.getNode())
914 AddToWorklist(NewOp.getNode());
917 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
918 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
919 DAG.getValueType(OldVT));
922 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
923 EVT OldVT = Op.getValueType();
925 bool Replace = false;
926 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
927 if (!NewOp.getNode())
929 AddToWorklist(NewOp.getNode());
932 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
933 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
936 /// Promote the specified integer binary operation if the target indicates it is
937 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
938 /// i32 since i16 instructions are longer.
939 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
940 if (!LegalOperations)
943 EVT VT = Op.getValueType();
944 if (VT.isVector() || !VT.isInteger())
947 // If operation type is 'undesirable', e.g. i16 on x86, consider
949 unsigned Opc = Op.getOpcode();
950 if (TLI.isTypeDesirableForOp(Opc, VT))
954 // Consult target whether it is a good idea to promote this operation and
955 // what's the right type to promote it to.
956 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
957 assert(PVT != VT && "Don't know what type to promote to!");
959 bool Replace0 = false;
960 SDValue N0 = Op.getOperand(0);
961 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
965 bool Replace1 = false;
966 SDValue N1 = Op.getOperand(1);
971 NN1 = PromoteOperand(N1, PVT, Replace1);
976 AddToWorklist(NN0.getNode());
978 AddToWorklist(NN1.getNode());
981 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
983 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
985 DEBUG(dbgs() << "\nPromoting ";
986 Op.getNode()->dump(&DAG));
988 return DAG.getNode(ISD::TRUNCATE, dl, VT,
989 DAG.getNode(Opc, dl, PVT, NN0, NN1));
994 /// Promote the specified integer shift operation if the target indicates it is
995 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
996 /// i32 since i16 instructions are longer.
997 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
998 if (!LegalOperations)
1001 EVT VT = Op.getValueType();
1002 if (VT.isVector() || !VT.isInteger())
1005 // If operation type is 'undesirable', e.g. i16 on x86, consider
1007 unsigned Opc = Op.getOpcode();
1008 if (TLI.isTypeDesirableForOp(Opc, VT))
1012 // Consult target whether it is a good idea to promote this operation and
1013 // what's the right type to promote it to.
1014 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1015 assert(PVT != VT && "Don't know what type to promote to!");
1017 bool Replace = false;
1018 SDValue N0 = Op.getOperand(0);
1019 if (Opc == ISD::SRA)
1020 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1021 else if (Opc == ISD::SRL)
1022 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1024 N0 = PromoteOperand(N0, PVT, Replace);
1028 AddToWorklist(N0.getNode());
1030 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1032 DEBUG(dbgs() << "\nPromoting ";
1033 Op.getNode()->dump(&DAG));
1035 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1036 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1041 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1042 if (!LegalOperations)
1045 EVT VT = Op.getValueType();
1046 if (VT.isVector() || !VT.isInteger())
1049 // If operation type is 'undesirable', e.g. i16 on x86, consider
1051 unsigned Opc = Op.getOpcode();
1052 if (TLI.isTypeDesirableForOp(Opc, VT))
1056 // Consult target whether it is a good idea to promote this operation and
1057 // what's the right type to promote it to.
1058 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1059 assert(PVT != VT && "Don't know what type to promote to!");
1060 // fold (aext (aext x)) -> (aext x)
1061 // fold (aext (zext x)) -> (zext x)
1062 // fold (aext (sext x)) -> (sext x)
1063 DEBUG(dbgs() << "\nPromoting ";
1064 Op.getNode()->dump(&DAG));
1065 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1070 bool DAGCombiner::PromoteLoad(SDValue Op) {
1071 if (!LegalOperations)
1074 EVT VT = Op.getValueType();
1075 if (VT.isVector() || !VT.isInteger())
1078 // If operation type is 'undesirable', e.g. i16 on x86, consider
1080 unsigned Opc = Op.getOpcode();
1081 if (TLI.isTypeDesirableForOp(Opc, VT))
1085 // Consult target whether it is a good idea to promote this operation and
1086 // what's the right type to promote it to.
1087 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1088 assert(PVT != VT && "Don't know what type to promote to!");
1091 SDNode *N = Op.getNode();
1092 LoadSDNode *LD = cast<LoadSDNode>(N);
1093 EVT MemVT = LD->getMemoryVT();
1094 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1095 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1097 : LD->getExtensionType();
1098 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1099 LD->getChain(), LD->getBasePtr(),
1100 MemVT, LD->getMemOperand());
1101 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1103 DEBUG(dbgs() << "\nPromoting ";
1106 Result.getNode()->dump(&DAG);
1108 WorklistRemover DeadNodes(*this);
1109 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1110 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1111 deleteAndRecombine(N);
1112 AddToWorklist(Result.getNode());
1118 /// \brief Recursively delete a node which has no uses and any operands for
1119 /// which it is the only use.
1121 /// Note that this both deletes the nodes and removes them from the worklist.
1122 /// It also adds any nodes who have had a user deleted to the worklist as they
1123 /// may now have only one use and subject to other combines.
1124 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1125 if (!N->use_empty())
1128 SmallSetVector<SDNode *, 16> Nodes;
1131 N = Nodes.pop_back_val();
1135 if (N->use_empty()) {
1136 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1137 Nodes.insert(N->getOperand(i).getNode());
1139 removeFromWorklist(N);
1144 } while (!Nodes.empty());
1148 //===----------------------------------------------------------------------===//
1149 // Main DAG Combiner implementation
1150 //===----------------------------------------------------------------------===//
1152 void DAGCombiner::Run(CombineLevel AtLevel) {
1153 // set the instance variables, so that the various visit routines may use it.
1155 LegalOperations = Level >= AfterLegalizeVectorOps;
1156 LegalTypes = Level >= AfterLegalizeTypes;
1158 // Early exit if this basic block is in an optnone function.
1159 AttributeSet FnAttrs =
1160 DAG.getMachineFunction().getFunction()->getAttributes();
1161 if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1162 Attribute::OptimizeNone))
1165 // Add all the dag nodes to the worklist.
1166 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1167 E = DAG.allnodes_end(); I != E; ++I)
1170 // Create a dummy node (which is not added to allnodes), that adds a reference
1171 // to the root node, preventing it from being deleted, and tracking any
1172 // changes of the root.
1173 HandleSDNode Dummy(DAG.getRoot());
1175 // while the worklist isn't empty, find a node and
1176 // try and combine it.
1177 while (!WorklistMap.empty()) {
1179 // The Worklist holds the SDNodes in order, but it may contain null entries.
1181 N = Worklist.pop_back_val();
1184 bool GoodWorklistEntry = WorklistMap.erase(N);
1185 (void)GoodWorklistEntry;
1186 assert(GoodWorklistEntry &&
1187 "Found a worklist entry without a corresponding map entry!");
1189 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1190 // N is deleted from the DAG, since they too may now be dead or may have a
1191 // reduced number of uses, allowing other xforms.
1192 if (recursivelyDeleteUnusedNodes(N))
1195 WorklistRemover DeadNodes(*this);
1197 // If this combine is running after legalizing the DAG, re-legalize any
1198 // nodes pulled off the worklist.
1199 if (Level == AfterLegalizeDAG) {
1200 SmallSetVector<SDNode *, 16> UpdatedNodes;
1201 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1203 for (SDNode *LN : UpdatedNodes) {
1205 AddUsersToWorklist(LN);
1211 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1213 // Add any operands of the new node which have not yet been combined to the
1214 // worklist as well. Because the worklist uniques things already, this
1215 // won't repeatedly process the same operand.
1216 CombinedNodes.insert(N);
1217 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1218 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1219 AddToWorklist(N->getOperand(i).getNode());
1221 SDValue RV = combine(N);
1228 // If we get back the same node we passed in, rather than a new node or
1229 // zero, we know that the node must have defined multiple values and
1230 // CombineTo was used. Since CombineTo takes care of the worklist
1231 // mechanics for us, we have no work to do in this case.
1232 if (RV.getNode() == N)
1235 assert(N->getOpcode() != ISD::DELETED_NODE &&
1236 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1237 "Node was deleted but visit returned new node!");
1239 DEBUG(dbgs() << " ... into: ";
1240 RV.getNode()->dump(&DAG));
1242 // Transfer debug value.
1243 DAG.TransferDbgValues(SDValue(N, 0), RV);
1244 if (N->getNumValues() == RV.getNode()->getNumValues())
1245 DAG.ReplaceAllUsesWith(N, RV.getNode());
1247 assert(N->getValueType(0) == RV.getValueType() &&
1248 N->getNumValues() == 1 && "Type mismatch");
1250 DAG.ReplaceAllUsesWith(N, &OpV);
1253 // Push the new node and any users onto the worklist
1254 AddToWorklist(RV.getNode());
1255 AddUsersToWorklist(RV.getNode());
1257 // Finally, if the node is now dead, remove it from the graph. The node
1258 // may not be dead if the replacement process recursively simplified to
1259 // something else needing this node. This will also take care of adding any
1260 // operands which have lost a user to the worklist.
1261 recursivelyDeleteUnusedNodes(N);
1264 // If the root changed (e.g. it was a dead load, update the root).
1265 DAG.setRoot(Dummy.getValue());
1266 DAG.RemoveDeadNodes();
1269 SDValue DAGCombiner::visit(SDNode *N) {
1270 switch (N->getOpcode()) {
1272 case ISD::TokenFactor: return visitTokenFactor(N);
1273 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1274 case ISD::ADD: return visitADD(N);
1275 case ISD::SUB: return visitSUB(N);
1276 case ISD::ADDC: return visitADDC(N);
1277 case ISD::SUBC: return visitSUBC(N);
1278 case ISD::ADDE: return visitADDE(N);
1279 case ISD::SUBE: return visitSUBE(N);
1280 case ISD::MUL: return visitMUL(N);
1281 case ISD::SDIV: return visitSDIV(N);
1282 case ISD::UDIV: return visitUDIV(N);
1283 case ISD::SREM: return visitSREM(N);
1284 case ISD::UREM: return visitUREM(N);
1285 case ISD::MULHU: return visitMULHU(N);
1286 case ISD::MULHS: return visitMULHS(N);
1287 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1288 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1289 case ISD::SMULO: return visitSMULO(N);
1290 case ISD::UMULO: return visitUMULO(N);
1291 case ISD::SDIVREM: return visitSDIVREM(N);
1292 case ISD::UDIVREM: return visitUDIVREM(N);
1293 case ISD::AND: return visitAND(N);
1294 case ISD::OR: return visitOR(N);
1295 case ISD::XOR: return visitXOR(N);
1296 case ISD::SHL: return visitSHL(N);
1297 case ISD::SRA: return visitSRA(N);
1298 case ISD::SRL: return visitSRL(N);
1300 case ISD::ROTL: return visitRotate(N);
1301 case ISD::CTLZ: return visitCTLZ(N);
1302 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1303 case ISD::CTTZ: return visitCTTZ(N);
1304 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1305 case ISD::CTPOP: return visitCTPOP(N);
1306 case ISD::SELECT: return visitSELECT(N);
1307 case ISD::VSELECT: return visitVSELECT(N);
1308 case ISD::SELECT_CC: return visitSELECT_CC(N);
1309 case ISD::SETCC: return visitSETCC(N);
1310 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1311 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1312 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1313 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1314 case ISD::TRUNCATE: return visitTRUNCATE(N);
1315 case ISD::BITCAST: return visitBITCAST(N);
1316 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1317 case ISD::FADD: return visitFADD(N);
1318 case ISD::FSUB: return visitFSUB(N);
1319 case ISD::FMUL: return visitFMUL(N);
1320 case ISD::FMA: return visitFMA(N);
1321 case ISD::FDIV: return visitFDIV(N);
1322 case ISD::FREM: return visitFREM(N);
1323 case ISD::FSQRT: return visitFSQRT(N);
1324 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1325 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1326 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1327 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1328 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1329 case ISD::FP_ROUND: return visitFP_ROUND(N);
1330 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1331 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1332 case ISD::FNEG: return visitFNEG(N);
1333 case ISD::FABS: return visitFABS(N);
1334 case ISD::FFLOOR: return visitFFLOOR(N);
1335 case ISD::FMINNUM: return visitFMINNUM(N);
1336 case ISD::FMAXNUM: return visitFMAXNUM(N);
1337 case ISD::FCEIL: return visitFCEIL(N);
1338 case ISD::FTRUNC: return visitFTRUNC(N);
1339 case ISD::BRCOND: return visitBRCOND(N);
1340 case ISD::BR_CC: return visitBR_CC(N);
1341 case ISD::LOAD: return visitLOAD(N);
1342 case ISD::STORE: return visitSTORE(N);
1343 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1344 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1345 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1346 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1347 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1348 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1349 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1354 SDValue DAGCombiner::combine(SDNode *N) {
1355 SDValue RV = visit(N);
1357 // If nothing happened, try a target-specific DAG combine.
1358 if (!RV.getNode()) {
1359 assert(N->getOpcode() != ISD::DELETED_NODE &&
1360 "Node was deleted but visit returned NULL!");
1362 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1363 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1365 // Expose the DAG combiner to the target combiner impls.
1366 TargetLowering::DAGCombinerInfo
1367 DagCombineInfo(DAG, Level, false, this);
1369 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1373 // If nothing happened still, try promoting the operation.
1374 if (!RV.getNode()) {
1375 switch (N->getOpcode()) {
1383 RV = PromoteIntBinOp(SDValue(N, 0));
1388 RV = PromoteIntShiftOp(SDValue(N, 0));
1390 case ISD::SIGN_EXTEND:
1391 case ISD::ZERO_EXTEND:
1392 case ISD::ANY_EXTEND:
1393 RV = PromoteExtend(SDValue(N, 0));
1396 if (PromoteLoad(SDValue(N, 0)))
1402 // If N is a commutative binary node, try commuting it to enable more
1404 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1405 N->getNumValues() == 1) {
1406 SDValue N0 = N->getOperand(0);
1407 SDValue N1 = N->getOperand(1);
1409 // Constant operands are canonicalized to RHS.
1410 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1411 SDValue Ops[] = {N1, N0};
1413 if (const BinaryWithFlagsSDNode *BinNode =
1414 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1415 CSENode = DAG.getNodeIfExists(
1416 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1417 BinNode->hasNoSignedWrap(), BinNode->isExact());
1419 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1422 return SDValue(CSENode, 0);
1429 /// Given a node, return its input chain if it has one, otherwise return a null
1431 static SDValue getInputChainForNode(SDNode *N) {
1432 if (unsigned NumOps = N->getNumOperands()) {
1433 if (N->getOperand(0).getValueType() == MVT::Other)
1434 return N->getOperand(0);
1435 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1436 return N->getOperand(NumOps-1);
1437 for (unsigned i = 1; i < NumOps-1; ++i)
1438 if (N->getOperand(i).getValueType() == MVT::Other)
1439 return N->getOperand(i);
1444 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1445 // If N has two operands, where one has an input chain equal to the other,
1446 // the 'other' chain is redundant.
1447 if (N->getNumOperands() == 2) {
1448 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1449 return N->getOperand(0);
1450 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1451 return N->getOperand(1);
1454 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1455 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1456 SmallPtrSet<SDNode*, 16> SeenOps;
1457 bool Changed = false; // If we should replace this token factor.
1459 // Start out with this token factor.
1462 // Iterate through token factors. The TFs grows when new token factors are
1464 for (unsigned i = 0; i < TFs.size(); ++i) {
1465 SDNode *TF = TFs[i];
1467 // Check each of the operands.
1468 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1469 SDValue Op = TF->getOperand(i);
1471 switch (Op.getOpcode()) {
1472 case ISD::EntryToken:
1473 // Entry tokens don't need to be added to the list. They are
1478 case ISD::TokenFactor:
1479 if (Op.hasOneUse() &&
1480 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1481 // Queue up for processing.
1482 TFs.push_back(Op.getNode());
1483 // Clean up in case the token factor is removed.
1484 AddToWorklist(Op.getNode());
1491 // Only add if it isn't already in the list.
1492 if (SeenOps.insert(Op.getNode()))
1503 // If we've change things around then replace token factor.
1506 // The entry token is the only possible outcome.
1507 Result = DAG.getEntryNode();
1509 // New and improved token factor.
1510 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1513 // Don't add users to work list.
1514 return CombineTo(N, Result, false);
1520 /// MERGE_VALUES can always be eliminated.
1521 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1522 WorklistRemover DeadNodes(*this);
1523 // Replacing results may cause a different MERGE_VALUES to suddenly
1524 // be CSE'd with N, and carry its uses with it. Iterate until no
1525 // uses remain, to ensure that the node can be safely deleted.
1526 // First add the users of this node to the work list so that they
1527 // can be tried again once they have new operands.
1528 AddUsersToWorklist(N);
1530 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1531 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1532 } while (!N->use_empty());
1533 deleteAndRecombine(N);
1534 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1537 SDValue DAGCombiner::visitADD(SDNode *N) {
1538 SDValue N0 = N->getOperand(0);
1539 SDValue N1 = N->getOperand(1);
1540 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1541 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1542 EVT VT = N0.getValueType();
1545 if (VT.isVector()) {
1546 SDValue FoldedVOp = SimplifyVBinOp(N);
1547 if (FoldedVOp.getNode()) return FoldedVOp;
1549 // fold (add x, 0) -> x, vector edition
1550 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1552 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1556 // fold (add x, undef) -> undef
1557 if (N0.getOpcode() == ISD::UNDEF)
1559 if (N1.getOpcode() == ISD::UNDEF)
1561 // fold (add c1, c2) -> c1+c2
1563 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1564 // canonicalize constant to RHS
1566 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1567 // fold (add x, 0) -> x
1568 if (N1C && N1C->isNullValue())
1570 // fold (add Sym, c) -> Sym+c
1571 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1572 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1573 GA->getOpcode() == ISD::GlobalAddress)
1574 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1576 (uint64_t)N1C->getSExtValue());
1577 // fold ((c1-A)+c2) -> (c1+c2)-A
1578 if (N1C && N0.getOpcode() == ISD::SUB)
1579 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1580 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1581 DAG.getConstant(N1C->getAPIntValue()+
1582 N0C->getAPIntValue(), VT),
1585 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1588 // fold ((0-A) + B) -> B-A
1589 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1590 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1591 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1592 // fold (A + (0-B)) -> A-B
1593 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1594 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1595 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1596 // fold (A+(B-A)) -> B
1597 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1598 return N1.getOperand(0);
1599 // fold ((B-A)+A) -> B
1600 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1601 return N0.getOperand(0);
1602 // fold (A+(B-(A+C))) to (B-C)
1603 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1604 N0 == N1.getOperand(1).getOperand(0))
1605 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1606 N1.getOperand(1).getOperand(1));
1607 // fold (A+(B-(C+A))) to (B-C)
1608 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1609 N0 == N1.getOperand(1).getOperand(1))
1610 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1611 N1.getOperand(1).getOperand(0));
1612 // fold (A+((B-A)+or-C)) to (B+or-C)
1613 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1614 N1.getOperand(0).getOpcode() == ISD::SUB &&
1615 N0 == N1.getOperand(0).getOperand(1))
1616 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1617 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1619 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1620 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1621 SDValue N00 = N0.getOperand(0);
1622 SDValue N01 = N0.getOperand(1);
1623 SDValue N10 = N1.getOperand(0);
1624 SDValue N11 = N1.getOperand(1);
1626 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1627 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1628 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1629 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1632 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1633 return SDValue(N, 0);
1635 // fold (a+b) -> (a|b) iff a and b share no bits.
1636 if (VT.isInteger() && !VT.isVector()) {
1637 APInt LHSZero, LHSOne;
1638 APInt RHSZero, RHSOne;
1639 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1641 if (LHSZero.getBoolValue()) {
1642 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1644 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1645 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1646 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1647 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1648 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1653 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1654 if (N1.getOpcode() == ISD::SHL &&
1655 N1.getOperand(0).getOpcode() == ISD::SUB)
1656 if (ConstantSDNode *C =
1657 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1658 if (C->getAPIntValue() == 0)
1659 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1660 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1661 N1.getOperand(0).getOperand(1),
1663 if (N0.getOpcode() == ISD::SHL &&
1664 N0.getOperand(0).getOpcode() == ISD::SUB)
1665 if (ConstantSDNode *C =
1666 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1667 if (C->getAPIntValue() == 0)
1668 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1669 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1670 N0.getOperand(0).getOperand(1),
1673 if (N1.getOpcode() == ISD::AND) {
1674 SDValue AndOp0 = N1.getOperand(0);
1675 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1676 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1677 unsigned DestBits = VT.getScalarType().getSizeInBits();
1679 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1680 // and similar xforms where the inner op is either ~0 or 0.
1681 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1683 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1687 // add (sext i1), X -> sub X, (zext i1)
1688 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1689 N0.getOperand(0).getValueType() == MVT::i1 &&
1690 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1692 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1693 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1696 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1697 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1698 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1699 if (TN->getVT() == MVT::i1) {
1701 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1702 DAG.getConstant(1, VT));
1703 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1710 SDValue DAGCombiner::visitADDC(SDNode *N) {
1711 SDValue N0 = N->getOperand(0);
1712 SDValue N1 = N->getOperand(1);
1713 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1714 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1715 EVT VT = N0.getValueType();
1717 // If the flag result is dead, turn this into an ADD.
1718 if (!N->hasAnyUseOfValue(1))
1719 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1720 DAG.getNode(ISD::CARRY_FALSE,
1721 SDLoc(N), MVT::Glue));
1723 // canonicalize constant to RHS.
1725 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1727 // fold (addc x, 0) -> x + no carry out
1728 if (N1C && N1C->isNullValue())
1729 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1730 SDLoc(N), MVT::Glue));
1732 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1733 APInt LHSZero, LHSOne;
1734 APInt RHSZero, RHSOne;
1735 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1737 if (LHSZero.getBoolValue()) {
1738 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1740 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1741 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1742 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1743 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1744 DAG.getNode(ISD::CARRY_FALSE,
1745 SDLoc(N), MVT::Glue));
1751 SDValue DAGCombiner::visitADDE(SDNode *N) {
1752 SDValue N0 = N->getOperand(0);
1753 SDValue N1 = N->getOperand(1);
1754 SDValue CarryIn = N->getOperand(2);
1755 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1756 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1758 // canonicalize constant to RHS
1760 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1763 // fold (adde x, y, false) -> (addc x, y)
1764 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1765 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1770 // Since it may not be valid to emit a fold to zero for vector initializers
1771 // check if we can before folding.
1772 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1774 bool LegalOperations, bool LegalTypes) {
1776 return DAG.getConstant(0, VT);
1777 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1778 return DAG.getConstant(0, VT);
1782 SDValue DAGCombiner::visitSUB(SDNode *N) {
1783 SDValue N0 = N->getOperand(0);
1784 SDValue N1 = N->getOperand(1);
1785 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1786 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1787 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1788 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1789 EVT VT = N0.getValueType();
1792 if (VT.isVector()) {
1793 SDValue FoldedVOp = SimplifyVBinOp(N);
1794 if (FoldedVOp.getNode()) return FoldedVOp;
1796 // fold (sub x, 0) -> x, vector edition
1797 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1801 // fold (sub x, x) -> 0
1802 // FIXME: Refactor this and xor and other similar operations together.
1804 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1805 // fold (sub c1, c2) -> c1-c2
1807 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1808 // fold (sub x, c) -> (add x, -c)
1810 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1811 DAG.getConstant(-N1C->getAPIntValue(), VT));
1812 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1813 if (N0C && N0C->isAllOnesValue())
1814 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1815 // fold A-(A-B) -> B
1816 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1817 return N1.getOperand(1);
1818 // fold (A+B)-A -> B
1819 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1820 return N0.getOperand(1);
1821 // fold (A+B)-B -> A
1822 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1823 return N0.getOperand(0);
1824 // fold C2-(A+C1) -> (C2-C1)-A
1825 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1826 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1828 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1831 // fold ((A+(B+or-C))-B) -> A+or-C
1832 if (N0.getOpcode() == ISD::ADD &&
1833 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1834 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1835 N0.getOperand(1).getOperand(0) == N1)
1836 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1837 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1838 // fold ((A+(C+B))-B) -> A+C
1839 if (N0.getOpcode() == ISD::ADD &&
1840 N0.getOperand(1).getOpcode() == ISD::ADD &&
1841 N0.getOperand(1).getOperand(1) == N1)
1842 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1843 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1844 // fold ((A-(B-C))-C) -> A-B
1845 if (N0.getOpcode() == ISD::SUB &&
1846 N0.getOperand(1).getOpcode() == ISD::SUB &&
1847 N0.getOperand(1).getOperand(1) == N1)
1848 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1851 // If either operand of a sub is undef, the result is undef
1852 if (N0.getOpcode() == ISD::UNDEF)
1854 if (N1.getOpcode() == ISD::UNDEF)
1857 // If the relocation model supports it, consider symbol offsets.
1858 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1859 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1860 // fold (sub Sym, c) -> Sym-c
1861 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1862 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1864 (uint64_t)N1C->getSExtValue());
1865 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1866 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1867 if (GA->getGlobal() == GB->getGlobal())
1868 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1872 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1873 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1874 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1875 if (TN->getVT() == MVT::i1) {
1877 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1878 DAG.getConstant(1, VT));
1879 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1886 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1887 SDValue N0 = N->getOperand(0);
1888 SDValue N1 = N->getOperand(1);
1889 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1890 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1891 EVT VT = N0.getValueType();
1893 // If the flag result is dead, turn this into an SUB.
1894 if (!N->hasAnyUseOfValue(1))
1895 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1896 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1899 // fold (subc x, x) -> 0 + no borrow
1901 return CombineTo(N, DAG.getConstant(0, VT),
1902 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1905 // fold (subc x, 0) -> x + no borrow
1906 if (N1C && N1C->isNullValue())
1907 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1910 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1911 if (N0C && N0C->isAllOnesValue())
1912 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1913 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1919 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1920 SDValue N0 = N->getOperand(0);
1921 SDValue N1 = N->getOperand(1);
1922 SDValue CarryIn = N->getOperand(2);
1924 // fold (sube x, y, false) -> (subc x, y)
1925 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1926 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1931 SDValue DAGCombiner::visitMUL(SDNode *N) {
1932 SDValue N0 = N->getOperand(0);
1933 SDValue N1 = N->getOperand(1);
1934 EVT VT = N0.getValueType();
1936 // fold (mul x, undef) -> 0
1937 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1938 return DAG.getConstant(0, VT);
1940 bool N0IsConst = false;
1941 bool N1IsConst = false;
1942 APInt ConstValue0, ConstValue1;
1944 if (VT.isVector()) {
1945 SDValue FoldedVOp = SimplifyVBinOp(N);
1946 if (FoldedVOp.getNode()) return FoldedVOp;
1948 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1949 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1951 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1952 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1954 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1955 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1959 // fold (mul c1, c2) -> c1*c2
1960 if (N0IsConst && N1IsConst)
1961 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1963 // canonicalize constant to RHS
1964 if (N0IsConst && !N1IsConst)
1965 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1966 // fold (mul x, 0) -> 0
1967 if (N1IsConst && ConstValue1 == 0)
1969 // We require a splat of the entire scalar bit width for non-contiguous
1972 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1973 // fold (mul x, 1) -> x
1974 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1976 // fold (mul x, -1) -> 0-x
1977 if (N1IsConst && ConstValue1.isAllOnesValue())
1978 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1979 DAG.getConstant(0, VT), N0);
1980 // fold (mul x, (1 << c)) -> x << c
1981 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1982 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1983 DAG.getConstant(ConstValue1.logBase2(),
1984 getShiftAmountTy(N0.getValueType())));
1985 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1986 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1987 unsigned Log2Val = (-ConstValue1).logBase2();
1988 // FIXME: If the input is something that is easily negated (e.g. a
1989 // single-use add), we should put the negate there.
1990 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1991 DAG.getConstant(0, VT),
1992 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1993 DAG.getConstant(Log2Val,
1994 getShiftAmountTy(N0.getValueType()))));
1998 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1999 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2000 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2001 isa<ConstantSDNode>(N0.getOperand(1)))) {
2002 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2003 N1, N0.getOperand(1));
2004 AddToWorklist(C3.getNode());
2005 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2006 N0.getOperand(0), C3);
2009 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2012 SDValue Sh(nullptr,0), Y(nullptr,0);
2013 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2014 if (N0.getOpcode() == ISD::SHL &&
2015 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2016 isa<ConstantSDNode>(N0.getOperand(1))) &&
2017 N0.getNode()->hasOneUse()) {
2019 } else if (N1.getOpcode() == ISD::SHL &&
2020 isa<ConstantSDNode>(N1.getOperand(1)) &&
2021 N1.getNode()->hasOneUse()) {
2026 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2027 Sh.getOperand(0), Y);
2028 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2029 Mul, Sh.getOperand(1));
2033 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2034 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2035 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2036 isa<ConstantSDNode>(N0.getOperand(1))))
2037 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2038 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2039 N0.getOperand(0), N1),
2040 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2041 N0.getOperand(1), N1));
2044 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2051 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2052 SDValue N0 = N->getOperand(0);
2053 SDValue N1 = N->getOperand(1);
2054 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2055 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2056 EVT VT = N->getValueType(0);
2059 if (VT.isVector()) {
2060 SDValue FoldedVOp = SimplifyVBinOp(N);
2061 if (FoldedVOp.getNode()) return FoldedVOp;
2064 // fold (sdiv c1, c2) -> c1/c2
2065 if (N0C && N1C && !N1C->isNullValue())
2066 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2067 // fold (sdiv X, 1) -> X
2068 if (N1C && N1C->getAPIntValue() == 1LL)
2070 // fold (sdiv X, -1) -> 0-X
2071 if (N1C && N1C->isAllOnesValue())
2072 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2073 DAG.getConstant(0, VT), N0);
2074 // If we know the sign bits of both operands are zero, strength reduce to a
2075 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2076 if (!VT.isVector()) {
2077 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2078 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2082 // fold (sdiv X, pow2) -> simple ops after legalize
2083 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2084 (-N1C->getAPIntValue()).isPowerOf2())) {
2085 // If dividing by powers of two is cheap, then don't perform the following
2087 if (TLI.isPow2SDivCheap())
2090 // Target-specific implementation of sdiv x, pow2.
2091 SDValue Res = BuildSDIVPow2(N);
2095 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2097 // Splat the sign bit into the register
2099 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2100 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2101 getShiftAmountTy(N0.getValueType())));
2102 AddToWorklist(SGN.getNode());
2104 // Add (N0 < 0) ? abs2 - 1 : 0;
2106 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2107 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2108 getShiftAmountTy(SGN.getValueType())));
2109 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2110 AddToWorklist(SRL.getNode());
2111 AddToWorklist(ADD.getNode()); // Divide by pow2
2112 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2113 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2115 // If we're dividing by a positive value, we're done. Otherwise, we must
2116 // negate the result.
2117 if (N1C->getAPIntValue().isNonNegative())
2120 AddToWorklist(SRA.getNode());
2121 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2124 // if integer divide is expensive and we satisfy the requirements, emit an
2125 // alternate sequence.
2126 if (N1C && !TLI.isIntDivCheap()) {
2127 SDValue Op = BuildSDIV(N);
2128 if (Op.getNode()) return Op;
2132 if (N0.getOpcode() == ISD::UNDEF)
2133 return DAG.getConstant(0, VT);
2134 // X / undef -> undef
2135 if (N1.getOpcode() == ISD::UNDEF)
2141 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2142 SDValue N0 = N->getOperand(0);
2143 SDValue N1 = N->getOperand(1);
2144 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2145 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2146 EVT VT = N->getValueType(0);
2149 if (VT.isVector()) {
2150 SDValue FoldedVOp = SimplifyVBinOp(N);
2151 if (FoldedVOp.getNode()) return FoldedVOp;
2154 // fold (udiv c1, c2) -> c1/c2
2155 if (N0C && N1C && !N1C->isNullValue())
2156 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2157 // fold (udiv x, (1 << c)) -> x >>u c
2158 if (N1C && N1C->getAPIntValue().isPowerOf2())
2159 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2160 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2161 getShiftAmountTy(N0.getValueType())));
2162 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2163 if (N1.getOpcode() == ISD::SHL) {
2164 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2165 if (SHC->getAPIntValue().isPowerOf2()) {
2166 EVT ADDVT = N1.getOperand(1).getValueType();
2167 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2169 DAG.getConstant(SHC->getAPIntValue()
2172 AddToWorklist(Add.getNode());
2173 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2177 // fold (udiv x, c) -> alternate
2178 if (N1C && !TLI.isIntDivCheap()) {
2179 SDValue Op = BuildUDIV(N);
2180 if (Op.getNode()) return Op;
2184 if (N0.getOpcode() == ISD::UNDEF)
2185 return DAG.getConstant(0, VT);
2186 // X / undef -> undef
2187 if (N1.getOpcode() == ISD::UNDEF)
2193 SDValue DAGCombiner::visitSREM(SDNode *N) {
2194 SDValue N0 = N->getOperand(0);
2195 SDValue N1 = N->getOperand(1);
2196 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2197 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2198 EVT VT = N->getValueType(0);
2200 // fold (srem c1, c2) -> c1%c2
2201 if (N0C && N1C && !N1C->isNullValue())
2202 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2203 // If we know the sign bits of both operands are zero, strength reduce to a
2204 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2205 if (!VT.isVector()) {
2206 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2207 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2210 // If X/C can be simplified by the division-by-constant logic, lower
2211 // X%C to the equivalent of X-X/C*C.
2212 if (N1C && !N1C->isNullValue()) {
2213 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2214 AddToWorklist(Div.getNode());
2215 SDValue OptimizedDiv = combine(Div.getNode());
2216 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2217 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2219 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2220 AddToWorklist(Mul.getNode());
2226 if (N0.getOpcode() == ISD::UNDEF)
2227 return DAG.getConstant(0, VT);
2228 // X % undef -> undef
2229 if (N1.getOpcode() == ISD::UNDEF)
2235 SDValue DAGCombiner::visitUREM(SDNode *N) {
2236 SDValue N0 = N->getOperand(0);
2237 SDValue N1 = N->getOperand(1);
2238 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2239 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2240 EVT VT = N->getValueType(0);
2242 // fold (urem c1, c2) -> c1%c2
2243 if (N0C && N1C && !N1C->isNullValue())
2244 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2245 // fold (urem x, pow2) -> (and x, pow2-1)
2246 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2247 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2248 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2249 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2250 if (N1.getOpcode() == ISD::SHL) {
2251 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2252 if (SHC->getAPIntValue().isPowerOf2()) {
2254 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2255 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2257 AddToWorklist(Add.getNode());
2258 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2263 // If X/C can be simplified by the division-by-constant logic, lower
2264 // X%C to the equivalent of X-X/C*C.
2265 if (N1C && !N1C->isNullValue()) {
2266 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2267 AddToWorklist(Div.getNode());
2268 SDValue OptimizedDiv = combine(Div.getNode());
2269 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2270 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2272 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2273 AddToWorklist(Mul.getNode());
2279 if (N0.getOpcode() == ISD::UNDEF)
2280 return DAG.getConstant(0, VT);
2281 // X % undef -> undef
2282 if (N1.getOpcode() == ISD::UNDEF)
2288 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2289 SDValue N0 = N->getOperand(0);
2290 SDValue N1 = N->getOperand(1);
2291 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2292 EVT VT = N->getValueType(0);
2295 // fold (mulhs x, 0) -> 0
2296 if (N1C && N1C->isNullValue())
2298 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2299 if (N1C && N1C->getAPIntValue() == 1)
2300 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2301 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2302 getShiftAmountTy(N0.getValueType())));
2303 // fold (mulhs x, undef) -> 0
2304 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2305 return DAG.getConstant(0, VT);
2307 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2309 if (VT.isSimple() && !VT.isVector()) {
2310 MVT Simple = VT.getSimpleVT();
2311 unsigned SimpleSize = Simple.getSizeInBits();
2312 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2313 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2314 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2315 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2316 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2317 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2318 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2319 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2326 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2327 SDValue N0 = N->getOperand(0);
2328 SDValue N1 = N->getOperand(1);
2329 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2330 EVT VT = N->getValueType(0);
2333 // fold (mulhu x, 0) -> 0
2334 if (N1C && N1C->isNullValue())
2336 // fold (mulhu x, 1) -> 0
2337 if (N1C && N1C->getAPIntValue() == 1)
2338 return DAG.getConstant(0, N0.getValueType());
2339 // fold (mulhu x, undef) -> 0
2340 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2341 return DAG.getConstant(0, VT);
2343 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2345 if (VT.isSimple() && !VT.isVector()) {
2346 MVT Simple = VT.getSimpleVT();
2347 unsigned SimpleSize = Simple.getSizeInBits();
2348 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2349 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2350 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2351 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2352 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2353 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2354 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2355 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2362 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2363 /// give the opcodes for the two computations that are being performed. Return
2364 /// true if a simplification was made.
2365 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2367 // If the high half is not needed, just compute the low half.
2368 bool HiExists = N->hasAnyUseOfValue(1);
2370 (!LegalOperations ||
2371 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2372 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2373 return CombineTo(N, Res, Res);
2376 // If the low half is not needed, just compute the high half.
2377 bool LoExists = N->hasAnyUseOfValue(0);
2379 (!LegalOperations ||
2380 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2381 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2382 return CombineTo(N, Res, Res);
2385 // If both halves are used, return as it is.
2386 if (LoExists && HiExists)
2389 // If the two computed results can be simplified separately, separate them.
2391 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2392 AddToWorklist(Lo.getNode());
2393 SDValue LoOpt = combine(Lo.getNode());
2394 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2395 (!LegalOperations ||
2396 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2397 return CombineTo(N, LoOpt, LoOpt);
2401 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2402 AddToWorklist(Hi.getNode());
2403 SDValue HiOpt = combine(Hi.getNode());
2404 if (HiOpt.getNode() && HiOpt != Hi &&
2405 (!LegalOperations ||
2406 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2407 return CombineTo(N, HiOpt, HiOpt);
2413 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2414 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2415 if (Res.getNode()) return Res;
2417 EVT VT = N->getValueType(0);
2420 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2422 if (VT.isSimple() && !VT.isVector()) {
2423 MVT Simple = VT.getSimpleVT();
2424 unsigned SimpleSize = Simple.getSizeInBits();
2425 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2426 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2427 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2428 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2429 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2430 // Compute the high part as N1.
2431 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2432 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2433 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2434 // Compute the low part as N0.
2435 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2436 return CombineTo(N, Lo, Hi);
2443 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2444 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2445 if (Res.getNode()) return Res;
2447 EVT VT = N->getValueType(0);
2450 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2452 if (VT.isSimple() && !VT.isVector()) {
2453 MVT Simple = VT.getSimpleVT();
2454 unsigned SimpleSize = Simple.getSizeInBits();
2455 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2456 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2457 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2458 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2459 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2460 // Compute the high part as N1.
2461 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2462 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2463 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2464 // Compute the low part as N0.
2465 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2466 return CombineTo(N, Lo, Hi);
2473 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2474 // (smulo x, 2) -> (saddo x, x)
2475 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2476 if (C2->getAPIntValue() == 2)
2477 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2478 N->getOperand(0), N->getOperand(0));
2483 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2484 // (umulo x, 2) -> (uaddo x, x)
2485 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2486 if (C2->getAPIntValue() == 2)
2487 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2488 N->getOperand(0), N->getOperand(0));
2493 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2494 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2495 if (Res.getNode()) return Res;
2500 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2501 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2502 if (Res.getNode()) return Res;
2507 /// If this is a binary operator with two operands of the same opcode, try to
2509 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2510 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2511 EVT VT = N0.getValueType();
2512 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2514 // Bail early if none of these transforms apply.
2515 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2517 // For each of OP in AND/OR/XOR:
2518 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2519 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2520 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2521 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2523 // do not sink logical op inside of a vector extend, since it may combine
2525 EVT Op0VT = N0.getOperand(0).getValueType();
2526 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2527 N0.getOpcode() == ISD::SIGN_EXTEND ||
2528 // Avoid infinite looping with PromoteIntBinOp.
2529 (N0.getOpcode() == ISD::ANY_EXTEND &&
2530 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2531 (N0.getOpcode() == ISD::TRUNCATE &&
2532 (!TLI.isZExtFree(VT, Op0VT) ||
2533 !TLI.isTruncateFree(Op0VT, VT)) &&
2534 TLI.isTypeLegal(Op0VT))) &&
2536 Op0VT == N1.getOperand(0).getValueType() &&
2537 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2538 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2539 N0.getOperand(0).getValueType(),
2540 N0.getOperand(0), N1.getOperand(0));
2541 AddToWorklist(ORNode.getNode());
2542 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2545 // For each of OP in SHL/SRL/SRA/AND...
2546 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2547 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2548 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2549 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2550 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2551 N0.getOperand(1) == N1.getOperand(1)) {
2552 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2553 N0.getOperand(0).getValueType(),
2554 N0.getOperand(0), N1.getOperand(0));
2555 AddToWorklist(ORNode.getNode());
2556 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2557 ORNode, N0.getOperand(1));
2560 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2561 // Only perform this optimization after type legalization and before
2562 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2563 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2564 // we don't want to undo this promotion.
2565 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2567 if ((N0.getOpcode() == ISD::BITCAST ||
2568 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2569 Level == AfterLegalizeTypes) {
2570 SDValue In0 = N0.getOperand(0);
2571 SDValue In1 = N1.getOperand(0);
2572 EVT In0Ty = In0.getValueType();
2573 EVT In1Ty = In1.getValueType();
2575 // If both incoming values are integers, and the original types are the
2577 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2578 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2579 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2580 AddToWorklist(Op.getNode());
2585 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2586 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2587 // If both shuffles use the same mask, and both shuffle within a single
2588 // vector, then it is worthwhile to move the swizzle after the operation.
2589 // The type-legalizer generates this pattern when loading illegal
2590 // vector types from memory. In many cases this allows additional shuffle
2592 // There are other cases where moving the shuffle after the xor/and/or
2593 // is profitable even if shuffles don't perform a swizzle.
2594 // If both shuffles use the same mask, and both shuffles have the same first
2595 // or second operand, then it might still be profitable to move the shuffle
2596 // after the xor/and/or operation.
2597 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2598 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2599 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2601 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2602 "Inputs to shuffles are not the same type");
2604 // Check that both shuffles use the same mask. The masks are known to be of
2605 // the same length because the result vector type is the same.
2606 // Check also that shuffles have only one use to avoid introducing extra
2608 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2609 SVN0->getMask().equals(SVN1->getMask())) {
2610 SDValue ShOp = N0->getOperand(1);
2612 // Don't try to fold this node if it requires introducing a
2613 // build vector of all zeros that might be illegal at this stage.
2614 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2616 ShOp = DAG.getConstant(0, VT);
2621 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2622 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2623 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2624 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2625 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2626 N0->getOperand(0), N1->getOperand(0));
2627 AddToWorklist(NewNode.getNode());
2628 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2629 &SVN0->getMask()[0]);
2632 // Don't try to fold this node if it requires introducing a
2633 // build vector of all zeros that might be illegal at this stage.
2634 ShOp = N0->getOperand(0);
2635 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2637 ShOp = DAG.getConstant(0, VT);
2642 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2643 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2644 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2645 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2646 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2647 N0->getOperand(1), N1->getOperand(1));
2648 AddToWorklist(NewNode.getNode());
2649 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2650 &SVN0->getMask()[0]);
2658 SDValue DAGCombiner::visitAND(SDNode *N) {
2659 SDValue N0 = N->getOperand(0);
2660 SDValue N1 = N->getOperand(1);
2661 SDValue LL, LR, RL, RR, CC0, CC1;
2662 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2663 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2664 EVT VT = N1.getValueType();
2665 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2668 if (VT.isVector()) {
2669 SDValue FoldedVOp = SimplifyVBinOp(N);
2670 if (FoldedVOp.getNode()) return FoldedVOp;
2672 // fold (and x, 0) -> 0, vector edition
2673 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2674 // do not return N0, because undef node may exist in N0
2675 return DAG.getConstant(
2676 APInt::getNullValue(
2677 N0.getValueType().getScalarType().getSizeInBits()),
2679 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2680 // do not return N1, because undef node may exist in N1
2681 return DAG.getConstant(
2682 APInt::getNullValue(
2683 N1.getValueType().getScalarType().getSizeInBits()),
2686 // fold (and x, -1) -> x, vector edition
2687 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2689 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2693 // fold (and x, undef) -> 0
2694 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2695 return DAG.getConstant(0, VT);
2696 // fold (and c1, c2) -> c1&c2
2698 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2699 // canonicalize constant to RHS
2701 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2702 // fold (and x, -1) -> x
2703 if (N1C && N1C->isAllOnesValue())
2705 // if (and x, c) is known to be zero, return 0
2706 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2707 APInt::getAllOnesValue(BitWidth)))
2708 return DAG.getConstant(0, VT);
2710 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2713 // fold (and (or x, C), D) -> D if (C & D) == D
2714 if (N1C && N0.getOpcode() == ISD::OR)
2715 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2716 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2718 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2719 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2720 SDValue N0Op0 = N0.getOperand(0);
2721 APInt Mask = ~N1C->getAPIntValue();
2722 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2723 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2724 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2725 N0.getValueType(), N0Op0);
2727 // Replace uses of the AND with uses of the Zero extend node.
2730 // We actually want to replace all uses of the any_extend with the
2731 // zero_extend, to avoid duplicating things. This will later cause this
2732 // AND to be folded.
2733 CombineTo(N0.getNode(), Zext);
2734 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2737 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2738 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2739 // already be zero by virtue of the width of the base type of the load.
2741 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2743 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2744 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2745 N0.getOpcode() == ISD::LOAD) {
2746 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2747 N0 : N0.getOperand(0) );
2749 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2750 // This can be a pure constant or a vector splat, in which case we treat the
2751 // vector as a scalar and use the splat value.
2752 APInt Constant = APInt::getNullValue(1);
2753 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2754 Constant = C->getAPIntValue();
2755 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2756 APInt SplatValue, SplatUndef;
2757 unsigned SplatBitSize;
2759 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2760 SplatBitSize, HasAnyUndefs);
2762 // Undef bits can contribute to a possible optimisation if set, so
2764 SplatValue |= SplatUndef;
2766 // The splat value may be something like "0x00FFFFFF", which means 0 for
2767 // the first vector value and FF for the rest, repeating. We need a mask
2768 // that will apply equally to all members of the vector, so AND all the
2769 // lanes of the constant together.
2770 EVT VT = Vector->getValueType(0);
2771 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2773 // If the splat value has been compressed to a bitlength lower
2774 // than the size of the vector lane, we need to re-expand it to
2776 if (BitWidth > SplatBitSize)
2777 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2778 SplatBitSize < BitWidth;
2779 SplatBitSize = SplatBitSize * 2)
2780 SplatValue |= SplatValue.shl(SplatBitSize);
2782 Constant = APInt::getAllOnesValue(BitWidth);
2783 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2784 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2788 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2789 // actually legal and isn't going to get expanded, else this is a false
2791 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2792 Load->getMemoryVT());
2794 // Resize the constant to the same size as the original memory access before
2795 // extension. If it is still the AllOnesValue then this AND is completely
2798 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2801 switch (Load->getExtensionType()) {
2802 default: B = false; break;
2803 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2805 case ISD::NON_EXTLOAD: B = true; break;
2808 if (B && Constant.isAllOnesValue()) {
2809 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2810 // preserve semantics once we get rid of the AND.
2811 SDValue NewLoad(Load, 0);
2812 if (Load->getExtensionType() == ISD::EXTLOAD) {
2813 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2814 Load->getValueType(0), SDLoc(Load),
2815 Load->getChain(), Load->getBasePtr(),
2816 Load->getOffset(), Load->getMemoryVT(),
2817 Load->getMemOperand());
2818 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2819 if (Load->getNumValues() == 3) {
2820 // PRE/POST_INC loads have 3 values.
2821 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2822 NewLoad.getValue(2) };
2823 CombineTo(Load, To, 3, true);
2825 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2829 // Fold the AND away, taking care not to fold to the old load node if we
2831 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2833 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2836 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2837 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2838 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2839 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2841 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2842 LL.getValueType().isInteger()) {
2843 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2844 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2845 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2846 LR.getValueType(), LL, RL);
2847 AddToWorklist(ORNode.getNode());
2848 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2850 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2851 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2852 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2853 LR.getValueType(), LL, RL);
2854 AddToWorklist(ANDNode.getNode());
2855 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2857 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2858 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2859 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2860 LR.getValueType(), LL, RL);
2861 AddToWorklist(ORNode.getNode());
2862 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2865 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2866 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2867 Op0 == Op1 && LL.getValueType().isInteger() &&
2868 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2869 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2870 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2871 cast<ConstantSDNode>(RR)->isNullValue()))) {
2872 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2873 LL, DAG.getConstant(1, LL.getValueType()));
2874 AddToWorklist(ADDNode.getNode());
2875 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2876 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2878 // canonicalize equivalent to ll == rl
2879 if (LL == RR && LR == RL) {
2880 Op1 = ISD::getSetCCSwappedOperands(Op1);
2883 if (LL == RL && LR == RR) {
2884 bool isInteger = LL.getValueType().isInteger();
2885 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2886 if (Result != ISD::SETCC_INVALID &&
2887 (!LegalOperations ||
2888 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2889 TLI.isOperationLegal(ISD::SETCC,
2890 getSetCCResultType(N0.getSimpleValueType())))))
2891 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2896 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2897 if (N0.getOpcode() == N1.getOpcode()) {
2898 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2899 if (Tmp.getNode()) return Tmp;
2902 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2903 // fold (and (sra)) -> (and (srl)) when possible.
2904 if (!VT.isVector() &&
2905 SimplifyDemandedBits(SDValue(N, 0)))
2906 return SDValue(N, 0);
2908 // fold (zext_inreg (extload x)) -> (zextload x)
2909 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2910 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2911 EVT MemVT = LN0->getMemoryVT();
2912 // If we zero all the possible extended bits, then we can turn this into
2913 // a zextload if we are running before legalize or the operation is legal.
2914 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2915 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2916 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2917 ((!LegalOperations && !LN0->isVolatile()) ||
2918 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2919 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2920 LN0->getChain(), LN0->getBasePtr(),
2921 MemVT, LN0->getMemOperand());
2923 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2924 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2927 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2928 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2930 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2931 EVT MemVT = LN0->getMemoryVT();
2932 // If we zero all the possible extended bits, then we can turn this into
2933 // a zextload if we are running before legalize or the operation is legal.
2934 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2935 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2936 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2937 ((!LegalOperations && !LN0->isVolatile()) ||
2938 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2939 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2940 LN0->getChain(), LN0->getBasePtr(),
2941 MemVT, LN0->getMemOperand());
2943 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2948 // fold (and (load x), 255) -> (zextload x, i8)
2949 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2950 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2951 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2952 (N0.getOpcode() == ISD::ANY_EXTEND &&
2953 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2954 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2955 LoadSDNode *LN0 = HasAnyExt
2956 ? cast<LoadSDNode>(N0.getOperand(0))
2957 : cast<LoadSDNode>(N0);
2958 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2959 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2960 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2961 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2962 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2963 EVT LoadedVT = LN0->getMemoryVT();
2965 if (ExtVT == LoadedVT &&
2966 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2967 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2970 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2971 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2972 LN0->getMemOperand());
2974 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2975 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2978 // Do not change the width of a volatile load.
2979 // Do not generate loads of non-round integer types since these can
2980 // be expensive (and would be wrong if the type is not byte sized).
2981 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2982 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2983 EVT PtrType = LN0->getOperand(1).getValueType();
2985 unsigned Alignment = LN0->getAlignment();
2986 SDValue NewPtr = LN0->getBasePtr();
2988 // For big endian targets, we need to add an offset to the pointer
2989 // to load the correct bytes. For little endian systems, we merely
2990 // need to read fewer bytes from the same pointer.
2991 if (TLI.isBigEndian()) {
2992 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2993 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2994 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2995 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2996 NewPtr, DAG.getConstant(PtrOff, PtrType));
2997 Alignment = MinAlign(Alignment, PtrOff);
3000 AddToWorklist(NewPtr.getNode());
3002 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3004 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3005 LN0->getChain(), NewPtr,
3006 LN0->getPointerInfo(),
3007 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3008 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3010 CombineTo(LN0, Load, Load.getValue(1));
3011 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3017 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3018 VT.getSizeInBits() <= 64) {
3019 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3020 APInt ADDC = ADDI->getAPIntValue();
3021 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3022 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3023 // immediate for an add, but it is legal if its top c2 bits are set,
3024 // transform the ADD so the immediate doesn't need to be materialized
3026 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3027 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3028 SRLI->getZExtValue());
3029 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3031 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3033 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3034 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3035 CombineTo(N0.getNode(), NewAdd);
3036 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3044 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3045 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3046 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3047 N0.getOperand(1), false);
3048 if (BSwap.getNode())
3055 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3056 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3057 bool DemandHighBits) {
3058 if (!LegalOperations)
3061 EVT VT = N->getValueType(0);
3062 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3064 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3067 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3068 bool LookPassAnd0 = false;
3069 bool LookPassAnd1 = false;
3070 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3072 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3074 if (N0.getOpcode() == ISD::AND) {
3075 if (!N0.getNode()->hasOneUse())
3077 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3078 if (!N01C || N01C->getZExtValue() != 0xFF00)
3080 N0 = N0.getOperand(0);
3081 LookPassAnd0 = true;
3084 if (N1.getOpcode() == ISD::AND) {
3085 if (!N1.getNode()->hasOneUse())
3087 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3088 if (!N11C || N11C->getZExtValue() != 0xFF)
3090 N1 = N1.getOperand(0);
3091 LookPassAnd1 = true;
3094 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3096 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3098 if (!N0.getNode()->hasOneUse() ||
3099 !N1.getNode()->hasOneUse())
3102 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3103 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3106 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3109 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3110 SDValue N00 = N0->getOperand(0);
3111 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3112 if (!N00.getNode()->hasOneUse())
3114 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3115 if (!N001C || N001C->getZExtValue() != 0xFF)
3117 N00 = N00.getOperand(0);
3118 LookPassAnd0 = true;
3121 SDValue N10 = N1->getOperand(0);
3122 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3123 if (!N10.getNode()->hasOneUse())
3125 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3126 if (!N101C || N101C->getZExtValue() != 0xFF00)
3128 N10 = N10.getOperand(0);
3129 LookPassAnd1 = true;
3135 // Make sure everything beyond the low halfword gets set to zero since the SRL
3136 // 16 will clear the top bits.
3137 unsigned OpSizeInBits = VT.getSizeInBits();
3138 if (DemandHighBits && OpSizeInBits > 16) {
3139 // If the left-shift isn't masked out then the only way this is a bswap is
3140 // if all bits beyond the low 8 are 0. In that case the entire pattern
3141 // reduces to a left shift anyway: leave it for other parts of the combiner.
3145 // However, if the right shift isn't masked out then it might be because
3146 // it's not needed. See if we can spot that too.
3147 if (!LookPassAnd1 &&
3148 !DAG.MaskedValueIsZero(
3149 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3153 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3154 if (OpSizeInBits > 16)
3155 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3156 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3160 /// Return true if the specified node is an element that makes up a 32-bit
3161 /// packed halfword byteswap.
3162 /// ((x & 0x000000ff) << 8) |
3163 /// ((x & 0x0000ff00) >> 8) |
3164 /// ((x & 0x00ff0000) << 8) |
3165 /// ((x & 0xff000000) >> 8)
3166 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3167 if (!N.getNode()->hasOneUse())
3170 unsigned Opc = N.getOpcode();
3171 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3174 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3179 switch (N1C->getZExtValue()) {
3182 case 0xFF: Num = 0; break;
3183 case 0xFF00: Num = 1; break;
3184 case 0xFF0000: Num = 2; break;
3185 case 0xFF000000: Num = 3; break;
3188 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3189 SDValue N0 = N.getOperand(0);
3190 if (Opc == ISD::AND) {
3191 if (Num == 0 || Num == 2) {
3193 // (x >> 8) & 0xff0000
3194 if (N0.getOpcode() != ISD::SRL)
3196 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3197 if (!C || C->getZExtValue() != 8)
3200 // (x << 8) & 0xff00
3201 // (x << 8) & 0xff000000
3202 if (N0.getOpcode() != ISD::SHL)
3204 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205 if (!C || C->getZExtValue() != 8)
3208 } else if (Opc == ISD::SHL) {
3210 // (x & 0xff0000) << 8
3211 if (Num != 0 && Num != 2)
3213 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3214 if (!C || C->getZExtValue() != 8)
3216 } else { // Opc == ISD::SRL
3217 // (x & 0xff00) >> 8
3218 // (x & 0xff000000) >> 8
3219 if (Num != 1 && Num != 3)
3221 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3222 if (!C || C->getZExtValue() != 8)
3229 Parts[Num] = N0.getOperand(0).getNode();
3233 /// Match a 32-bit packed halfword bswap. That is
3234 /// ((x & 0x000000ff) << 8) |
3235 /// ((x & 0x0000ff00) >> 8) |
3236 /// ((x & 0x00ff0000) << 8) |
3237 /// ((x & 0xff000000) >> 8)
3238 /// => (rotl (bswap x), 16)
3239 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3240 if (!LegalOperations)
3243 EVT VT = N->getValueType(0);
3246 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3250 // (or (or (and), (and)), (or (and), (and)))
3251 // (or (or (or (and), (and)), (and)), (and))
3252 if (N0.getOpcode() != ISD::OR)
3254 SDValue N00 = N0.getOperand(0);
3255 SDValue N01 = N0.getOperand(1);
3256 SDNode *Parts[4] = {};
3258 if (N1.getOpcode() == ISD::OR &&
3259 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3260 // (or (or (and), (and)), (or (and), (and)))
3261 SDValue N000 = N00.getOperand(0);
3262 if (!isBSwapHWordElement(N000, Parts))
3265 SDValue N001 = N00.getOperand(1);
3266 if (!isBSwapHWordElement(N001, Parts))
3268 SDValue N010 = N01.getOperand(0);
3269 if (!isBSwapHWordElement(N010, Parts))
3271 SDValue N011 = N01.getOperand(1);
3272 if (!isBSwapHWordElement(N011, Parts))
3275 // (or (or (or (and), (and)), (and)), (and))
3276 if (!isBSwapHWordElement(N1, Parts))
3278 if (!isBSwapHWordElement(N01, Parts))
3280 if (N00.getOpcode() != ISD::OR)
3282 SDValue N000 = N00.getOperand(0);
3283 if (!isBSwapHWordElement(N000, Parts))
3285 SDValue N001 = N00.getOperand(1);
3286 if (!isBSwapHWordElement(N001, Parts))
3290 // Make sure the parts are all coming from the same node.
3291 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3294 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3295 SDValue(Parts[0],0));
3297 // Result of the bswap should be rotated by 16. If it's not legal, then
3298 // do (x << 16) | (x >> 16).
3299 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3300 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3301 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3302 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3303 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3304 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3305 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3306 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3309 SDValue DAGCombiner::visitOR(SDNode *N) {
3310 SDValue N0 = N->getOperand(0);
3311 SDValue N1 = N->getOperand(1);
3312 SDValue LL, LR, RL, RR, CC0, CC1;
3313 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3314 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3315 EVT VT = N1.getValueType();
3318 if (VT.isVector()) {
3319 SDValue FoldedVOp = SimplifyVBinOp(N);
3320 if (FoldedVOp.getNode()) return FoldedVOp;
3322 // fold (or x, 0) -> x, vector edition
3323 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3325 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3328 // fold (or x, -1) -> -1, vector edition
3329 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3330 // do not return N0, because undef node may exist in N0
3331 return DAG.getConstant(
3332 APInt::getAllOnesValue(
3333 N0.getValueType().getScalarType().getSizeInBits()),
3335 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3336 // do not return N1, because undef node may exist in N1
3337 return DAG.getConstant(
3338 APInt::getAllOnesValue(
3339 N1.getValueType().getScalarType().getSizeInBits()),
3342 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3343 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3344 // Do this only if the resulting shuffle is legal.
3345 if (isa<ShuffleVectorSDNode>(N0) &&
3346 isa<ShuffleVectorSDNode>(N1) &&
3347 // Avoid folding a node with illegal type.
3348 TLI.isTypeLegal(VT) &&
3349 N0->getOperand(1) == N1->getOperand(1) &&
3350 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3351 bool CanFold = true;
3352 unsigned NumElts = VT.getVectorNumElements();
3353 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3354 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3355 // We construct two shuffle masks:
3356 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3357 // and N1 as the second operand.
3358 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3359 // and N0 as the second operand.
3360 // We do this because OR is commutable and therefore there might be
3361 // two ways to fold this node into a shuffle.
3362 SmallVector<int,4> Mask1;
3363 SmallVector<int,4> Mask2;
3365 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3366 int M0 = SV0->getMaskElt(i);
3367 int M1 = SV1->getMaskElt(i);
3369 // Both shuffle indexes are undef. Propagate Undef.
3370 if (M0 < 0 && M1 < 0) {
3371 Mask1.push_back(M0);
3372 Mask2.push_back(M0);
3376 if (M0 < 0 || M1 < 0 ||
3377 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3378 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3383 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3384 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3388 // Fold this sequence only if the resulting shuffle is 'legal'.
3389 if (TLI.isShuffleMaskLegal(Mask1, VT))
3390 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3391 N1->getOperand(0), &Mask1[0]);
3392 if (TLI.isShuffleMaskLegal(Mask2, VT))
3393 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3394 N0->getOperand(0), &Mask2[0]);
3399 // fold (or x, undef) -> -1
3400 if (!LegalOperations &&
3401 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3402 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3403 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3405 // fold (or c1, c2) -> c1|c2
3407 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3408 // canonicalize constant to RHS
3410 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3411 // fold (or x, 0) -> x
3412 if (N1C && N1C->isNullValue())
3414 // fold (or x, -1) -> -1
3415 if (N1C && N1C->isAllOnesValue())
3417 // fold (or x, c) -> c iff (x & ~c) == 0
3418 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3421 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3422 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3423 if (BSwap.getNode())
3425 BSwap = MatchBSwapHWordLow(N, N0, N1);
3426 if (BSwap.getNode())
3430 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3433 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3434 // iff (c1 & c2) == 0.
3435 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3436 isa<ConstantSDNode>(N0.getOperand(1))) {
3437 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3438 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3439 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3442 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3443 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3444 N0.getOperand(0), N1), COR);
3447 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3448 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3449 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3450 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3452 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3453 LL.getValueType().isInteger()) {
3454 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3455 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3456 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3457 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3458 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3459 LR.getValueType(), LL, RL);
3460 AddToWorklist(ORNode.getNode());
3461 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3463 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3464 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3465 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3466 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3467 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3468 LR.getValueType(), LL, RL);
3469 AddToWorklist(ANDNode.getNode());
3470 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3473 // canonicalize equivalent to ll == rl
3474 if (LL == RR && LR == RL) {
3475 Op1 = ISD::getSetCCSwappedOperands(Op1);
3478 if (LL == RL && LR == RR) {
3479 bool isInteger = LL.getValueType().isInteger();
3480 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3481 if (Result != ISD::SETCC_INVALID &&
3482 (!LegalOperations ||
3483 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3484 TLI.isOperationLegal(ISD::SETCC,
3485 getSetCCResultType(N0.getValueType())))))
3486 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3491 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3492 if (N0.getOpcode() == N1.getOpcode()) {
3493 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3494 if (Tmp.getNode()) return Tmp;
3497 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3498 if (N0.getOpcode() == ISD::AND &&
3499 N1.getOpcode() == ISD::AND &&
3500 N0.getOperand(1).getOpcode() == ISD::Constant &&
3501 N1.getOperand(1).getOpcode() == ISD::Constant &&
3502 // Don't increase # computations.
3503 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3504 // We can only do this xform if we know that bits from X that are set in C2
3505 // but not in C1 are already zero. Likewise for Y.
3506 const APInt &LHSMask =
3507 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3508 const APInt &RHSMask =
3509 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3511 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3512 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3513 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3514 N0.getOperand(0), N1.getOperand(0));
3515 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3516 DAG.getConstant(LHSMask | RHSMask, VT));
3520 // See if this is some rotate idiom.
3521 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3522 return SDValue(Rot, 0);
3524 // Simplify the operands using demanded-bits information.
3525 if (!VT.isVector() &&
3526 SimplifyDemandedBits(SDValue(N, 0)))
3527 return SDValue(N, 0);
3532 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3533 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3534 if (Op.getOpcode() == ISD::AND) {
3535 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3536 Mask = Op.getOperand(1);
3537 Op = Op.getOperand(0);
3543 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3551 // Return true if we can prove that, whenever Neg and Pos are both in the
3552 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3553 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3555 // (or (shift1 X, Neg), (shift2 X, Pos))
3557 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3558 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3559 // to consider shift amounts with defined behavior.
3560 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3561 // If OpSize is a power of 2 then:
3563 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3564 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3566 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3567 // for the stronger condition:
3569 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3571 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3572 // we can just replace Neg with Neg' for the rest of the function.
3574 // In other cases we check for the even stronger condition:
3576 // Neg == OpSize - Pos [B]
3578 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3579 // behavior if Pos == 0 (and consequently Neg == OpSize).
3581 // We could actually use [A] whenever OpSize is a power of 2, but the
3582 // only extra cases that it would match are those uninteresting ones
3583 // where Neg and Pos are never in range at the same time. E.g. for
3584 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3585 // as well as (sub 32, Pos), but:
3587 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3589 // always invokes undefined behavior for 32-bit X.
3591 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3592 unsigned MaskLoBits = 0;
3593 if (Neg.getOpcode() == ISD::AND &&
3594 isPowerOf2_64(OpSize) &&
3595 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3596 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3597 Neg = Neg.getOperand(0);
3598 MaskLoBits = Log2_64(OpSize);
3601 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3602 if (Neg.getOpcode() != ISD::SUB)
3604 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3607 SDValue NegOp1 = Neg.getOperand(1);
3609 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3610 // Pos'. The truncation is redundant for the purpose of the equality.
3612 Pos.getOpcode() == ISD::AND &&
3613 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3614 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3615 Pos = Pos.getOperand(0);
3617 // The condition we need is now:
3619 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3621 // If NegOp1 == Pos then we need:
3623 // OpSize & Mask == NegC & Mask
3625 // (because "x & Mask" is a truncation and distributes through subtraction).
3628 Width = NegC->getAPIntValue();
3629 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3630 // Then the condition we want to prove becomes:
3632 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3634 // which, again because "x & Mask" is a truncation, becomes:
3636 // NegC & Mask == (OpSize - PosC) & Mask
3637 // OpSize & Mask == (NegC + PosC) & Mask
3638 else if (Pos.getOpcode() == ISD::ADD &&
3639 Pos.getOperand(0) == NegOp1 &&
3640 Pos.getOperand(1).getOpcode() == ISD::Constant)
3641 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3642 NegC->getAPIntValue());
3646 // Now we just need to check that OpSize & Mask == Width & Mask.
3648 // Opsize & Mask is 0 since Mask is Opsize - 1.
3649 return Width.getLoBits(MaskLoBits) == 0;
3650 return Width == OpSize;
3653 // A subroutine of MatchRotate used once we have found an OR of two opposite
3654 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3655 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3656 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3657 // Neg with outer conversions stripped away.
3658 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3659 SDValue Neg, SDValue InnerPos,
3660 SDValue InnerNeg, unsigned PosOpcode,
3661 unsigned NegOpcode, SDLoc DL) {
3662 // fold (or (shl x, (*ext y)),
3663 // (srl x, (*ext (sub 32, y)))) ->
3664 // (rotl x, y) or (rotr x, (sub 32, y))
3666 // fold (or (shl x, (*ext (sub 32, y))),
3667 // (srl x, (*ext y))) ->
3668 // (rotr x, y) or (rotl x, (sub 32, y))
3669 EVT VT = Shifted.getValueType();
3670 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3671 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3672 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3673 HasPos ? Pos : Neg).getNode();
3679 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3680 // idioms for rotate, and if the target supports rotation instructions, generate
3682 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3683 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3684 EVT VT = LHS.getValueType();
3685 if (!TLI.isTypeLegal(VT)) return nullptr;
3687 // The target must have at least one rotate flavor.
3688 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3689 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3690 if (!HasROTL && !HasROTR) return nullptr;
3692 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3693 SDValue LHSShift; // The shift.
3694 SDValue LHSMask; // AND value if any.
3695 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3696 return nullptr; // Not part of a rotate.
3698 SDValue RHSShift; // The shift.
3699 SDValue RHSMask; // AND value if any.
3700 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3701 return nullptr; // Not part of a rotate.
3703 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3704 return nullptr; // Not shifting the same value.
3706 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3707 return nullptr; // Shifts must disagree.
3709 // Canonicalize shl to left side in a shl/srl pair.
3710 if (RHSShift.getOpcode() == ISD::SHL) {
3711 std::swap(LHS, RHS);
3712 std::swap(LHSShift, RHSShift);
3713 std::swap(LHSMask , RHSMask );
3716 unsigned OpSizeInBits = VT.getSizeInBits();
3717 SDValue LHSShiftArg = LHSShift.getOperand(0);
3718 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3719 SDValue RHSShiftArg = RHSShift.getOperand(0);
3720 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3722 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3723 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3724 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3725 RHSShiftAmt.getOpcode() == ISD::Constant) {
3726 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3727 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3728 if ((LShVal + RShVal) != OpSizeInBits)
3731 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3732 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3734 // If there is an AND of either shifted operand, apply it to the result.
3735 if (LHSMask.getNode() || RHSMask.getNode()) {
3736 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3738 if (LHSMask.getNode()) {
3739 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3740 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3742 if (RHSMask.getNode()) {
3743 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3744 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3747 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3750 return Rot.getNode();
3753 // If there is a mask here, and we have a variable shift, we can't be sure
3754 // that we're masking out the right stuff.
3755 if (LHSMask.getNode() || RHSMask.getNode())
3758 // If the shift amount is sign/zext/any-extended just peel it off.
3759 SDValue LExtOp0 = LHSShiftAmt;
3760 SDValue RExtOp0 = RHSShiftAmt;
3761 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3762 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3763 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3764 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3765 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3766 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3767 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3768 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3769 LExtOp0 = LHSShiftAmt.getOperand(0);
3770 RExtOp0 = RHSShiftAmt.getOperand(0);
3773 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3774 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3778 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3779 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3786 SDValue DAGCombiner::visitXOR(SDNode *N) {
3787 SDValue N0 = N->getOperand(0);
3788 SDValue N1 = N->getOperand(1);
3789 SDValue LHS, RHS, CC;
3790 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3791 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3792 EVT VT = N0.getValueType();
3795 if (VT.isVector()) {
3796 SDValue FoldedVOp = SimplifyVBinOp(N);
3797 if (FoldedVOp.getNode()) return FoldedVOp;
3799 // fold (xor x, 0) -> x, vector edition
3800 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3802 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3806 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3807 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3808 return DAG.getConstant(0, VT);
3809 // fold (xor x, undef) -> undef
3810 if (N0.getOpcode() == ISD::UNDEF)
3812 if (N1.getOpcode() == ISD::UNDEF)
3814 // fold (xor c1, c2) -> c1^c2
3816 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3817 // canonicalize constant to RHS
3819 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3820 // fold (xor x, 0) -> x
3821 if (N1C && N1C->isNullValue())
3824 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3828 // fold !(x cc y) -> (x !cc y)
3829 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3830 bool isInt = LHS.getValueType().isInteger();
3831 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3834 if (!LegalOperations ||
3835 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3836 switch (N0.getOpcode()) {
3838 llvm_unreachable("Unhandled SetCC Equivalent!");
3840 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3841 case ISD::SELECT_CC:
3842 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3843 N0.getOperand(3), NotCC);
3848 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3849 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3850 N0.getNode()->hasOneUse() &&
3851 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3852 SDValue V = N0.getOperand(0);
3853 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3854 DAG.getConstant(1, V.getValueType()));
3855 AddToWorklist(V.getNode());
3856 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3859 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3860 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3861 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3862 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3863 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3864 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3865 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3866 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3867 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3868 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3871 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3872 if (N1C && N1C->isAllOnesValue() &&
3873 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3874 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3875 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3876 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3877 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3878 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3879 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3880 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3883 // fold (xor (and x, y), y) -> (and (not x), y)
3884 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3885 N0->getOperand(1) == N1) {
3886 SDValue X = N0->getOperand(0);
3887 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3888 AddToWorklist(NotX.getNode());
3889 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3891 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3892 if (N1C && N0.getOpcode() == ISD::XOR) {
3893 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3894 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3896 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3897 DAG.getConstant(N1C->getAPIntValue() ^
3898 N00C->getAPIntValue(), VT));
3900 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3901 DAG.getConstant(N1C->getAPIntValue() ^
3902 N01C->getAPIntValue(), VT));
3904 // fold (xor x, x) -> 0
3906 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3908 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3909 if (N0.getOpcode() == N1.getOpcode()) {
3910 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3911 if (Tmp.getNode()) return Tmp;
3914 // Simplify the expression using non-local knowledge.
3915 if (!VT.isVector() &&
3916 SimplifyDemandedBits(SDValue(N, 0)))
3917 return SDValue(N, 0);
3922 /// Handle transforms common to the three shifts, when the shift amount is a
3924 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3925 // We can't and shouldn't fold opaque constants.
3926 if (Amt->isOpaque())
3929 SDNode *LHS = N->getOperand(0).getNode();
3930 if (!LHS->hasOneUse()) return SDValue();
3932 // We want to pull some binops through shifts, so that we have (and (shift))
3933 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3934 // thing happens with address calculations, so it's important to canonicalize
3936 bool HighBitSet = false; // Can we transform this if the high bit is set?
3938 switch (LHS->getOpcode()) {
3939 default: return SDValue();
3942 HighBitSet = false; // We can only transform sra if the high bit is clear.
3945 HighBitSet = true; // We can only transform sra if the high bit is set.
3948 if (N->getOpcode() != ISD::SHL)
3949 return SDValue(); // only shl(add) not sr[al](add).
3950 HighBitSet = false; // We can only transform sra if the high bit is clear.
3954 // We require the RHS of the binop to be a constant and not opaque as well.
3955 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3956 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3958 // FIXME: disable this unless the input to the binop is a shift by a constant.
3959 // If it is not a shift, it pessimizes some common cases like:
3961 // void foo(int *X, int i) { X[i & 1235] = 1; }
3962 // int bar(int *X, int i) { return X[i & 255]; }
3963 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3964 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3965 BinOpLHSVal->getOpcode() != ISD::SRA &&
3966 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3967 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3970 EVT VT = N->getValueType(0);
3972 // If this is a signed shift right, and the high bit is modified by the
3973 // logical operation, do not perform the transformation. The highBitSet
3974 // boolean indicates the value of the high bit of the constant which would
3975 // cause it to be modified for this operation.
3976 if (N->getOpcode() == ISD::SRA) {
3977 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3978 if (BinOpRHSSignSet != HighBitSet)
3982 if (!TLI.isDesirableToCommuteWithShift(LHS))
3985 // Fold the constants, shifting the binop RHS by the shift amount.
3986 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3988 LHS->getOperand(1), N->getOperand(1));
3989 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3991 // Create the new shift.
3992 SDValue NewShift = DAG.getNode(N->getOpcode(),
3993 SDLoc(LHS->getOperand(0)),
3994 VT, LHS->getOperand(0), N->getOperand(1));
3996 // Create the new binop.
3997 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4000 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4001 assert(N->getOpcode() == ISD::TRUNCATE);
4002 assert(N->getOperand(0).getOpcode() == ISD::AND);
4004 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4005 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4006 SDValue N01 = N->getOperand(0).getOperand(1);
4008 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4009 EVT TruncVT = N->getValueType(0);
4010 SDValue N00 = N->getOperand(0).getOperand(0);
4011 APInt TruncC = N01C->getAPIntValue();
4012 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4014 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4015 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4016 DAG.getConstant(TruncC, TruncVT));
4023 SDValue DAGCombiner::visitRotate(SDNode *N) {
4024 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4025 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4026 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4027 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4028 if (NewOp1.getNode())
4029 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4030 N->getOperand(0), NewOp1);
4035 SDValue DAGCombiner::visitSHL(SDNode *N) {
4036 SDValue N0 = N->getOperand(0);
4037 SDValue N1 = N->getOperand(1);
4038 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4039 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4040 EVT VT = N0.getValueType();
4041 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4044 if (VT.isVector()) {
4045 SDValue FoldedVOp = SimplifyVBinOp(N);
4046 if (FoldedVOp.getNode()) return FoldedVOp;
4048 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4049 // If setcc produces all-one true value then:
4050 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4051 if (N1CV && N1CV->isConstant()) {
4052 if (N0.getOpcode() == ISD::AND) {
4053 SDValue N00 = N0->getOperand(0);
4054 SDValue N01 = N0->getOperand(1);
4055 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4057 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4058 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4059 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4060 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4062 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4065 N1C = isConstOrConstSplat(N1);
4070 // fold (shl c1, c2) -> c1<<c2
4072 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4073 // fold (shl 0, x) -> 0
4074 if (N0C && N0C->isNullValue())
4076 // fold (shl x, c >= size(x)) -> undef
4077 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4078 return DAG.getUNDEF(VT);
4079 // fold (shl x, 0) -> x
4080 if (N1C && N1C->isNullValue())
4082 // fold (shl undef, x) -> 0
4083 if (N0.getOpcode() == ISD::UNDEF)
4084 return DAG.getConstant(0, VT);
4085 // if (shl x, c) is known to be zero, return 0
4086 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4087 APInt::getAllOnesValue(OpSizeInBits)))
4088 return DAG.getConstant(0, VT);
4089 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4090 if (N1.getOpcode() == ISD::TRUNCATE &&
4091 N1.getOperand(0).getOpcode() == ISD::AND) {
4092 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4093 if (NewOp1.getNode())
4094 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4097 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4098 return SDValue(N, 0);
4100 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4101 if (N1C && N0.getOpcode() == ISD::SHL) {
4102 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4103 uint64_t c1 = N0C1->getZExtValue();
4104 uint64_t c2 = N1C->getZExtValue();
4105 if (c1 + c2 >= OpSizeInBits)
4106 return DAG.getConstant(0, VT);
4107 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4108 DAG.getConstant(c1 + c2, N1.getValueType()));
4112 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4113 // For this to be valid, the second form must not preserve any of the bits
4114 // that are shifted out by the inner shift in the first form. This means
4115 // the outer shift size must be >= the number of bits added by the ext.
4116 // As a corollary, we don't care what kind of ext it is.
4117 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4118 N0.getOpcode() == ISD::ANY_EXTEND ||
4119 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4120 N0.getOperand(0).getOpcode() == ISD::SHL) {
4121 SDValue N0Op0 = N0.getOperand(0);
4122 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4123 uint64_t c1 = N0Op0C1->getZExtValue();
4124 uint64_t c2 = N1C->getZExtValue();
4125 EVT InnerShiftVT = N0Op0.getValueType();
4126 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4127 if (c2 >= OpSizeInBits - InnerShiftSize) {
4128 if (c1 + c2 >= OpSizeInBits)
4129 return DAG.getConstant(0, VT);
4130 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4131 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4132 N0Op0->getOperand(0)),
4133 DAG.getConstant(c1 + c2, N1.getValueType()));
4138 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4139 // Only fold this if the inner zext has no other uses to avoid increasing
4140 // the total number of instructions.
4141 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4142 N0.getOperand(0).getOpcode() == ISD::SRL) {
4143 SDValue N0Op0 = N0.getOperand(0);
4144 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4145 uint64_t c1 = N0Op0C1->getZExtValue();
4146 if (c1 < VT.getScalarSizeInBits()) {
4147 uint64_t c2 = N1C->getZExtValue();
4149 SDValue NewOp0 = N0.getOperand(0);
4150 EVT CountVT = NewOp0.getOperand(1).getValueType();
4151 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4152 NewOp0, DAG.getConstant(c2, CountVT));
4153 AddToWorklist(NewSHL.getNode());
4154 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4160 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4161 // (and (srl x, (sub c1, c2), MASK)
4162 // Only fold this if the inner shift has no other uses -- if it does, folding
4163 // this will increase the total number of instructions.
4164 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4165 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4166 uint64_t c1 = N0C1->getZExtValue();
4167 if (c1 < OpSizeInBits) {
4168 uint64_t c2 = N1C->getZExtValue();
4169 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4172 Mask = Mask.shl(c2 - c1);
4173 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4174 DAG.getConstant(c2 - c1, N1.getValueType()));
4176 Mask = Mask.lshr(c1 - c2);
4177 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4178 DAG.getConstant(c1 - c2, N1.getValueType()));
4180 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4181 DAG.getConstant(Mask, VT));
4185 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4186 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4187 unsigned BitSize = VT.getScalarSizeInBits();
4188 SDValue HiBitsMask =
4189 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4190 BitSize - N1C->getZExtValue()), VT);
4191 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4195 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4196 // Variant of version done on multiply, except mul by a power of 2 is turned
4199 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4200 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4201 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4202 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4203 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4204 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4208 SDValue NewSHL = visitShiftByConstant(N, N1C);
4209 if (NewSHL.getNode())
4216 SDValue DAGCombiner::visitSRA(SDNode *N) {
4217 SDValue N0 = N->getOperand(0);
4218 SDValue N1 = N->getOperand(1);
4219 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4220 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4221 EVT VT = N0.getValueType();
4222 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4225 if (VT.isVector()) {
4226 SDValue FoldedVOp = SimplifyVBinOp(N);
4227 if (FoldedVOp.getNode()) return FoldedVOp;
4229 N1C = isConstOrConstSplat(N1);
4232 // fold (sra c1, c2) -> (sra c1, c2)
4234 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4235 // fold (sra 0, x) -> 0
4236 if (N0C && N0C->isNullValue())
4238 // fold (sra -1, x) -> -1
4239 if (N0C && N0C->isAllOnesValue())
4241 // fold (sra x, (setge c, size(x))) -> undef
4242 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4243 return DAG.getUNDEF(VT);
4244 // fold (sra x, 0) -> x
4245 if (N1C && N1C->isNullValue())
4247 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4249 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4250 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4251 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4253 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4254 ExtVT, VT.getVectorNumElements());
4255 if ((!LegalOperations ||
4256 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4257 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4258 N0.getOperand(0), DAG.getValueType(ExtVT));
4261 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4262 if (N1C && N0.getOpcode() == ISD::SRA) {
4263 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4264 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4265 if (Sum >= OpSizeInBits)
4266 Sum = OpSizeInBits - 1;
4267 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4268 DAG.getConstant(Sum, N1.getValueType()));
4272 // fold (sra (shl X, m), (sub result_size, n))
4273 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4274 // result_size - n != m.
4275 // If truncate is free for the target sext(shl) is likely to result in better
4277 if (N0.getOpcode() == ISD::SHL && N1C) {
4278 // Get the two constanst of the shifts, CN0 = m, CN = n.
4279 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4281 LLVMContext &Ctx = *DAG.getContext();
4282 // Determine what the truncate's result bitsize and type would be.
4283 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4286 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4288 // Determine the residual right-shift amount.
4289 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4291 // If the shift is not a no-op (in which case this should be just a sign
4292 // extend already), the truncated to type is legal, sign_extend is legal
4293 // on that type, and the truncate to that type is both legal and free,
4294 // perform the transform.
4295 if ((ShiftAmt > 0) &&
4296 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4297 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4298 TLI.isTruncateFree(VT, TruncVT)) {
4300 SDValue Amt = DAG.getConstant(ShiftAmt,
4301 getShiftAmountTy(N0.getOperand(0).getValueType()));
4302 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4303 N0.getOperand(0), Amt);
4304 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4306 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4307 N->getValueType(0), Trunc);
4312 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4313 if (N1.getOpcode() == ISD::TRUNCATE &&
4314 N1.getOperand(0).getOpcode() == ISD::AND) {
4315 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4316 if (NewOp1.getNode())
4317 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4320 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4321 // if c1 is equal to the number of bits the trunc removes
4322 if (N0.getOpcode() == ISD::TRUNCATE &&
4323 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4324 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4325 N0.getOperand(0).hasOneUse() &&
4326 N0.getOperand(0).getOperand(1).hasOneUse() &&
4328 SDValue N0Op0 = N0.getOperand(0);
4329 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4330 unsigned LargeShiftVal = LargeShift->getZExtValue();
4331 EVT LargeVT = N0Op0.getValueType();
4333 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4335 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4336 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4337 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4338 N0Op0.getOperand(0), Amt);
4339 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4344 // Simplify, based on bits shifted out of the LHS.
4345 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4346 return SDValue(N, 0);
4349 // If the sign bit is known to be zero, switch this to a SRL.
4350 if (DAG.SignBitIsZero(N0))
4351 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4354 SDValue NewSRA = visitShiftByConstant(N, N1C);
4355 if (NewSRA.getNode())
4362 SDValue DAGCombiner::visitSRL(SDNode *N) {
4363 SDValue N0 = N->getOperand(0);
4364 SDValue N1 = N->getOperand(1);
4365 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4366 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4367 EVT VT = N0.getValueType();
4368 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4371 if (VT.isVector()) {
4372 SDValue FoldedVOp = SimplifyVBinOp(N);
4373 if (FoldedVOp.getNode()) return FoldedVOp;
4375 N1C = isConstOrConstSplat(N1);
4378 // fold (srl c1, c2) -> c1 >>u c2
4380 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4381 // fold (srl 0, x) -> 0
4382 if (N0C && N0C->isNullValue())
4384 // fold (srl x, c >= size(x)) -> undef
4385 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4386 return DAG.getUNDEF(VT);
4387 // fold (srl x, 0) -> x
4388 if (N1C && N1C->isNullValue())
4390 // if (srl x, c) is known to be zero, return 0
4391 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4392 APInt::getAllOnesValue(OpSizeInBits)))
4393 return DAG.getConstant(0, VT);
4395 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4396 if (N1C && N0.getOpcode() == ISD::SRL) {
4397 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4398 uint64_t c1 = N01C->getZExtValue();
4399 uint64_t c2 = N1C->getZExtValue();
4400 if (c1 + c2 >= OpSizeInBits)
4401 return DAG.getConstant(0, VT);
4402 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4403 DAG.getConstant(c1 + c2, N1.getValueType()));
4407 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4408 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4409 N0.getOperand(0).getOpcode() == ISD::SRL &&
4410 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4412 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4413 uint64_t c2 = N1C->getZExtValue();
4414 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4415 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4416 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4417 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4418 if (c1 + OpSizeInBits == InnerShiftSize) {
4419 if (c1 + c2 >= InnerShiftSize)
4420 return DAG.getConstant(0, VT);
4421 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4422 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4423 N0.getOperand(0)->getOperand(0),
4424 DAG.getConstant(c1 + c2, ShiftCountVT)));
4428 // fold (srl (shl x, c), c) -> (and x, cst2)
4429 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4430 unsigned BitSize = N0.getScalarValueSizeInBits();
4431 if (BitSize <= 64) {
4432 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4433 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4434 DAG.getConstant(~0ULL >> ShAmt, VT));
4438 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4439 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4440 // Shifting in all undef bits?
4441 EVT SmallVT = N0.getOperand(0).getValueType();
4442 unsigned BitSize = SmallVT.getScalarSizeInBits();
4443 if (N1C->getZExtValue() >= BitSize)
4444 return DAG.getUNDEF(VT);
4446 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4447 uint64_t ShiftAmt = N1C->getZExtValue();
4448 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4450 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4451 AddToWorklist(SmallShift.getNode());
4452 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4453 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4454 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4455 DAG.getConstant(Mask, VT));
4459 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4460 // bit, which is unmodified by sra.
4461 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4462 if (N0.getOpcode() == ISD::SRA)
4463 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4466 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4467 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4468 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4469 APInt KnownZero, KnownOne;
4470 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4472 // If any of the input bits are KnownOne, then the input couldn't be all
4473 // zeros, thus the result of the srl will always be zero.
4474 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4476 // If all of the bits input the to ctlz node are known to be zero, then
4477 // the result of the ctlz is "32" and the result of the shift is one.
4478 APInt UnknownBits = ~KnownZero;
4479 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4481 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4482 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4483 // Okay, we know that only that the single bit specified by UnknownBits
4484 // could be set on input to the CTLZ node. If this bit is set, the SRL
4485 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4486 // to an SRL/XOR pair, which is likely to simplify more.
4487 unsigned ShAmt = UnknownBits.countTrailingZeros();
4488 SDValue Op = N0.getOperand(0);
4491 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4492 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4493 AddToWorklist(Op.getNode());
4496 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4497 Op, DAG.getConstant(1, VT));
4501 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4502 if (N1.getOpcode() == ISD::TRUNCATE &&
4503 N1.getOperand(0).getOpcode() == ISD::AND) {
4504 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4505 if (NewOp1.getNode())
4506 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4509 // fold operands of srl based on knowledge that the low bits are not
4511 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4512 return SDValue(N, 0);
4515 SDValue NewSRL = visitShiftByConstant(N, N1C);
4516 if (NewSRL.getNode())
4520 // Attempt to convert a srl of a load into a narrower zero-extending load.
4521 SDValue NarrowLoad = ReduceLoadWidth(N);
4522 if (NarrowLoad.getNode())
4525 // Here is a common situation. We want to optimize:
4528 // %b = and i32 %a, 2
4529 // %c = srl i32 %b, 1
4530 // brcond i32 %c ...
4536 // %c = setcc eq %b, 0
4539 // However when after the source operand of SRL is optimized into AND, the SRL
4540 // itself may not be optimized further. Look for it and add the BRCOND into
4542 if (N->hasOneUse()) {
4543 SDNode *Use = *N->use_begin();
4544 if (Use->getOpcode() == ISD::BRCOND)
4546 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4547 // Also look pass the truncate.
4548 Use = *Use->use_begin();
4549 if (Use->getOpcode() == ISD::BRCOND)
4557 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4558 SDValue N0 = N->getOperand(0);
4559 EVT VT = N->getValueType(0);
4561 // fold (ctlz c1) -> c2
4562 if (isa<ConstantSDNode>(N0))
4563 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4567 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4568 SDValue N0 = N->getOperand(0);
4569 EVT VT = N->getValueType(0);
4571 // fold (ctlz_zero_undef c1) -> c2
4572 if (isa<ConstantSDNode>(N0))
4573 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4577 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4578 SDValue N0 = N->getOperand(0);
4579 EVT VT = N->getValueType(0);
4581 // fold (cttz c1) -> c2
4582 if (isa<ConstantSDNode>(N0))
4583 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4587 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4588 SDValue N0 = N->getOperand(0);
4589 EVT VT = N->getValueType(0);
4591 // fold (cttz_zero_undef c1) -> c2
4592 if (isa<ConstantSDNode>(N0))
4593 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4597 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4598 SDValue N0 = N->getOperand(0);
4599 EVT VT = N->getValueType(0);
4601 // fold (ctpop c1) -> c2
4602 if (isa<ConstantSDNode>(N0))
4603 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4607 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4608 SDValue N0 = N->getOperand(0);
4609 SDValue N1 = N->getOperand(1);
4610 SDValue N2 = N->getOperand(2);
4611 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4612 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4613 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4614 EVT VT = N->getValueType(0);
4615 EVT VT0 = N0.getValueType();
4617 // fold (select C, X, X) -> X
4620 // fold (select true, X, Y) -> X
4621 if (N0C && !N0C->isNullValue())
4623 // fold (select false, X, Y) -> Y
4624 if (N0C && N0C->isNullValue())
4626 // fold (select C, 1, X) -> (or C, X)
4627 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4628 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4629 // fold (select C, 0, 1) -> (xor C, 1)
4630 // We can't do this reliably if integer based booleans have different contents
4631 // to floating point based booleans. This is because we can't tell whether we
4632 // have an integer-based boolean or a floating-point-based boolean unless we
4633 // can find the SETCC that produced it and inspect its operands. This is
4634 // fairly easy if C is the SETCC node, but it can potentially be
4635 // undiscoverable (or not reasonably discoverable). For example, it could be
4636 // in another basic block or it could require searching a complicated
4638 if (VT.isInteger() &&
4639 (VT0 == MVT::i1 || (VT0.isInteger() &&
4640 TLI.getBooleanContents(false, false) ==
4641 TLI.getBooleanContents(false, true) &&
4642 TLI.getBooleanContents(false, false) ==
4643 TargetLowering::ZeroOrOneBooleanContent)) &&
4644 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4647 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4648 N0, DAG.getConstant(1, VT0));
4649 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4650 N0, DAG.getConstant(1, VT0));
4651 AddToWorklist(XORNode.getNode());
4653 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4654 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4656 // fold (select C, 0, X) -> (and (not C), X)
4657 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4658 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4659 AddToWorklist(NOTNode.getNode());
4660 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4662 // fold (select C, X, 1) -> (or (not C), X)
4663 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4664 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4665 AddToWorklist(NOTNode.getNode());
4666 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4668 // fold (select C, X, 0) -> (and C, X)
4669 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4670 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4671 // fold (select X, X, Y) -> (or X, Y)
4672 // fold (select X, 1, Y) -> (or X, Y)
4673 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4674 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4675 // fold (select X, Y, X) -> (and X, Y)
4676 // fold (select X, Y, 0) -> (and X, Y)
4677 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4678 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4680 // If we can fold this based on the true/false value, do so.
4681 if (SimplifySelectOps(N, N1, N2))
4682 return SDValue(N, 0); // Don't revisit N.
4684 // fold selects based on a setcc into other things, such as min/max/abs
4685 if (N0.getOpcode() == ISD::SETCC) {
4686 if ((!LegalOperations &&
4687 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4688 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4689 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4690 N0.getOperand(0), N0.getOperand(1),
4691 N1, N2, N0.getOperand(2));
4692 return SimplifySelect(SDLoc(N), N0, N1, N2);
4699 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4702 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4704 // Split the inputs.
4705 SDValue Lo, Hi, LL, LH, RL, RH;
4706 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4707 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4709 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4710 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4712 return std::make_pair(Lo, Hi);
4715 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4716 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4717 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4719 SDValue Cond = N->getOperand(0);
4720 SDValue LHS = N->getOperand(1);
4721 SDValue RHS = N->getOperand(2);
4722 EVT VT = N->getValueType(0);
4723 int NumElems = VT.getVectorNumElements();
4724 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4725 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4726 Cond.getOpcode() == ISD::BUILD_VECTOR);
4728 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4729 // binary ones here.
4730 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4733 // We're sure we have an even number of elements due to the
4734 // concat_vectors we have as arguments to vselect.
4735 // Skip BV elements until we find one that's not an UNDEF
4736 // After we find an UNDEF element, keep looping until we get to half the
4737 // length of the BV and see if all the non-undef nodes are the same.
4738 ConstantSDNode *BottomHalf = nullptr;
4739 for (int i = 0; i < NumElems / 2; ++i) {
4740 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4743 if (BottomHalf == nullptr)
4744 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4745 else if (Cond->getOperand(i).getNode() != BottomHalf)
4749 // Do the same for the second half of the BuildVector
4750 ConstantSDNode *TopHalf = nullptr;
4751 for (int i = NumElems / 2; i < NumElems; ++i) {
4752 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4755 if (TopHalf == nullptr)
4756 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4757 else if (Cond->getOperand(i).getNode() != TopHalf)
4761 assert(TopHalf && BottomHalf &&
4762 "One half of the selector was all UNDEFs and the other was all the "
4763 "same value. This should have been addressed before this function.");
4765 ISD::CONCAT_VECTORS, dl, VT,
4766 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4767 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4770 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4771 SDValue N0 = N->getOperand(0);
4772 SDValue N1 = N->getOperand(1);
4773 SDValue N2 = N->getOperand(2);
4776 // Canonicalize integer abs.
4777 // vselect (setg[te] X, 0), X, -X ->
4778 // vselect (setgt X, -1), X, -X ->
4779 // vselect (setl[te] X, 0), -X, X ->
4780 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4781 if (N0.getOpcode() == ISD::SETCC) {
4782 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4783 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4785 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4787 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4788 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4789 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4790 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4791 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4792 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4793 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4796 EVT VT = LHS.getValueType();
4797 SDValue Shift = DAG.getNode(
4798 ISD::SRA, DL, VT, LHS,
4799 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4800 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4801 AddToWorklist(Shift.getNode());
4802 AddToWorklist(Add.getNode());
4803 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4807 // If the VSELECT result requires splitting and the mask is provided by a
4808 // SETCC, then split both nodes and its operands before legalization. This
4809 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4810 // and enables future optimizations (e.g. min/max pattern matching on X86).
4811 if (N0.getOpcode() == ISD::SETCC) {
4812 EVT VT = N->getValueType(0);
4814 // Check if any splitting is required.
4815 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4816 TargetLowering::TypeSplitVector)
4819 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4820 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4821 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4822 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4824 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4825 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4827 // Add the new VSELECT nodes to the work list in case they need to be split
4829 AddToWorklist(Lo.getNode());
4830 AddToWorklist(Hi.getNode());
4832 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4835 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4836 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4838 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4839 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4842 // The ConvertSelectToConcatVector function is assuming both the above
4843 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4845 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4846 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4847 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4848 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4856 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4857 SDValue N0 = N->getOperand(0);
4858 SDValue N1 = N->getOperand(1);
4859 SDValue N2 = N->getOperand(2);
4860 SDValue N3 = N->getOperand(3);
4861 SDValue N4 = N->getOperand(4);
4862 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4864 // fold select_cc lhs, rhs, x, x, cc -> x
4868 // Determine if the condition we're dealing with is constant
4869 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4870 N0, N1, CC, SDLoc(N), false);
4871 if (SCC.getNode()) {
4872 AddToWorklist(SCC.getNode());
4874 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4875 if (!SCCC->isNullValue())
4876 return N2; // cond always true -> true val
4878 return N3; // cond always false -> false val
4881 // Fold to a simpler select_cc
4882 if (SCC.getOpcode() == ISD::SETCC)
4883 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4884 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4888 // If we can fold this based on the true/false value, do so.
4889 if (SimplifySelectOps(N, N2, N3))
4890 return SDValue(N, 0); // Don't revisit N.
4892 // fold select_cc into other things, such as min/max/abs
4893 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4896 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4897 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4898 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4902 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4903 // dag node into a ConstantSDNode or a build_vector of constants.
4904 // This function is called by the DAGCombiner when visiting sext/zext/aext
4905 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4906 // Vector extends are not folded if operations are legal; this is to
4907 // avoid introducing illegal build_vector dag nodes.
4908 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4909 SelectionDAG &DAG, bool LegalTypes,
4910 bool LegalOperations) {
4911 unsigned Opcode = N->getOpcode();
4912 SDValue N0 = N->getOperand(0);
4913 EVT VT = N->getValueType(0);
4915 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4916 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4918 // fold (sext c1) -> c1
4919 // fold (zext c1) -> c1
4920 // fold (aext c1) -> c1
4921 if (isa<ConstantSDNode>(N0))
4922 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4924 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4925 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4926 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4927 EVT SVT = VT.getScalarType();
4928 if (!(VT.isVector() &&
4929 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4930 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4933 // We can fold this node into a build_vector.
4934 unsigned VTBits = SVT.getSizeInBits();
4935 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4936 unsigned ShAmt = VTBits - EVTBits;
4937 SmallVector<SDValue, 8> Elts;
4938 unsigned NumElts = N0->getNumOperands();
4941 for (unsigned i=0; i != NumElts; ++i) {
4942 SDValue Op = N0->getOperand(i);
4943 if (Op->getOpcode() == ISD::UNDEF) {
4944 Elts.push_back(DAG.getUNDEF(SVT));
4948 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4949 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4950 if (Opcode == ISD::SIGN_EXTEND)
4951 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4954 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4958 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4961 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4962 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4963 // transformation. Returns true if extension are possible and the above
4964 // mentioned transformation is profitable.
4965 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4967 SmallVectorImpl<SDNode *> &ExtendNodes,
4968 const TargetLowering &TLI) {
4969 bool HasCopyToRegUses = false;
4970 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4971 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4972 UE = N0.getNode()->use_end();
4977 if (UI.getUse().getResNo() != N0.getResNo())
4979 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4980 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4981 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4982 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4983 // Sign bits will be lost after a zext.
4986 for (unsigned i = 0; i != 2; ++i) {
4987 SDValue UseOp = User->getOperand(i);
4990 if (!isa<ConstantSDNode>(UseOp))
4995 ExtendNodes.push_back(User);
4998 // If truncates aren't free and there are users we can't
4999 // extend, it isn't worthwhile.
5002 // Remember if this value is live-out.
5003 if (User->getOpcode() == ISD::CopyToReg)
5004 HasCopyToRegUses = true;
5007 if (HasCopyToRegUses) {
5008 bool BothLiveOut = false;
5009 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5011 SDUse &Use = UI.getUse();
5012 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5018 // Both unextended and extended values are live out. There had better be
5019 // a good reason for the transformation.
5020 return ExtendNodes.size();
5025 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5026 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5027 ISD::NodeType ExtType) {
5028 // Extend SetCC uses if necessary.
5029 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5030 SDNode *SetCC = SetCCs[i];
5031 SmallVector<SDValue, 4> Ops;
5033 for (unsigned j = 0; j != 2; ++j) {
5034 SDValue SOp = SetCC->getOperand(j);
5036 Ops.push_back(ExtLoad);
5038 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5041 Ops.push_back(SetCC->getOperand(2));
5042 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5046 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5047 SDValue N0 = N->getOperand(0);
5048 EVT VT = N->getValueType(0);
5050 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5052 return SDValue(Res, 0);
5054 // fold (sext (sext x)) -> (sext x)
5055 // fold (sext (aext x)) -> (sext x)
5056 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5057 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5060 if (N0.getOpcode() == ISD::TRUNCATE) {
5061 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5062 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5063 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5064 if (NarrowLoad.getNode()) {
5065 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5066 if (NarrowLoad.getNode() != N0.getNode()) {
5067 CombineTo(N0.getNode(), NarrowLoad);
5068 // CombineTo deleted the truncate, if needed, but not what's under it.
5071 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5074 // See if the value being truncated is already sign extended. If so, just
5075 // eliminate the trunc/sext pair.
5076 SDValue Op = N0.getOperand(0);
5077 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5078 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5079 unsigned DestBits = VT.getScalarType().getSizeInBits();
5080 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5082 if (OpBits == DestBits) {
5083 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5084 // bits, it is already ready.
5085 if (NumSignBits > DestBits-MidBits)
5087 } else if (OpBits < DestBits) {
5088 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5089 // bits, just sext from i32.
5090 if (NumSignBits > OpBits-MidBits)
5091 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5093 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5094 // bits, just truncate to i32.
5095 if (NumSignBits > OpBits-MidBits)
5096 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5099 // fold (sext (truncate x)) -> (sextinreg x).
5100 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5101 N0.getValueType())) {
5102 if (OpBits < DestBits)
5103 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5104 else if (OpBits > DestBits)
5105 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5106 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5107 DAG.getValueType(N0.getValueType()));
5111 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5112 // None of the supported targets knows how to perform load and sign extend
5113 // on vectors in one instruction. We only perform this transformation on
5115 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5116 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5117 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5118 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5119 bool DoXform = true;
5120 SmallVector<SDNode*, 4> SetCCs;
5121 if (!N0.hasOneUse())
5122 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5124 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5125 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5127 LN0->getBasePtr(), N0.getValueType(),
5128 LN0->getMemOperand());
5129 CombineTo(N, ExtLoad);
5130 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5131 N0.getValueType(), ExtLoad);
5132 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5133 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5135 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5139 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5140 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5141 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5142 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5143 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5144 EVT MemVT = LN0->getMemoryVT();
5145 if ((!LegalOperations && !LN0->isVolatile()) ||
5146 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5147 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5149 LN0->getBasePtr(), MemVT,
5150 LN0->getMemOperand());
5151 CombineTo(N, ExtLoad);
5152 CombineTo(N0.getNode(),
5153 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5154 N0.getValueType(), ExtLoad),
5155 ExtLoad.getValue(1));
5156 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5160 // fold (sext (and/or/xor (load x), cst)) ->
5161 // (and/or/xor (sextload x), (sext cst))
5162 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5163 N0.getOpcode() == ISD::XOR) &&
5164 isa<LoadSDNode>(N0.getOperand(0)) &&
5165 N0.getOperand(1).getOpcode() == ISD::Constant &&
5166 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5167 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5168 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5169 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5170 bool DoXform = true;
5171 SmallVector<SDNode*, 4> SetCCs;
5172 if (!N0.hasOneUse())
5173 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5176 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5177 LN0->getChain(), LN0->getBasePtr(),
5179 LN0->getMemOperand());
5180 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5181 Mask = Mask.sext(VT.getSizeInBits());
5182 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5183 ExtLoad, DAG.getConstant(Mask, VT));
5184 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5185 SDLoc(N0.getOperand(0)),
5186 N0.getOperand(0).getValueType(), ExtLoad);
5188 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5189 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5191 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5196 if (N0.getOpcode() == ISD::SETCC) {
5197 EVT N0VT = N0.getOperand(0).getValueType();
5198 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5199 // Only do this before legalize for now.
5200 if (VT.isVector() && !LegalOperations &&
5201 TLI.getBooleanContents(N0VT) ==
5202 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5203 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5204 // of the same size as the compared operands. Only optimize sext(setcc())
5205 // if this is the case.
5206 EVT SVT = getSetCCResultType(N0VT);
5208 // We know that the # elements of the results is the same as the
5209 // # elements of the compare (and the # elements of the compare result
5210 // for that matter). Check to see that they are the same size. If so,
5211 // we know that the element size of the sext'd result matches the
5212 // element size of the compare operands.
5213 if (VT.getSizeInBits() == SVT.getSizeInBits())
5214 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5216 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5218 // If the desired elements are smaller or larger than the source
5219 // elements we can use a matching integer vector type and then
5220 // truncate/sign extend
5221 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5222 if (SVT == MatchingVectorType) {
5223 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5224 N0.getOperand(0), N0.getOperand(1),
5225 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5226 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5230 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5231 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5233 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5235 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5236 NegOne, DAG.getConstant(0, VT),
5237 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5238 if (SCC.getNode()) return SCC;
5240 if (!VT.isVector()) {
5241 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5242 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5244 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5245 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5246 N0.getOperand(0), N0.getOperand(1), CC);
5247 return DAG.getSelect(DL, VT, SetCC,
5248 NegOne, DAG.getConstant(0, VT));
5253 // fold (sext x) -> (zext x) if the sign bit is known zero.
5254 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5255 DAG.SignBitIsZero(N0))
5256 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5261 // isTruncateOf - If N is a truncate of some other value, return true, record
5262 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5263 // This function computes KnownZero to avoid a duplicated call to
5264 // computeKnownBits in the caller.
5265 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5268 if (N->getOpcode() == ISD::TRUNCATE) {
5269 Op = N->getOperand(0);
5270 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5274 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5275 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5278 SDValue Op0 = N->getOperand(0);
5279 SDValue Op1 = N->getOperand(1);
5280 assert(Op0.getValueType() == Op1.getValueType());
5282 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5283 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5284 if (COp0 && COp0->isNullValue())
5286 else if (COp1 && COp1->isNullValue())
5291 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5293 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5299 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5300 SDValue N0 = N->getOperand(0);
5301 EVT VT = N->getValueType(0);
5303 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5305 return SDValue(Res, 0);
5307 // fold (zext (zext x)) -> (zext x)
5308 // fold (zext (aext x)) -> (zext x)
5309 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5310 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5313 // fold (zext (truncate x)) -> (zext x) or
5314 // (zext (truncate x)) -> (truncate x)
5315 // This is valid when the truncated bits of x are already zero.
5316 // FIXME: We should extend this to work for vectors too.
5319 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5320 APInt TruncatedBits =
5321 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5322 APInt(Op.getValueSizeInBits(), 0) :
5323 APInt::getBitsSet(Op.getValueSizeInBits(),
5324 N0.getValueSizeInBits(),
5325 std::min(Op.getValueSizeInBits(),
5326 VT.getSizeInBits()));
5327 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5328 if (VT.bitsGT(Op.getValueType()))
5329 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5330 if (VT.bitsLT(Op.getValueType()))
5331 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5337 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5338 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5339 if (N0.getOpcode() == ISD::TRUNCATE) {
5340 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5341 if (NarrowLoad.getNode()) {
5342 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5343 if (NarrowLoad.getNode() != N0.getNode()) {
5344 CombineTo(N0.getNode(), NarrowLoad);
5345 // CombineTo deleted the truncate, if needed, but not what's under it.
5348 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5352 // fold (zext (truncate x)) -> (and x, mask)
5353 if (N0.getOpcode() == ISD::TRUNCATE &&
5354 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5356 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5357 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5358 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5359 if (NarrowLoad.getNode()) {
5360 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5361 if (NarrowLoad.getNode() != N0.getNode()) {
5362 CombineTo(N0.getNode(), NarrowLoad);
5363 // CombineTo deleted the truncate, if needed, but not what's under it.
5366 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5369 SDValue Op = N0.getOperand(0);
5370 if (Op.getValueType().bitsLT(VT)) {
5371 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5372 AddToWorklist(Op.getNode());
5373 } else if (Op.getValueType().bitsGT(VT)) {
5374 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5375 AddToWorklist(Op.getNode());
5377 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5378 N0.getValueType().getScalarType());
5381 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5382 // if either of the casts is not free.
5383 if (N0.getOpcode() == ISD::AND &&
5384 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5385 N0.getOperand(1).getOpcode() == ISD::Constant &&
5386 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5387 N0.getValueType()) ||
5388 !TLI.isZExtFree(N0.getValueType(), VT))) {
5389 SDValue X = N0.getOperand(0).getOperand(0);
5390 if (X.getValueType().bitsLT(VT)) {
5391 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5392 } else if (X.getValueType().bitsGT(VT)) {
5393 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5395 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5396 Mask = Mask.zext(VT.getSizeInBits());
5397 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5398 X, DAG.getConstant(Mask, VT));
5401 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5402 // None of the supported targets knows how to perform load and vector_zext
5403 // on vectors in one instruction. We only perform this transformation on
5405 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5406 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5407 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5408 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5409 bool DoXform = true;
5410 SmallVector<SDNode*, 4> SetCCs;
5411 if (!N0.hasOneUse())
5412 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5414 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5415 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5417 LN0->getBasePtr(), N0.getValueType(),
5418 LN0->getMemOperand());
5419 CombineTo(N, ExtLoad);
5420 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5421 N0.getValueType(), ExtLoad);
5422 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5424 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5426 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5430 // fold (zext (and/or/xor (load x), cst)) ->
5431 // (and/or/xor (zextload x), (zext cst))
5432 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5433 N0.getOpcode() == ISD::XOR) &&
5434 isa<LoadSDNode>(N0.getOperand(0)) &&
5435 N0.getOperand(1).getOpcode() == ISD::Constant &&
5436 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5437 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5438 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5439 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5440 bool DoXform = true;
5441 SmallVector<SDNode*, 4> SetCCs;
5442 if (!N0.hasOneUse())
5443 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5446 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5447 LN0->getChain(), LN0->getBasePtr(),
5449 LN0->getMemOperand());
5450 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5451 Mask = Mask.zext(VT.getSizeInBits());
5452 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5453 ExtLoad, DAG.getConstant(Mask, VT));
5454 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5455 SDLoc(N0.getOperand(0)),
5456 N0.getOperand(0).getValueType(), ExtLoad);
5458 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5459 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5461 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5466 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5467 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5468 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5469 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5470 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5471 EVT MemVT = LN0->getMemoryVT();
5472 if ((!LegalOperations && !LN0->isVolatile()) ||
5473 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5474 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5476 LN0->getBasePtr(), MemVT,
5477 LN0->getMemOperand());
5478 CombineTo(N, ExtLoad);
5479 CombineTo(N0.getNode(),
5480 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5482 ExtLoad.getValue(1));
5483 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5487 if (N0.getOpcode() == ISD::SETCC) {
5488 if (!LegalOperations && VT.isVector() &&
5489 N0.getValueType().getVectorElementType() == MVT::i1) {
5490 EVT N0VT = N0.getOperand(0).getValueType();
5491 if (getSetCCResultType(N0VT) == N0.getValueType())
5494 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5495 // Only do this before legalize for now.
5496 EVT EltVT = VT.getVectorElementType();
5497 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5498 DAG.getConstant(1, EltVT));
5499 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5500 // We know that the # elements of the results is the same as the
5501 // # elements of the compare (and the # elements of the compare result
5502 // for that matter). Check to see that they are the same size. If so,
5503 // we know that the element size of the sext'd result matches the
5504 // element size of the compare operands.
5505 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5506 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5508 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5509 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5512 // If the desired elements are smaller or larger than the source
5513 // elements we can use a matching integer vector type and then
5514 // truncate/sign extend
5515 EVT MatchingElementType =
5516 EVT::getIntegerVT(*DAG.getContext(),
5517 N0VT.getScalarType().getSizeInBits());
5518 EVT MatchingVectorType =
5519 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5520 N0VT.getVectorNumElements());
5522 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5524 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5525 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5526 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5527 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5530 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5532 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5533 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5534 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5535 if (SCC.getNode()) return SCC;
5538 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5539 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5540 isa<ConstantSDNode>(N0.getOperand(1)) &&
5541 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5543 SDValue ShAmt = N0.getOperand(1);
5544 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5545 if (N0.getOpcode() == ISD::SHL) {
5546 SDValue InnerZExt = N0.getOperand(0);
5547 // If the original shl may be shifting out bits, do not perform this
5549 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5550 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5551 if (ShAmtVal > KnownZeroBits)
5557 // Ensure that the shift amount is wide enough for the shifted value.
5558 if (VT.getSizeInBits() >= 256)
5559 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5561 return DAG.getNode(N0.getOpcode(), DL, VT,
5562 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5569 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5570 SDValue N0 = N->getOperand(0);
5571 EVT VT = N->getValueType(0);
5573 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5575 return SDValue(Res, 0);
5577 // fold (aext (aext x)) -> (aext x)
5578 // fold (aext (zext x)) -> (zext x)
5579 // fold (aext (sext x)) -> (sext x)
5580 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5581 N0.getOpcode() == ISD::ZERO_EXTEND ||
5582 N0.getOpcode() == ISD::SIGN_EXTEND)
5583 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5585 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5586 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5587 if (N0.getOpcode() == ISD::TRUNCATE) {
5588 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5589 if (NarrowLoad.getNode()) {
5590 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5591 if (NarrowLoad.getNode() != N0.getNode()) {
5592 CombineTo(N0.getNode(), NarrowLoad);
5593 // CombineTo deleted the truncate, if needed, but not what's under it.
5596 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5600 // fold (aext (truncate x))
5601 if (N0.getOpcode() == ISD::TRUNCATE) {
5602 SDValue TruncOp = N0.getOperand(0);
5603 if (TruncOp.getValueType() == VT)
5604 return TruncOp; // x iff x size == zext size.
5605 if (TruncOp.getValueType().bitsGT(VT))
5606 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5607 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5610 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5611 // if the trunc is not free.
5612 if (N0.getOpcode() == ISD::AND &&
5613 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5614 N0.getOperand(1).getOpcode() == ISD::Constant &&
5615 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5616 N0.getValueType())) {
5617 SDValue X = N0.getOperand(0).getOperand(0);
5618 if (X.getValueType().bitsLT(VT)) {
5619 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5620 } else if (X.getValueType().bitsGT(VT)) {
5621 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5623 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5624 Mask = Mask.zext(VT.getSizeInBits());
5625 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5626 X, DAG.getConstant(Mask, VT));
5629 // fold (aext (load x)) -> (aext (truncate (extload x)))
5630 // None of the supported targets knows how to perform load and any_ext
5631 // on vectors in one instruction. We only perform this transformation on
5633 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5634 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5635 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5636 bool DoXform = true;
5637 SmallVector<SDNode*, 4> SetCCs;
5638 if (!N0.hasOneUse())
5639 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5641 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5642 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, 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));
5650 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5652 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5656 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5657 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5658 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5659 if (N0.getOpcode() == ISD::LOAD &&
5660 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5662 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5663 ISD::LoadExtType ExtType = LN0->getExtensionType();
5664 EVT MemVT = LN0->getMemoryVT();
5665 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5666 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5667 VT, LN0->getChain(), LN0->getBasePtr(),
5668 MemVT, LN0->getMemOperand());
5669 CombineTo(N, ExtLoad);
5670 CombineTo(N0.getNode(),
5671 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5672 N0.getValueType(), ExtLoad),
5673 ExtLoad.getValue(1));
5674 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5678 if (N0.getOpcode() == ISD::SETCC) {
5680 // aext(setcc) -> vsetcc
5681 // aext(setcc) -> truncate(vsetcc)
5682 // aext(setcc) -> aext(vsetcc)
5683 // Only do this before legalize for now.
5684 if (VT.isVector() && !LegalOperations) {
5685 EVT N0VT = N0.getOperand(0).getValueType();
5686 // We know that the # elements of the results is the same as the
5687 // # elements of the compare (and the # elements of the compare result
5688 // for that matter). Check to see that they are the same size. If so,
5689 // we know that the element size of the sext'd result matches the
5690 // element size of the compare operands.
5691 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5692 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5694 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5695 // If the desired elements are smaller or larger than the source
5696 // elements we can use a matching integer vector type and then
5697 // truncate/any extend
5699 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5701 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5703 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5704 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5708 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5710 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5711 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5712 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5720 /// See if the specified operand can be simplified with the knowledge that only
5721 /// the bits specified by Mask are used. If so, return the simpler operand,
5722 /// otherwise return a null SDValue.
5723 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5724 switch (V.getOpcode()) {
5726 case ISD::Constant: {
5727 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5728 assert(CV && "Const value should be ConstSDNode.");
5729 const APInt &CVal = CV->getAPIntValue();
5730 APInt NewVal = CVal & Mask;
5732 return DAG.getConstant(NewVal, V.getValueType());
5737 // If the LHS or RHS don't contribute bits to the or, drop them.
5738 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5739 return V.getOperand(1);
5740 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5741 return V.getOperand(0);
5744 // Only look at single-use SRLs.
5745 if (!V.getNode()->hasOneUse())
5747 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5748 // See if we can recursively simplify the LHS.
5749 unsigned Amt = RHSC->getZExtValue();
5751 // Watch out for shift count overflow though.
5752 if (Amt >= Mask.getBitWidth()) break;
5753 APInt NewMask = Mask << Amt;
5754 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5755 if (SimplifyLHS.getNode())
5756 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5757 SimplifyLHS, V.getOperand(1));
5763 /// If the result of a wider load is shifted to right of N bits and then
5764 /// truncated to a narrower type and where N is a multiple of number of bits of
5765 /// the narrower type, transform it to a narrower load from address + N / num of
5766 /// bits of new type. If the result is to be extended, also fold the extension
5767 /// to form a extending load.
5768 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5769 unsigned Opc = N->getOpcode();
5771 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5772 SDValue N0 = N->getOperand(0);
5773 EVT VT = N->getValueType(0);
5776 // This transformation isn't valid for vector loads.
5780 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5782 if (Opc == ISD::SIGN_EXTEND_INREG) {
5783 ExtType = ISD::SEXTLOAD;
5784 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5785 } else if (Opc == ISD::SRL) {
5786 // Another special-case: SRL is basically zero-extending a narrower value.
5787 ExtType = ISD::ZEXTLOAD;
5789 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5790 if (!N01) return SDValue();
5791 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5792 VT.getSizeInBits() - N01->getZExtValue());
5794 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5797 unsigned EVTBits = ExtVT.getSizeInBits();
5799 // Do not generate loads of non-round integer types since these can
5800 // be expensive (and would be wrong if the type is not byte sized).
5801 if (!ExtVT.isRound())
5805 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5806 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5807 ShAmt = N01->getZExtValue();
5808 // Is the shift amount a multiple of size of VT?
5809 if ((ShAmt & (EVTBits-1)) == 0) {
5810 N0 = N0.getOperand(0);
5811 // Is the load width a multiple of size of VT?
5812 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5816 // At this point, we must have a load or else we can't do the transform.
5817 if (!isa<LoadSDNode>(N0)) return SDValue();
5819 // Because a SRL must be assumed to *need* to zero-extend the high bits
5820 // (as opposed to anyext the high bits), we can't combine the zextload
5821 // lowering of SRL and an sextload.
5822 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5825 // If the shift amount is larger than the input type then we're not
5826 // accessing any of the loaded bytes. If the load was a zextload/extload
5827 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5828 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5833 // If the load is shifted left (and the result isn't shifted back right),
5834 // we can fold the truncate through the shift.
5835 unsigned ShLeftAmt = 0;
5836 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5837 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5838 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5839 ShLeftAmt = N01->getZExtValue();
5840 N0 = N0.getOperand(0);
5844 // If we haven't found a load, we can't narrow it. Don't transform one with
5845 // multiple uses, this would require adding a new load.
5846 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5849 // Don't change the width of a volatile load.
5850 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5851 if (LN0->isVolatile())
5854 // Verify that we are actually reducing a load width here.
5855 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5858 // For the transform to be legal, the load must produce only two values
5859 // (the value loaded and the chain). Don't transform a pre-increment
5860 // load, for example, which produces an extra value. Otherwise the
5861 // transformation is not equivalent, and the downstream logic to replace
5862 // uses gets things wrong.
5863 if (LN0->getNumValues() > 2)
5866 // If the load that we're shrinking is an extload and we're not just
5867 // discarding the extension we can't simply shrink the load. Bail.
5868 // TODO: It would be possible to merge the extensions in some cases.
5869 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5870 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5873 EVT PtrType = N0.getOperand(1).getValueType();
5875 if (PtrType == MVT::Untyped || PtrType.isExtended())
5876 // It's not possible to generate a constant of extended or untyped type.
5879 // For big endian targets, we need to adjust the offset to the pointer to
5880 // load the correct bytes.
5881 if (TLI.isBigEndian()) {
5882 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5883 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5884 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5887 uint64_t PtrOff = ShAmt / 8;
5888 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5889 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5890 PtrType, LN0->getBasePtr(),
5891 DAG.getConstant(PtrOff, PtrType));
5892 AddToWorklist(NewPtr.getNode());
5895 if (ExtType == ISD::NON_EXTLOAD)
5896 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5897 LN0->getPointerInfo().getWithOffset(PtrOff),
5898 LN0->isVolatile(), LN0->isNonTemporal(),
5899 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5901 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5902 LN0->getPointerInfo().getWithOffset(PtrOff),
5903 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5904 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5906 // Replace the old load's chain with the new load's chain.
5907 WorklistRemover DeadNodes(*this);
5908 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5910 // Shift the result left, if we've swallowed a left shift.
5911 SDValue Result = Load;
5912 if (ShLeftAmt != 0) {
5913 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5914 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5916 // If the shift amount is as large as the result size (but, presumably,
5917 // no larger than the source) then the useful bits of the result are
5918 // zero; we can't simply return the shortened shift, because the result
5919 // of that operation is undefined.
5920 if (ShLeftAmt >= VT.getSizeInBits())
5921 Result = DAG.getConstant(0, VT);
5923 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5924 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5927 // Return the new loaded value.
5931 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5932 SDValue N0 = N->getOperand(0);
5933 SDValue N1 = N->getOperand(1);
5934 EVT VT = N->getValueType(0);
5935 EVT EVT = cast<VTSDNode>(N1)->getVT();
5936 unsigned VTBits = VT.getScalarType().getSizeInBits();
5937 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5939 // fold (sext_in_reg c1) -> c1
5940 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5941 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5943 // If the input is already sign extended, just drop the extension.
5944 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5947 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5948 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5949 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5950 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5951 N0.getOperand(0), N1);
5953 // fold (sext_in_reg (sext x)) -> (sext x)
5954 // fold (sext_in_reg (aext x)) -> (sext x)
5955 // if x is small enough.
5956 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5957 SDValue N00 = N0.getOperand(0);
5958 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5959 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5960 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5963 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5964 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5965 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5967 // fold operands of sext_in_reg based on knowledge that the top bits are not
5969 if (SimplifyDemandedBits(SDValue(N, 0)))
5970 return SDValue(N, 0);
5972 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5973 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5974 SDValue NarrowLoad = ReduceLoadWidth(N);
5975 if (NarrowLoad.getNode())
5978 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5979 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5980 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5981 if (N0.getOpcode() == ISD::SRL) {
5982 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5983 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5984 // We can turn this into an SRA iff the input to the SRL is already sign
5986 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5987 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5988 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5989 N0.getOperand(0), N0.getOperand(1));
5993 // fold (sext_inreg (extload x)) -> (sextload x)
5994 if (ISD::isEXTLoad(N0.getNode()) &&
5995 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5996 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5997 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5998 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5999 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6000 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6002 LN0->getBasePtr(), EVT,
6003 LN0->getMemOperand());
6004 CombineTo(N, ExtLoad);
6005 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6006 AddToWorklist(ExtLoad.getNode());
6007 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6009 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6010 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6012 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6013 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6014 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6015 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6016 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6018 LN0->getBasePtr(), EVT,
6019 LN0->getMemOperand());
6020 CombineTo(N, ExtLoad);
6021 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6022 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6025 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6026 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6027 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6028 N0.getOperand(1), false);
6029 if (BSwap.getNode())
6030 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6034 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6035 // into a build_vector.
6036 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6037 SmallVector<SDValue, 8> Elts;
6038 unsigned NumElts = N0->getNumOperands();
6039 unsigned ShAmt = VTBits - EVTBits;
6041 for (unsigned i = 0; i != NumElts; ++i) {
6042 SDValue Op = N0->getOperand(i);
6043 if (Op->getOpcode() == ISD::UNDEF) {
6048 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6049 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6050 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6051 Op.getValueType()));
6054 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6060 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6061 SDValue N0 = N->getOperand(0);
6062 EVT VT = N->getValueType(0);
6063 bool isLE = TLI.isLittleEndian();
6066 if (N0.getValueType() == N->getValueType(0))
6068 // fold (truncate c1) -> c1
6069 if (isa<ConstantSDNode>(N0))
6070 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6071 // fold (truncate (truncate x)) -> (truncate x)
6072 if (N0.getOpcode() == ISD::TRUNCATE)
6073 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6074 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6075 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6076 N0.getOpcode() == ISD::SIGN_EXTEND ||
6077 N0.getOpcode() == ISD::ANY_EXTEND) {
6078 if (N0.getOperand(0).getValueType().bitsLT(VT))
6079 // if the source is smaller than the dest, we still need an extend
6080 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6082 if (N0.getOperand(0).getValueType().bitsGT(VT))
6083 // if the source is larger than the dest, than we just need the truncate
6084 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6085 // if the source and dest are the same type, we can drop both the extend
6086 // and the truncate.
6087 return N0.getOperand(0);
6090 // Fold extract-and-trunc into a narrow extract. For example:
6091 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6092 // i32 y = TRUNCATE(i64 x)
6094 // v16i8 b = BITCAST (v2i64 val)
6095 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6097 // Note: We only run this optimization after type legalization (which often
6098 // creates this pattern) and before operation legalization after which
6099 // we need to be more careful about the vector instructions that we generate.
6100 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6101 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6103 EVT VecTy = N0.getOperand(0).getValueType();
6104 EVT ExTy = N0.getValueType();
6105 EVT TrTy = N->getValueType(0);
6107 unsigned NumElem = VecTy.getVectorNumElements();
6108 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6110 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6111 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6113 SDValue EltNo = N0->getOperand(1);
6114 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6115 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6116 EVT IndexTy = TLI.getVectorIdxTy();
6117 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6119 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6120 NVT, N0.getOperand(0));
6122 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6124 DAG.getConstant(Index, IndexTy));
6128 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6129 if (N0.getOpcode() == ISD::SELECT) {
6130 EVT SrcVT = N0.getValueType();
6131 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6132 TLI.isTruncateFree(SrcVT, VT)) {
6134 SDValue Cond = N0.getOperand(0);
6135 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6136 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6137 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6141 // Fold a series of buildvector, bitcast, and truncate if possible.
6143 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6144 // (2xi32 (buildvector x, y)).
6145 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6146 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6147 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6148 N0.getOperand(0).hasOneUse()) {
6150 SDValue BuildVect = N0.getOperand(0);
6151 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6152 EVT TruncVecEltTy = VT.getVectorElementType();
6154 // Check that the element types match.
6155 if (BuildVectEltTy == TruncVecEltTy) {
6156 // Now we only need to compute the offset of the truncated elements.
6157 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6158 unsigned TruncVecNumElts = VT.getVectorNumElements();
6159 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6161 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6162 "Invalid number of elements");
6164 SmallVector<SDValue, 8> Opnds;
6165 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6166 Opnds.push_back(BuildVect.getOperand(i));
6168 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6172 // See if we can simplify the input to this truncate through knowledge that
6173 // only the low bits are being used.
6174 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6175 // Currently we only perform this optimization on scalars because vectors
6176 // may have different active low bits.
6177 if (!VT.isVector()) {
6179 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6180 VT.getSizeInBits()));
6181 if (Shorter.getNode())
6182 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6184 // fold (truncate (load x)) -> (smaller load x)
6185 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6186 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6187 SDValue Reduced = ReduceLoadWidth(N);
6188 if (Reduced.getNode())
6190 // Handle the case where the load remains an extending load even
6191 // after truncation.
6192 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6193 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6194 if (!LN0->isVolatile() &&
6195 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6196 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6197 VT, LN0->getChain(), LN0->getBasePtr(),
6199 LN0->getMemOperand());
6200 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6205 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6206 // where ... are all 'undef'.
6207 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6208 SmallVector<EVT, 8> VTs;
6211 unsigned NumDefs = 0;
6213 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6214 SDValue X = N0.getOperand(i);
6215 if (X.getOpcode() != ISD::UNDEF) {
6220 // Stop if more than one members are non-undef.
6223 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6224 VT.getVectorElementType(),
6225 X.getValueType().getVectorNumElements()));
6229 return DAG.getUNDEF(VT);
6232 assert(V.getNode() && "The single defined operand is empty!");
6233 SmallVector<SDValue, 8> Opnds;
6234 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6236 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6239 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6240 AddToWorklist(NV.getNode());
6241 Opnds.push_back(NV);
6243 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6247 // Simplify the operands using demanded-bits information.
6248 if (!VT.isVector() &&
6249 SimplifyDemandedBits(SDValue(N, 0)))
6250 return SDValue(N, 0);
6255 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6256 SDValue Elt = N->getOperand(i);
6257 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6258 return Elt.getNode();
6259 return Elt.getOperand(Elt.getResNo()).getNode();
6262 /// build_pair (load, load) -> load
6263 /// if load locations are consecutive.
6264 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6265 assert(N->getOpcode() == ISD::BUILD_PAIR);
6267 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6268 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6269 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6270 LD1->getAddressSpace() != LD2->getAddressSpace())
6272 EVT LD1VT = LD1->getValueType(0);
6274 if (ISD::isNON_EXTLoad(LD2) &&
6276 // If both are volatile this would reduce the number of volatile loads.
6277 // If one is volatile it might be ok, but play conservative and bail out.
6278 !LD1->isVolatile() &&
6279 !LD2->isVolatile() &&
6280 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6281 unsigned Align = LD1->getAlignment();
6282 unsigned NewAlign = TLI.getDataLayout()->
6283 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6285 if (NewAlign <= Align &&
6286 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6287 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6288 LD1->getBasePtr(), LD1->getPointerInfo(),
6289 false, false, false, Align);
6295 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6296 SDValue N0 = N->getOperand(0);
6297 EVT VT = N->getValueType(0);
6299 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6300 // Only do this before legalize, since afterward the target may be depending
6301 // on the bitconvert.
6302 // First check to see if this is all constant.
6304 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6306 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6308 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6309 assert(!DestEltVT.isVector() &&
6310 "Element type of vector ValueType must not be vector!");
6312 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6315 // If the input is a constant, let getNode fold it.
6316 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6317 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6318 if (Res.getNode() != N) {
6319 if (!LegalOperations ||
6320 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6323 // Folding it resulted in an illegal node, and it's too late to
6324 // do that. Clean up the old node and forego the transformation.
6325 // Ideally this won't happen very often, because instcombine
6326 // and the earlier dagcombine runs (where illegal nodes are
6327 // permitted) should have folded most of them already.
6328 deleteAndRecombine(Res.getNode());
6332 // (conv (conv x, t1), t2) -> (conv x, t2)
6333 if (N0.getOpcode() == ISD::BITCAST)
6334 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6337 // fold (conv (load x)) -> (load (conv*)x)
6338 // If the resultant load doesn't need a higher alignment than the original!
6339 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6340 // Do not change the width of a volatile load.
6341 !cast<LoadSDNode>(N0)->isVolatile() &&
6342 // Do not remove the cast if the types differ in endian layout.
6343 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6344 TLI.hasBigEndianPartOrdering(VT) &&
6345 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6346 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6347 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6348 unsigned Align = TLI.getDataLayout()->
6349 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6350 unsigned OrigAlign = LN0->getAlignment();
6352 if (Align <= OrigAlign) {
6353 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6354 LN0->getBasePtr(), LN0->getPointerInfo(),
6355 LN0->isVolatile(), LN0->isNonTemporal(),
6356 LN0->isInvariant(), OrigAlign,
6358 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6363 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6364 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6365 // This often reduces constant pool loads.
6366 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6367 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6368 N0.getNode()->hasOneUse() && VT.isInteger() &&
6369 !VT.isVector() && !N0.getValueType().isVector()) {
6370 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6372 AddToWorklist(NewConv.getNode());
6374 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6375 if (N0.getOpcode() == ISD::FNEG)
6376 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6377 NewConv, DAG.getConstant(SignBit, VT));
6378 assert(N0.getOpcode() == ISD::FABS);
6379 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6380 NewConv, DAG.getConstant(~SignBit, VT));
6383 // fold (bitconvert (fcopysign cst, x)) ->
6384 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6385 // Note that we don't handle (copysign x, cst) because this can always be
6386 // folded to an fneg or fabs.
6387 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6388 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6389 VT.isInteger() && !VT.isVector()) {
6390 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6391 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6392 if (isTypeLegal(IntXVT)) {
6393 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6394 IntXVT, N0.getOperand(1));
6395 AddToWorklist(X.getNode());
6397 // If X has a different width than the result/lhs, sext it or truncate it.
6398 unsigned VTWidth = VT.getSizeInBits();
6399 if (OrigXWidth < VTWidth) {
6400 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6401 AddToWorklist(X.getNode());
6402 } else if (OrigXWidth > VTWidth) {
6403 // To get the sign bit in the right place, we have to shift it right
6404 // before truncating.
6405 X = DAG.getNode(ISD::SRL, SDLoc(X),
6406 X.getValueType(), X,
6407 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6408 AddToWorklist(X.getNode());
6409 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6410 AddToWorklist(X.getNode());
6413 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6414 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6415 X, DAG.getConstant(SignBit, VT));
6416 AddToWorklist(X.getNode());
6418 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6419 VT, N0.getOperand(0));
6420 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6421 Cst, DAG.getConstant(~SignBit, VT));
6422 AddToWorklist(Cst.getNode());
6424 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6428 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6429 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6430 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6431 if (CombineLD.getNode())
6438 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6439 EVT VT = N->getValueType(0);
6440 return CombineConsecutiveLoads(N, VT);
6443 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6444 /// operands. DstEltVT indicates the destination element value type.
6445 SDValue DAGCombiner::
6446 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6447 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6449 // If this is already the right type, we're done.
6450 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6452 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6453 unsigned DstBitSize = DstEltVT.getSizeInBits();
6455 // If this is a conversion of N elements of one type to N elements of another
6456 // type, convert each element. This handles FP<->INT cases.
6457 if (SrcBitSize == DstBitSize) {
6458 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6459 BV->getValueType(0).getVectorNumElements());
6461 // Due to the FP element handling below calling this routine recursively,
6462 // we can end up with a scalar-to-vector node here.
6463 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6464 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6465 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6466 DstEltVT, BV->getOperand(0)));
6468 SmallVector<SDValue, 8> Ops;
6469 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6470 SDValue Op = BV->getOperand(i);
6471 // If the vector element type is not legal, the BUILD_VECTOR operands
6472 // are promoted and implicitly truncated. Make that explicit here.
6473 if (Op.getValueType() != SrcEltVT)
6474 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6475 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6477 AddToWorklist(Ops.back().getNode());
6479 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6482 // Otherwise, we're growing or shrinking the elements. To avoid having to
6483 // handle annoying details of growing/shrinking FP values, we convert them to
6485 if (SrcEltVT.isFloatingPoint()) {
6486 // Convert the input float vector to a int vector where the elements are the
6488 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6489 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6490 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6494 // Now we know the input is an integer vector. If the output is a FP type,
6495 // convert to integer first, then to FP of the right size.
6496 if (DstEltVT.isFloatingPoint()) {
6497 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6498 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6499 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6501 // Next, convert to FP elements of the same size.
6502 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6505 // Okay, we know the src/dst types are both integers of differing types.
6506 // Handling growing first.
6507 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6508 if (SrcBitSize < DstBitSize) {
6509 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6511 SmallVector<SDValue, 8> Ops;
6512 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6513 i += NumInputsPerOutput) {
6514 bool isLE = TLI.isLittleEndian();
6515 APInt NewBits = APInt(DstBitSize, 0);
6516 bool EltIsUndef = true;
6517 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6518 // Shift the previously computed bits over.
6519 NewBits <<= SrcBitSize;
6520 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6521 if (Op.getOpcode() == ISD::UNDEF) continue;
6524 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6525 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6529 Ops.push_back(DAG.getUNDEF(DstEltVT));
6531 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6534 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6535 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6538 // Finally, this must be the case where we are shrinking elements: each input
6539 // turns into multiple outputs.
6540 bool isS2V = ISD::isScalarToVector(BV);
6541 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6542 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6543 NumOutputsPerInput*BV->getNumOperands());
6544 SmallVector<SDValue, 8> Ops;
6546 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6547 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6548 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6549 Ops.push_back(DAG.getUNDEF(DstEltVT));
6553 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6554 getAPIntValue().zextOrTrunc(SrcBitSize);
6556 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6557 APInt ThisVal = OpVal.trunc(DstBitSize);
6558 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6559 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6560 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6561 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6563 OpVal = OpVal.lshr(DstBitSize);
6566 // For big endian targets, swap the order of the pieces of each element.
6567 if (TLI.isBigEndian())
6568 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6571 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6574 SDValue DAGCombiner::visitFADD(SDNode *N) {
6575 SDValue N0 = N->getOperand(0);
6576 SDValue N1 = N->getOperand(1);
6577 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6578 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6579 EVT VT = N->getValueType(0);
6580 const TargetOptions &Options = DAG.getTarget().Options;
6583 if (VT.isVector()) {
6584 SDValue FoldedVOp = SimplifyVBinOp(N);
6585 if (FoldedVOp.getNode()) return FoldedVOp;
6588 // fold (fadd c1, c2) -> c1 + c2
6590 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6592 // canonicalize constant to RHS
6593 if (N0CFP && !N1CFP)
6594 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6596 // fold (fadd A, (fneg B)) -> (fsub A, B)
6597 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6598 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6599 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6600 GetNegatedExpression(N1, DAG, LegalOperations));
6602 // fold (fadd (fneg A), B) -> (fsub B, A)
6603 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6604 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6605 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6606 GetNegatedExpression(N0, DAG, LegalOperations));
6608 // If 'unsafe math' is enabled, fold lots of things.
6609 if (Options.UnsafeFPMath) {
6610 // No FP constant should be created after legalization as Instruction
6611 // Selection pass has a hard time dealing with FP constants.
6612 bool AllowNewConst = (Level < AfterLegalizeDAG);
6614 // fold (fadd A, 0) -> A
6615 if (N1CFP && N1CFP->getValueAPF().isZero())
6618 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6619 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6620 isa<ConstantFPSDNode>(N0.getOperand(1)))
6621 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6622 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6623 N0.getOperand(1), N1));
6625 // If allowed, fold (fadd (fneg x), x) -> 0.0
6626 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6627 return DAG.getConstantFP(0.0, VT);
6629 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6630 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6631 return DAG.getConstantFP(0.0, VT);
6633 // We can fold chains of FADD's of the same value into multiplications.
6634 // This transform is not safe in general because we are reducing the number
6635 // of rounding steps.
6636 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6637 if (N0.getOpcode() == ISD::FMUL) {
6638 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6639 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6641 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6642 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6643 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6645 DAG.getConstantFP(1.0, VT));
6646 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6649 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6650 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6651 N1.getOperand(0) == N1.getOperand(1) &&
6652 N0.getOperand(0) == N1.getOperand(0)) {
6653 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6655 DAG.getConstantFP(2.0, VT));
6656 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6657 N0.getOperand(0), NewCFP);
6661 if (N1.getOpcode() == ISD::FMUL) {
6662 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6663 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6665 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6666 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6667 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6669 DAG.getConstantFP(1.0, VT));
6670 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6673 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6674 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6675 N0.getOperand(0) == N0.getOperand(1) &&
6676 N1.getOperand(0) == N0.getOperand(0)) {
6677 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6679 DAG.getConstantFP(2.0, VT));
6680 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6684 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6685 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6686 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6687 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6688 (N0.getOperand(0) == N1))
6689 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6690 N1, DAG.getConstantFP(3.0, VT));
6693 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6694 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6695 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6696 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6697 N1.getOperand(0) == N0)
6698 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6699 N0, DAG.getConstantFP(3.0, VT));
6702 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6703 if (AllowNewConst &&
6704 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6705 N0.getOperand(0) == N0.getOperand(1) &&
6706 N1.getOperand(0) == N1.getOperand(1) &&
6707 N0.getOperand(0) == N1.getOperand(0))
6708 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6709 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6711 } // enable-unsafe-fp-math
6713 // FADD -> FMA combines:
6714 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6715 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6716 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6718 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6719 if (N0.getOpcode() == ISD::FMUL &&
6720 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6721 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6722 N0.getOperand(0), N0.getOperand(1), N1);
6724 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6725 // Note: Commutes FADD operands.
6726 if (N1.getOpcode() == ISD::FMUL &&
6727 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6728 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6729 N1.getOperand(0), N1.getOperand(1), N0);
6735 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6736 SDValue N0 = N->getOperand(0);
6737 SDValue N1 = N->getOperand(1);
6738 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6739 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6740 EVT VT = N->getValueType(0);
6742 const TargetOptions &Options = DAG.getTarget().Options;
6745 if (VT.isVector()) {
6746 SDValue FoldedVOp = SimplifyVBinOp(N);
6747 if (FoldedVOp.getNode()) return FoldedVOp;
6750 // fold (fsub c1, c2) -> c1-c2
6752 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6754 // fold (fsub A, (fneg B)) -> (fadd A, B)
6755 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6756 return DAG.getNode(ISD::FADD, dl, VT, N0,
6757 GetNegatedExpression(N1, DAG, LegalOperations));
6759 // If 'unsafe math' is enabled, fold lots of things.
6760 if (Options.UnsafeFPMath) {
6762 if (N1CFP && N1CFP->getValueAPF().isZero())
6765 // (fsub 0, B) -> -B
6766 if (N0CFP && N0CFP->getValueAPF().isZero()) {
6767 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6768 return GetNegatedExpression(N1, DAG, LegalOperations);
6769 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6770 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6773 // (fsub x, x) -> 0.0
6775 return DAG.getConstantFP(0.0f, VT);
6777 // (fsub x, (fadd x, y)) -> (fneg y)
6778 // (fsub x, (fadd y, x)) -> (fneg y)
6779 if (N1.getOpcode() == ISD::FADD) {
6780 SDValue N10 = N1->getOperand(0);
6781 SDValue N11 = N1->getOperand(1);
6783 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6784 return GetNegatedExpression(N11, DAG, LegalOperations);
6786 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6787 return GetNegatedExpression(N10, DAG, LegalOperations);
6791 // FSUB -> FMA combines:
6792 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6793 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6794 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6796 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6797 if (N0.getOpcode() == ISD::FMUL &&
6798 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6799 return DAG.getNode(ISD::FMA, dl, VT,
6800 N0.getOperand(0), N0.getOperand(1),
6801 DAG.getNode(ISD::FNEG, dl, VT, N1));
6803 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6804 // Note: Commutes FSUB operands.
6805 if (N1.getOpcode() == ISD::FMUL &&
6806 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6807 return DAG.getNode(ISD::FMA, dl, VT,
6808 DAG.getNode(ISD::FNEG, dl, VT,
6810 N1.getOperand(1), N0);
6812 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6813 if (N0.getOpcode() == ISD::FNEG &&
6814 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6815 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6816 TLI.enableAggressiveFMAFusion(VT))) {
6817 SDValue N00 = N0.getOperand(0).getOperand(0);
6818 SDValue N01 = N0.getOperand(0).getOperand(1);
6819 return DAG.getNode(ISD::FMA, dl, VT,
6820 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6821 DAG.getNode(ISD::FNEG, dl, VT, N1));
6828 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6829 SDValue N0 = N->getOperand(0);
6830 SDValue N1 = N->getOperand(1);
6831 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6832 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6833 EVT VT = N->getValueType(0);
6834 const TargetOptions &Options = DAG.getTarget().Options;
6837 if (VT.isVector()) {
6838 // This just handles C1 * C2 for vectors. Other vector folds are below.
6839 SDValue FoldedVOp = SimplifyVBinOp(N);
6840 if (FoldedVOp.getNode())
6842 // Canonicalize vector constant to RHS.
6843 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6844 N1.getOpcode() != ISD::BUILD_VECTOR)
6845 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6846 if (BV0->isConstant())
6847 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6850 // fold (fmul c1, c2) -> c1*c2
6852 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6854 // canonicalize constant to RHS
6855 if (N0CFP && !N1CFP)
6856 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6858 // fold (fmul A, 1.0) -> A
6859 if (N1CFP && N1CFP->isExactlyValue(1.0))
6862 if (Options.UnsafeFPMath) {
6863 // fold (fmul A, 0) -> 0
6864 if (N1CFP && N1CFP->getValueAPF().isZero())
6867 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6868 if (N0.getOpcode() == ISD::FMUL) {
6869 // Fold scalars or any vector constants (not just splats).
6870 // This fold is done in general by InstCombine, but extra fmul insts
6871 // may have been generated during lowering.
6872 SDValue N01 = N0.getOperand(1);
6873 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6874 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6875 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6876 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6878 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6879 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6883 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6884 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6885 // during an early run of DAGCombiner can prevent folding with fmuls
6886 // inserted during lowering.
6887 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6889 const SDValue Two = DAG.getConstantFP(2.0, VT);
6890 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6891 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6895 // fold (fmul X, 2.0) -> (fadd X, X)
6896 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6897 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6899 // fold (fmul X, -1.0) -> (fneg X)
6900 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6901 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6902 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6904 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6905 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6906 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6907 // Both can be negated for free, check to see if at least one is cheaper
6909 if (LHSNeg == 2 || RHSNeg == 2)
6910 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6911 GetNegatedExpression(N0, DAG, LegalOperations),
6912 GetNegatedExpression(N1, DAG, LegalOperations));
6919 SDValue DAGCombiner::visitFMA(SDNode *N) {
6920 SDValue N0 = N->getOperand(0);
6921 SDValue N1 = N->getOperand(1);
6922 SDValue N2 = N->getOperand(2);
6923 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6924 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6925 EVT VT = N->getValueType(0);
6927 const TargetOptions &Options = DAG.getTarget().Options;
6929 // Constant fold FMA.
6930 if (isa<ConstantFPSDNode>(N0) &&
6931 isa<ConstantFPSDNode>(N1) &&
6932 isa<ConstantFPSDNode>(N2)) {
6933 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6936 if (Options.UnsafeFPMath) {
6937 if (N0CFP && N0CFP->isZero())
6939 if (N1CFP && N1CFP->isZero())
6942 if (N0CFP && N0CFP->isExactlyValue(1.0))
6943 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6944 if (N1CFP && N1CFP->isExactlyValue(1.0))
6945 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6947 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6948 if (N0CFP && !N1CFP)
6949 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6951 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6952 if (Options.UnsafeFPMath && N1CFP &&
6953 N2.getOpcode() == ISD::FMUL &&
6954 N0 == N2.getOperand(0) &&
6955 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6956 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6957 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6961 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6962 if (Options.UnsafeFPMath &&
6963 N0.getOpcode() == ISD::FMUL && N1CFP &&
6964 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6965 return DAG.getNode(ISD::FMA, dl, VT,
6967 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6971 // (fma x, 1, y) -> (fadd x, y)
6972 // (fma x, -1, y) -> (fadd (fneg x), y)
6974 if (N1CFP->isExactlyValue(1.0))
6975 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6977 if (N1CFP->isExactlyValue(-1.0) &&
6978 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6979 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6980 AddToWorklist(RHSNeg.getNode());
6981 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6985 // (fma x, c, x) -> (fmul x, (c+1))
6986 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6987 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6988 DAG.getNode(ISD::FADD, dl, VT,
6989 N1, DAG.getConstantFP(1.0, VT)));
6991 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6992 if (Options.UnsafeFPMath && N1CFP &&
6993 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6994 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6995 DAG.getNode(ISD::FADD, dl, VT,
6996 N1, DAG.getConstantFP(-1.0, VT)));
7002 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7003 SDValue N0 = N->getOperand(0);
7004 SDValue N1 = N->getOperand(1);
7005 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7006 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7007 EVT VT = N->getValueType(0);
7009 const TargetOptions &Options = DAG.getTarget().Options;
7012 if (VT.isVector()) {
7013 SDValue FoldedVOp = SimplifyVBinOp(N);
7014 if (FoldedVOp.getNode()) return FoldedVOp;
7017 // fold (fdiv c1, c2) -> c1/c2
7019 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7021 if (Options.UnsafeFPMath) {
7022 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7024 // Compute the reciprocal 1.0 / c2.
7025 APFloat N1APF = N1CFP->getValueAPF();
7026 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7027 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7028 // Only do the transform if the reciprocal is a legal fp immediate that
7029 // isn't too nasty (eg NaN, denormal, ...).
7030 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7031 (!LegalOperations ||
7032 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7033 // backend)... we should handle this gracefully after Legalize.
7034 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7035 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7036 TLI.isFPImmLegal(Recip, VT)))
7037 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7038 DAG.getConstantFP(Recip, VT));
7041 // If this FDIV is part of a reciprocal square root, it may be folded
7042 // into a target-specific square root estimate instruction.
7043 if (N1.getOpcode() == ISD::FSQRT) {
7044 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7045 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7047 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7048 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7049 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7050 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7051 AddToWorklist(RV.getNode());
7052 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7054 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7055 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7056 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7057 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7058 AddToWorklist(RV.getNode());
7059 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7061 } else if (N1.getOpcode() == ISD::FMUL) {
7062 // Look through an FMUL. Even though this won't remove the FDIV directly,
7063 // it's still worthwhile to get rid of the FSQRT if possible.
7066 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7067 SqrtOp = N1.getOperand(0);
7068 OtherOp = N1.getOperand(1);
7069 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7070 SqrtOp = N1.getOperand(1);
7071 OtherOp = N1.getOperand(0);
7073 if (SqrtOp.getNode()) {
7074 // We found a FSQRT, so try to make this fold:
7075 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7076 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7077 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7078 AddToWorklist(RV.getNode());
7079 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7084 // Fold into a reciprocal estimate and multiply instead of a real divide.
7085 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7086 AddToWorklist(RV.getNode());
7087 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7091 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7092 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7093 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7094 // Both can be negated for free, check to see if at least one is cheaper
7096 if (LHSNeg == 2 || RHSNeg == 2)
7097 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7098 GetNegatedExpression(N0, DAG, LegalOperations),
7099 GetNegatedExpression(N1, DAG, LegalOperations));
7106 SDValue DAGCombiner::visitFREM(SDNode *N) {
7107 SDValue N0 = N->getOperand(0);
7108 SDValue N1 = N->getOperand(1);
7109 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7110 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7111 EVT VT = N->getValueType(0);
7113 // fold (frem c1, c2) -> fmod(c1,c2)
7115 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7120 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7121 if (DAG.getTarget().Options.UnsafeFPMath) {
7122 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7123 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7124 EVT VT = RV.getValueType();
7125 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7126 AddToWorklist(RV.getNode());
7128 // Unfortunately, RV is now NaN if the input was exactly 0.
7129 // Select out this case and force the answer to 0.
7130 SDValue Zero = DAG.getConstantFP(0.0, VT);
7132 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7133 N->getOperand(0), Zero, ISD::SETEQ);
7134 AddToWorklist(ZeroCmp.getNode());
7135 AddToWorklist(RV.getNode());
7137 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7138 SDLoc(N), VT, ZeroCmp, Zero, RV);
7145 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7146 SDValue N0 = N->getOperand(0);
7147 SDValue N1 = N->getOperand(1);
7148 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7149 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7150 EVT VT = N->getValueType(0);
7152 if (N0CFP && N1CFP) // Constant fold
7153 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7156 const APFloat& V = N1CFP->getValueAPF();
7157 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7158 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7159 if (!V.isNegative()) {
7160 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7161 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7163 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7164 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7165 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7169 // copysign(fabs(x), y) -> copysign(x, y)
7170 // copysign(fneg(x), y) -> copysign(x, y)
7171 // copysign(copysign(x,z), y) -> copysign(x, y)
7172 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7173 N0.getOpcode() == ISD::FCOPYSIGN)
7174 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7175 N0.getOperand(0), N1);
7177 // copysign(x, abs(y)) -> abs(x)
7178 if (N1.getOpcode() == ISD::FABS)
7179 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7181 // copysign(x, copysign(y,z)) -> copysign(x, z)
7182 if (N1.getOpcode() == ISD::FCOPYSIGN)
7183 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7184 N0, N1.getOperand(1));
7186 // copysign(x, fp_extend(y)) -> copysign(x, y)
7187 // copysign(x, fp_round(y)) -> copysign(x, y)
7188 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7189 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7190 N0, N1.getOperand(0));
7195 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7196 SDValue N0 = N->getOperand(0);
7197 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7198 EVT VT = N->getValueType(0);
7199 EVT OpVT = N0.getValueType();
7201 // fold (sint_to_fp c1) -> c1fp
7203 // ...but only if the target supports immediate floating-point values
7204 (!LegalOperations ||
7205 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7206 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7208 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7209 // but UINT_TO_FP is legal on this target, try to convert.
7210 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7211 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7212 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7213 if (DAG.SignBitIsZero(N0))
7214 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7217 // The next optimizations are desirable only if SELECT_CC can be lowered.
7218 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7219 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7220 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7222 (!LegalOperations ||
7223 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7225 { N0.getOperand(0), N0.getOperand(1),
7226 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7228 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7231 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7232 // (select_cc x, y, 1.0, 0.0,, cc)
7233 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7234 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7235 (!LegalOperations ||
7236 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7238 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7239 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7240 N0.getOperand(0).getOperand(2) };
7241 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7248 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7249 SDValue N0 = N->getOperand(0);
7250 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7251 EVT VT = N->getValueType(0);
7252 EVT OpVT = N0.getValueType();
7254 // fold (uint_to_fp c1) -> c1fp
7256 // ...but only if the target supports immediate floating-point values
7257 (!LegalOperations ||
7258 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7259 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7261 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7262 // but SINT_TO_FP is legal on this target, try to convert.
7263 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7264 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7265 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7266 if (DAG.SignBitIsZero(N0))
7267 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7270 // The next optimizations are desirable only if SELECT_CC can be lowered.
7271 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7272 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7274 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7275 (!LegalOperations ||
7276 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7278 { N0.getOperand(0), N0.getOperand(1),
7279 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7281 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7288 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7289 SDValue N0 = N->getOperand(0);
7290 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7291 EVT VT = N->getValueType(0);
7293 // fold (fp_to_sint c1fp) -> c1
7295 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7300 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7301 SDValue N0 = N->getOperand(0);
7302 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7303 EVT VT = N->getValueType(0);
7305 // fold (fp_to_uint c1fp) -> c1
7307 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7312 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7313 SDValue N0 = N->getOperand(0);
7314 SDValue N1 = N->getOperand(1);
7315 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7316 EVT VT = N->getValueType(0);
7318 // fold (fp_round c1fp) -> c1fp
7320 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7322 // fold (fp_round (fp_extend x)) -> x
7323 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7324 return N0.getOperand(0);
7326 // fold (fp_round (fp_round x)) -> (fp_round x)
7327 if (N0.getOpcode() == ISD::FP_ROUND) {
7328 // This is a value preserving truncation if both round's are.
7329 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7330 N0.getNode()->getConstantOperandVal(1) == 1;
7331 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7332 DAG.getIntPtrConstant(IsTrunc));
7335 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7336 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7337 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7338 N0.getOperand(0), N1);
7339 AddToWorklist(Tmp.getNode());
7340 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7341 Tmp, N0.getOperand(1));
7347 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7348 SDValue N0 = N->getOperand(0);
7349 EVT VT = N->getValueType(0);
7350 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7351 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7353 // fold (fp_round_inreg c1fp) -> c1fp
7354 if (N0CFP && isTypeLegal(EVT)) {
7355 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7356 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7362 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7363 SDValue N0 = N->getOperand(0);
7364 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7365 EVT VT = N->getValueType(0);
7367 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7368 if (N->hasOneUse() &&
7369 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7372 // fold (fp_extend c1fp) -> c1fp
7374 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7376 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7378 if (N0.getOpcode() == ISD::FP_ROUND
7379 && N0.getNode()->getConstantOperandVal(1) == 1) {
7380 SDValue In = N0.getOperand(0);
7381 if (In.getValueType() == VT) return In;
7382 if (VT.bitsLT(In.getValueType()))
7383 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7384 In, N0.getOperand(1));
7385 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7388 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7389 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7390 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7391 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7392 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7394 LN0->getBasePtr(), N0.getValueType(),
7395 LN0->getMemOperand());
7396 CombineTo(N, ExtLoad);
7397 CombineTo(N0.getNode(),
7398 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7399 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7400 ExtLoad.getValue(1));
7401 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7407 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7408 SDValue N0 = N->getOperand(0);
7409 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7410 EVT VT = N->getValueType(0);
7412 // fold (fceil c1) -> fceil(c1)
7414 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7419 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7420 SDValue N0 = N->getOperand(0);
7421 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7422 EVT VT = N->getValueType(0);
7424 // fold (ftrunc c1) -> ftrunc(c1)
7426 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7431 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7432 SDValue N0 = N->getOperand(0);
7433 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7434 EVT VT = N->getValueType(0);
7436 // fold (ffloor c1) -> ffloor(c1)
7438 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7443 // FIXME: FNEG and FABS have a lot in common; refactor.
7444 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7445 SDValue N0 = N->getOperand(0);
7446 EVT VT = N->getValueType(0);
7448 if (VT.isVector()) {
7449 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7450 if (FoldedVOp.getNode()) return FoldedVOp;
7453 // Constant fold FNEG.
7454 if (isa<ConstantFPSDNode>(N0))
7455 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7457 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7458 &DAG.getTarget().Options))
7459 return GetNegatedExpression(N0, DAG, LegalOperations);
7461 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7462 // constant pool values.
7463 if (!TLI.isFNegFree(VT) &&
7464 N0.getOpcode() == ISD::BITCAST &&
7465 N0.getNode()->hasOneUse()) {
7466 SDValue Int = N0.getOperand(0);
7467 EVT IntVT = Int.getValueType();
7468 if (IntVT.isInteger() && !IntVT.isVector()) {
7470 if (N0.getValueType().isVector()) {
7471 // For a vector, get a mask such as 0x80... per scalar element
7473 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7474 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7476 // For a scalar, just generate 0x80...
7477 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7479 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7480 DAG.getConstant(SignMask, IntVT));
7481 AddToWorklist(Int.getNode());
7482 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7486 // (fneg (fmul c, x)) -> (fmul -c, x)
7487 if (N0.getOpcode() == ISD::FMUL) {
7488 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7490 APFloat CVal = CFP1->getValueAPF();
7492 if (Level >= AfterLegalizeDAG &&
7493 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7494 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7496 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7497 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7504 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7505 SDValue N0 = N->getOperand(0);
7506 SDValue N1 = N->getOperand(1);
7507 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7508 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7510 if (N0CFP && N1CFP) {
7511 const APFloat &C0 = N0CFP->getValueAPF();
7512 const APFloat &C1 = N1CFP->getValueAPF();
7513 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7517 EVT VT = N->getValueType(0);
7518 // Canonicalize to constant on RHS.
7519 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7525 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7526 SDValue N0 = N->getOperand(0);
7527 SDValue N1 = N->getOperand(1);
7528 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7529 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7531 if (N0CFP && N1CFP) {
7532 const APFloat &C0 = N0CFP->getValueAPF();
7533 const APFloat &C1 = N1CFP->getValueAPF();
7534 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7538 EVT VT = N->getValueType(0);
7539 // Canonicalize to constant on RHS.
7540 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7546 SDValue DAGCombiner::visitFABS(SDNode *N) {
7547 SDValue N0 = N->getOperand(0);
7548 EVT VT = N->getValueType(0);
7550 if (VT.isVector()) {
7551 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7552 if (FoldedVOp.getNode()) return FoldedVOp;
7555 // fold (fabs c1) -> fabs(c1)
7556 if (isa<ConstantFPSDNode>(N0))
7557 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7559 // fold (fabs (fabs x)) -> (fabs x)
7560 if (N0.getOpcode() == ISD::FABS)
7561 return N->getOperand(0);
7563 // fold (fabs (fneg x)) -> (fabs x)
7564 // fold (fabs (fcopysign x, y)) -> (fabs x)
7565 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7566 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7568 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7569 // constant pool values.
7570 if (!TLI.isFAbsFree(VT) &&
7571 N0.getOpcode() == ISD::BITCAST &&
7572 N0.getNode()->hasOneUse()) {
7573 SDValue Int = N0.getOperand(0);
7574 EVT IntVT = Int.getValueType();
7575 if (IntVT.isInteger() && !IntVT.isVector()) {
7577 if (N0.getValueType().isVector()) {
7578 // For a vector, get a mask such as 0x7f... per scalar element
7580 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7581 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7583 // For a scalar, just generate 0x7f...
7584 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7586 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7587 DAG.getConstant(SignMask, IntVT));
7588 AddToWorklist(Int.getNode());
7589 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7596 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7597 SDValue Chain = N->getOperand(0);
7598 SDValue N1 = N->getOperand(1);
7599 SDValue N2 = N->getOperand(2);
7601 // If N is a constant we could fold this into a fallthrough or unconditional
7602 // branch. However that doesn't happen very often in normal code, because
7603 // Instcombine/SimplifyCFG should have handled the available opportunities.
7604 // If we did this folding here, it would be necessary to update the
7605 // MachineBasicBlock CFG, which is awkward.
7607 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7609 if (N1.getOpcode() == ISD::SETCC &&
7610 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7611 N1.getOperand(0).getValueType())) {
7612 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7613 Chain, N1.getOperand(2),
7614 N1.getOperand(0), N1.getOperand(1), N2);
7617 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7618 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7619 (N1.getOperand(0).hasOneUse() &&
7620 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7621 SDNode *Trunc = nullptr;
7622 if (N1.getOpcode() == ISD::TRUNCATE) {
7623 // Look pass the truncate.
7624 Trunc = N1.getNode();
7625 N1 = N1.getOperand(0);
7628 // Match this pattern so that we can generate simpler code:
7631 // %b = and i32 %a, 2
7632 // %c = srl i32 %b, 1
7633 // brcond i32 %c ...
7638 // %b = and i32 %a, 2
7639 // %c = setcc eq %b, 0
7642 // This applies only when the AND constant value has one bit set and the
7643 // SRL constant is equal to the log2 of the AND constant. The back-end is
7644 // smart enough to convert the result into a TEST/JMP sequence.
7645 SDValue Op0 = N1.getOperand(0);
7646 SDValue Op1 = N1.getOperand(1);
7648 if (Op0.getOpcode() == ISD::AND &&
7649 Op1.getOpcode() == ISD::Constant) {
7650 SDValue AndOp1 = Op0.getOperand(1);
7652 if (AndOp1.getOpcode() == ISD::Constant) {
7653 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7655 if (AndConst.isPowerOf2() &&
7656 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7658 DAG.getSetCC(SDLoc(N),
7659 getSetCCResultType(Op0.getValueType()),
7660 Op0, DAG.getConstant(0, Op0.getValueType()),
7663 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7664 MVT::Other, Chain, SetCC, N2);
7665 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7666 // will convert it back to (X & C1) >> C2.
7667 CombineTo(N, NewBRCond, false);
7668 // Truncate is dead.
7670 deleteAndRecombine(Trunc);
7671 // Replace the uses of SRL with SETCC
7672 WorklistRemover DeadNodes(*this);
7673 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7674 deleteAndRecombine(N1.getNode());
7675 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7681 // Restore N1 if the above transformation doesn't match.
7682 N1 = N->getOperand(1);
7685 // Transform br(xor(x, y)) -> br(x != y)
7686 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7687 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7688 SDNode *TheXor = N1.getNode();
7689 SDValue Op0 = TheXor->getOperand(0);
7690 SDValue Op1 = TheXor->getOperand(1);
7691 if (Op0.getOpcode() == Op1.getOpcode()) {
7692 // Avoid missing important xor optimizations.
7693 SDValue Tmp = visitXOR(TheXor);
7694 if (Tmp.getNode()) {
7695 if (Tmp.getNode() != TheXor) {
7696 DEBUG(dbgs() << "\nReplacing.8 ";
7698 dbgs() << "\nWith: ";
7699 Tmp.getNode()->dump(&DAG);
7701 WorklistRemover DeadNodes(*this);
7702 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7703 deleteAndRecombine(TheXor);
7704 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7705 MVT::Other, Chain, Tmp, N2);
7708 // visitXOR has changed XOR's operands or replaced the XOR completely,
7710 return SDValue(N, 0);
7714 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7716 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7717 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7718 Op0.getOpcode() == ISD::XOR) {
7719 TheXor = Op0.getNode();
7723 EVT SetCCVT = N1.getValueType();
7725 SetCCVT = getSetCCResultType(SetCCVT);
7726 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7729 Equal ? ISD::SETEQ : ISD::SETNE);
7730 // Replace the uses of XOR with SETCC
7731 WorklistRemover DeadNodes(*this);
7732 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7733 deleteAndRecombine(N1.getNode());
7734 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7735 MVT::Other, Chain, SetCC, N2);
7742 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7744 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7745 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7746 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7748 // If N is a constant we could fold this into a fallthrough or unconditional
7749 // branch. However that doesn't happen very often in normal code, because
7750 // Instcombine/SimplifyCFG should have handled the available opportunities.
7751 // If we did this folding here, it would be necessary to update the
7752 // MachineBasicBlock CFG, which is awkward.
7754 // Use SimplifySetCC to simplify SETCC's.
7755 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7756 CondLHS, CondRHS, CC->get(), SDLoc(N),
7758 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7760 // fold to a simpler setcc
7761 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7762 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7763 N->getOperand(0), Simp.getOperand(2),
7764 Simp.getOperand(0), Simp.getOperand(1),
7770 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7771 /// and that N may be folded in the load / store addressing mode.
7772 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7774 const TargetLowering &TLI) {
7776 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7777 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7779 VT = Use->getValueType(0);
7780 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7781 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7783 VT = ST->getValue().getValueType();
7787 TargetLowering::AddrMode AM;
7788 if (N->getOpcode() == ISD::ADD) {
7789 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7792 AM.BaseOffs = Offset->getSExtValue();
7796 } else if (N->getOpcode() == ISD::SUB) {
7797 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7800 AM.BaseOffs = -Offset->getSExtValue();
7807 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7810 /// Try turning a load/store into a pre-indexed load/store when the base
7811 /// pointer is an add or subtract and it has other uses besides the load/store.
7812 /// After the transformation, the new indexed load/store has effectively folded
7813 /// the add/subtract in and all of its other uses are redirected to the
7815 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7816 if (Level < AfterLegalizeDAG)
7822 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7823 if (LD->isIndexed())
7825 VT = LD->getMemoryVT();
7826 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7827 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7829 Ptr = LD->getBasePtr();
7830 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7831 if (ST->isIndexed())
7833 VT = ST->getMemoryVT();
7834 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7835 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7837 Ptr = ST->getBasePtr();
7843 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7844 // out. There is no reason to make this a preinc/predec.
7845 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7846 Ptr.getNode()->hasOneUse())
7849 // Ask the target to do addressing mode selection.
7852 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7853 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7856 // Backends without true r+i pre-indexed forms may need to pass a
7857 // constant base with a variable offset so that constant coercion
7858 // will work with the patterns in canonical form.
7859 bool Swapped = false;
7860 if (isa<ConstantSDNode>(BasePtr)) {
7861 std::swap(BasePtr, Offset);
7865 // Don't create a indexed load / store with zero offset.
7866 if (isa<ConstantSDNode>(Offset) &&
7867 cast<ConstantSDNode>(Offset)->isNullValue())
7870 // Try turning it into a pre-indexed load / store except when:
7871 // 1) The new base ptr is a frame index.
7872 // 2) If N is a store and the new base ptr is either the same as or is a
7873 // predecessor of the value being stored.
7874 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7875 // that would create a cycle.
7876 // 4) All uses are load / store ops that use it as old base ptr.
7878 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7879 // (plus the implicit offset) to a register to preinc anyway.
7880 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7885 SDValue Val = cast<StoreSDNode>(N)->getValue();
7886 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7890 // If the offset is a constant, there may be other adds of constants that
7891 // can be folded with this one. We should do this to avoid having to keep
7892 // a copy of the original base pointer.
7893 SmallVector<SDNode *, 16> OtherUses;
7894 if (isa<ConstantSDNode>(Offset))
7895 for (SDNode *Use : BasePtr.getNode()->uses()) {
7896 if (Use == Ptr.getNode())
7899 if (Use->isPredecessorOf(N))
7902 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7907 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7908 if (Op1.getNode() == BasePtr.getNode())
7909 std::swap(Op0, Op1);
7910 assert(Op0.getNode() == BasePtr.getNode() &&
7911 "Use of ADD/SUB but not an operand");
7913 if (!isa<ConstantSDNode>(Op1)) {
7918 // FIXME: In some cases, we can be smarter about this.
7919 if (Op1.getValueType() != Offset.getValueType()) {
7924 OtherUses.push_back(Use);
7928 std::swap(BasePtr, Offset);
7930 // Now check for #3 and #4.
7931 bool RealUse = false;
7933 // Caches for hasPredecessorHelper
7934 SmallPtrSet<const SDNode *, 32> Visited;
7935 SmallVector<const SDNode *, 16> Worklist;
7937 for (SDNode *Use : Ptr.getNode()->uses()) {
7940 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7943 // If Ptr may be folded in addressing mode of other use, then it's
7944 // not profitable to do this transformation.
7945 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7954 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7955 BasePtr, Offset, AM);
7957 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7958 BasePtr, Offset, AM);
7961 DEBUG(dbgs() << "\nReplacing.4 ";
7963 dbgs() << "\nWith: ";
7964 Result.getNode()->dump(&DAG);
7966 WorklistRemover DeadNodes(*this);
7968 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7969 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7971 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7974 // Finally, since the node is now dead, remove it from the graph.
7975 deleteAndRecombine(N);
7978 std::swap(BasePtr, Offset);
7980 // Replace other uses of BasePtr that can be updated to use Ptr
7981 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7982 unsigned OffsetIdx = 1;
7983 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7985 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7986 BasePtr.getNode() && "Expected BasePtr operand");
7988 // We need to replace ptr0 in the following expression:
7989 // x0 * offset0 + y0 * ptr0 = t0
7991 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7993 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7994 // indexed load/store and the expresion that needs to be re-written.
7996 // Therefore, we have:
7997 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7999 ConstantSDNode *CN =
8000 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8002 APInt Offset0 = CN->getAPIntValue();
8003 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8005 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8006 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8007 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8008 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8010 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8012 APInt CNV = Offset0;
8013 if (X0 < 0) CNV = -CNV;
8014 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8015 else CNV = CNV - Offset1;
8017 // We can now generate the new expression.
8018 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8019 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8021 SDValue NewUse = DAG.getNode(Opcode,
8022 SDLoc(OtherUses[i]),
8023 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8024 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8025 deleteAndRecombine(OtherUses[i]);
8028 // Replace the uses of Ptr with uses of the updated base value.
8029 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8030 deleteAndRecombine(Ptr.getNode());
8035 /// Try to combine a load/store with a add/sub of the base pointer node into a
8036 /// post-indexed load/store. The transformation folded the add/subtract into the
8037 /// new indexed load/store effectively and all of its uses are redirected to the
8039 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8040 if (Level < AfterLegalizeDAG)
8046 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8047 if (LD->isIndexed())
8049 VT = LD->getMemoryVT();
8050 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8051 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8053 Ptr = LD->getBasePtr();
8054 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8055 if (ST->isIndexed())
8057 VT = ST->getMemoryVT();
8058 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8059 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8061 Ptr = ST->getBasePtr();
8067 if (Ptr.getNode()->hasOneUse())
8070 for (SDNode *Op : Ptr.getNode()->uses()) {
8072 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8077 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8078 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8079 // Don't create a indexed load / store with zero offset.
8080 if (isa<ConstantSDNode>(Offset) &&
8081 cast<ConstantSDNode>(Offset)->isNullValue())
8084 // Try turning it into a post-indexed load / store except when
8085 // 1) All uses are load / store ops that use it as base ptr (and
8086 // it may be folded as addressing mmode).
8087 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8088 // nor a successor of N. Otherwise, if Op is folded that would
8091 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8095 bool TryNext = false;
8096 for (SDNode *Use : BasePtr.getNode()->uses()) {
8097 if (Use == Ptr.getNode())
8100 // If all the uses are load / store addresses, then don't do the
8102 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8103 bool RealUse = false;
8104 for (SDNode *UseUse : Use->uses()) {
8105 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8120 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8121 SDValue Result = isLoad
8122 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8123 BasePtr, Offset, AM)
8124 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8125 BasePtr, Offset, AM);
8128 DEBUG(dbgs() << "\nReplacing.5 ";
8130 dbgs() << "\nWith: ";
8131 Result.getNode()->dump(&DAG);
8133 WorklistRemover DeadNodes(*this);
8135 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8136 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8138 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8141 // Finally, since the node is now dead, remove it from the graph.
8142 deleteAndRecombine(N);
8144 // Replace the uses of Use with uses of the updated base value.
8145 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8146 Result.getValue(isLoad ? 1 : 0));
8147 deleteAndRecombine(Op);
8156 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8157 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8158 ISD::MemIndexedMode AM = LD->getAddressingMode();
8159 assert(AM != ISD::UNINDEXED);
8160 SDValue BP = LD->getOperand(1);
8161 SDValue Inc = LD->getOperand(2);
8163 // Some backends use TargetConstants for load offsets, but don't expect
8164 // TargetConstants in general ADD nodes. We can convert these constants into
8165 // regular Constants (if the constant is not opaque).
8166 assert((Inc.getOpcode() != ISD::TargetConstant ||
8167 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8168 "Cannot split out indexing using opaque target constants");
8169 if (Inc.getOpcode() == ISD::TargetConstant) {
8170 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8171 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8172 ConstInc->getValueType(0));
8176 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8177 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8180 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8181 LoadSDNode *LD = cast<LoadSDNode>(N);
8182 SDValue Chain = LD->getChain();
8183 SDValue Ptr = LD->getBasePtr();
8185 // If load is not volatile and there are no uses of the loaded value (and
8186 // the updated indexed value in case of indexed loads), change uses of the
8187 // chain value into uses of the chain input (i.e. delete the dead load).
8188 if (!LD->isVolatile()) {
8189 if (N->getValueType(1) == MVT::Other) {
8191 if (!N->hasAnyUseOfValue(0)) {
8192 // It's not safe to use the two value CombineTo variant here. e.g.
8193 // v1, chain2 = load chain1, loc
8194 // v2, chain3 = load chain2, loc
8196 // Now we replace use of chain2 with chain1. This makes the second load
8197 // isomorphic to the one we are deleting, and thus makes this load live.
8198 DEBUG(dbgs() << "\nReplacing.6 ";
8200 dbgs() << "\nWith chain: ";
8201 Chain.getNode()->dump(&DAG);
8203 WorklistRemover DeadNodes(*this);
8204 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8207 deleteAndRecombine(N);
8209 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8213 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8215 // If this load has an opaque TargetConstant offset, then we cannot split
8216 // the indexing into an add/sub directly (that TargetConstant may not be
8217 // valid for a different type of node, and we cannot convert an opaque
8218 // target constant into a regular constant).
8219 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8220 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8222 if (!N->hasAnyUseOfValue(0) &&
8223 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8224 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8226 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8227 Index = SplitIndexingFromLoad(LD);
8228 // Try to fold the base pointer arithmetic into subsequent loads and
8230 AddUsersToWorklist(N);
8232 Index = DAG.getUNDEF(N->getValueType(1));
8233 DEBUG(dbgs() << "\nReplacing.7 ";
8235 dbgs() << "\nWith: ";
8236 Undef.getNode()->dump(&DAG);
8237 dbgs() << " and 2 other values\n");
8238 WorklistRemover DeadNodes(*this);
8239 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8240 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8241 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8242 deleteAndRecombine(N);
8243 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8248 // If this load is directly stored, replace the load value with the stored
8250 // TODO: Handle store large -> read small portion.
8251 // TODO: Handle TRUNCSTORE/LOADEXT
8252 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8253 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8254 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8255 if (PrevST->getBasePtr() == Ptr &&
8256 PrevST->getValue().getValueType() == N->getValueType(0))
8257 return CombineTo(N, Chain.getOperand(1), Chain);
8261 // Try to infer better alignment information than the load already has.
8262 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8263 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8264 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8266 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8267 LD->getValueType(0),
8268 Chain, Ptr, LD->getPointerInfo(),
8270 LD->isVolatile(), LD->isNonTemporal(),
8271 LD->isInvariant(), Align, LD->getAAInfo());
8272 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8277 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8278 : DAG.getSubtarget().useAA();
8280 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8281 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8284 if (UseAA && LD->isUnindexed()) {
8285 // Walk up chain skipping non-aliasing memory nodes.
8286 SDValue BetterChain = FindBetterChain(N, Chain);
8288 // If there is a better chain.
8289 if (Chain != BetterChain) {
8292 // Replace the chain to void dependency.
8293 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8294 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8295 BetterChain, Ptr, LD->getMemOperand());
8297 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8298 LD->getValueType(0),
8299 BetterChain, Ptr, LD->getMemoryVT(),
8300 LD->getMemOperand());
8303 // Create token factor to keep old chain connected.
8304 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8305 MVT::Other, Chain, ReplLoad.getValue(1));
8307 // Make sure the new and old chains are cleaned up.
8308 AddToWorklist(Token.getNode());
8310 // Replace uses with load result and token factor. Don't add users
8312 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8316 // Try transforming N to an indexed load.
8317 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8318 return SDValue(N, 0);
8320 // Try to slice up N to more direct loads if the slices are mapped to
8321 // different register banks or pairing can take place.
8323 return SDValue(N, 0);
8329 /// \brief Helper structure used to slice a load in smaller loads.
8330 /// Basically a slice is obtained from the following sequence:
8331 /// Origin = load Ty1, Base
8332 /// Shift = srl Ty1 Origin, CstTy Amount
8333 /// Inst = trunc Shift to Ty2
8335 /// Then, it will be rewriten into:
8336 /// Slice = load SliceTy, Base + SliceOffset
8337 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8339 /// SliceTy is deduced from the number of bits that are actually used to
8341 struct LoadedSlice {
8342 /// \brief Helper structure used to compute the cost of a slice.
8344 /// Are we optimizing for code size.
8349 unsigned CrossRegisterBanksCopies;
8353 Cost(bool ForCodeSize = false)
8354 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8355 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8357 /// \brief Get the cost of one isolated slice.
8358 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8359 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8360 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8361 EVT TruncType = LS.Inst->getValueType(0);
8362 EVT LoadedType = LS.getLoadedType();
8363 if (TruncType != LoadedType &&
8364 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8368 /// \brief Account for slicing gain in the current cost.
8369 /// Slicing provide a few gains like removing a shift or a
8370 /// truncate. This method allows to grow the cost of the original
8371 /// load with the gain from this slice.
8372 void addSliceGain(const LoadedSlice &LS) {
8373 // Each slice saves a truncate.
8374 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8375 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8376 LS.Inst->getOperand(0).getValueType()))
8378 // If there is a shift amount, this slice gets rid of it.
8381 // If this slice can merge a cross register bank copy, account for it.
8382 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8383 ++CrossRegisterBanksCopies;
8386 Cost &operator+=(const Cost &RHS) {
8388 Truncates += RHS.Truncates;
8389 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8395 bool operator==(const Cost &RHS) const {
8396 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8397 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8398 ZExts == RHS.ZExts && Shift == RHS.Shift;
8401 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8403 bool operator<(const Cost &RHS) const {
8404 // Assume cross register banks copies are as expensive as loads.
8405 // FIXME: Do we want some more target hooks?
8406 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8407 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8408 // Unless we are optimizing for code size, consider the
8409 // expensive operation first.
8410 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8411 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8412 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8413 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8416 bool operator>(const Cost &RHS) const { return RHS < *this; }
8418 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8420 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8422 // The last instruction that represent the slice. This should be a
8423 // truncate instruction.
8425 // The original load instruction.
8427 // The right shift amount in bits from the original load.
8429 // The DAG from which Origin came from.
8430 // This is used to get some contextual information about legal types, etc.
8433 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8434 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8435 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8437 LoadedSlice(const LoadedSlice &LS)
8438 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8440 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8441 /// \return Result is \p BitWidth and has used bits set to 1 and
8442 /// not used bits set to 0.
8443 APInt getUsedBits() const {
8444 // Reproduce the trunc(lshr) sequence:
8445 // - Start from the truncated value.
8446 // - Zero extend to the desired bit width.
8448 assert(Origin && "No original load to compare against.");
8449 unsigned BitWidth = Origin->getValueSizeInBits(0);
8450 assert(Inst && "This slice is not bound to an instruction");
8451 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8452 "Extracted slice is bigger than the whole type!");
8453 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8454 UsedBits.setAllBits();
8455 UsedBits = UsedBits.zext(BitWidth);
8460 /// \brief Get the size of the slice to be loaded in bytes.
8461 unsigned getLoadedSize() const {
8462 unsigned SliceSize = getUsedBits().countPopulation();
8463 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8464 return SliceSize / 8;
8467 /// \brief Get the type that will be loaded for this slice.
8468 /// Note: This may not be the final type for the slice.
8469 EVT getLoadedType() const {
8470 assert(DAG && "Missing context");
8471 LLVMContext &Ctxt = *DAG->getContext();
8472 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8475 /// \brief Get the alignment of the load used for this slice.
8476 unsigned getAlignment() const {
8477 unsigned Alignment = Origin->getAlignment();
8478 unsigned Offset = getOffsetFromBase();
8480 Alignment = MinAlign(Alignment, Alignment + Offset);
8484 /// \brief Check if this slice can be rewritten with legal operations.
8485 bool isLegal() const {
8486 // An invalid slice is not legal.
8487 if (!Origin || !Inst || !DAG)
8490 // Offsets are for indexed load only, we do not handle that.
8491 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8494 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8496 // Check that the type is legal.
8497 EVT SliceType = getLoadedType();
8498 if (!TLI.isTypeLegal(SliceType))
8501 // Check that the load is legal for this type.
8502 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8505 // Check that the offset can be computed.
8506 // 1. Check its type.
8507 EVT PtrType = Origin->getBasePtr().getValueType();
8508 if (PtrType == MVT::Untyped || PtrType.isExtended())
8511 // 2. Check that it fits in the immediate.
8512 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8515 // 3. Check that the computation is legal.
8516 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8519 // Check that the zext is legal if it needs one.
8520 EVT TruncateType = Inst->getValueType(0);
8521 if (TruncateType != SliceType &&
8522 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8528 /// \brief Get the offset in bytes of this slice in the original chunk of
8530 /// \pre DAG != nullptr.
8531 uint64_t getOffsetFromBase() const {
8532 assert(DAG && "Missing context.");
8534 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8535 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8536 uint64_t Offset = Shift / 8;
8537 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8538 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8539 "The size of the original loaded type is not a multiple of a"
8541 // If Offset is bigger than TySizeInBytes, it means we are loading all
8542 // zeros. This should have been optimized before in the process.
8543 assert(TySizeInBytes > Offset &&
8544 "Invalid shift amount for given loaded size");
8546 Offset = TySizeInBytes - Offset - getLoadedSize();
8550 /// \brief Generate the sequence of instructions to load the slice
8551 /// represented by this object and redirect the uses of this slice to
8552 /// this new sequence of instructions.
8553 /// \pre this->Inst && this->Origin are valid Instructions and this
8554 /// object passed the legal check: LoadedSlice::isLegal returned true.
8555 /// \return The last instruction of the sequence used to load the slice.
8556 SDValue loadSlice() const {
8557 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8558 const SDValue &OldBaseAddr = Origin->getBasePtr();
8559 SDValue BaseAddr = OldBaseAddr;
8560 // Get the offset in that chunk of bytes w.r.t. the endianess.
8561 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8562 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8564 // BaseAddr = BaseAddr + Offset.
8565 EVT ArithType = BaseAddr.getValueType();
8566 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8567 DAG->getConstant(Offset, ArithType));
8570 // Create the type of the loaded slice according to its size.
8571 EVT SliceType = getLoadedType();
8573 // Create the load for the slice.
8574 SDValue LastInst = DAG->getLoad(
8575 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8576 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8577 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8578 // If the final type is not the same as the loaded type, this means that
8579 // we have to pad with zero. Create a zero extend for that.
8580 EVT FinalType = Inst->getValueType(0);
8581 if (SliceType != FinalType)
8583 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8587 /// \brief Check if this slice can be merged with an expensive cross register
8588 /// bank copy. E.g.,
8590 /// f = bitcast i32 i to float
8591 bool canMergeExpensiveCrossRegisterBankCopy() const {
8592 if (!Inst || !Inst->hasOneUse())
8594 SDNode *Use = *Inst->use_begin();
8595 if (Use->getOpcode() != ISD::BITCAST)
8597 assert(DAG && "Missing context");
8598 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8599 EVT ResVT = Use->getValueType(0);
8600 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8601 const TargetRegisterClass *ArgRC =
8602 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8603 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8606 // At this point, we know that we perform a cross-register-bank copy.
8607 // Check if it is expensive.
8608 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8609 // Assume bitcasts are cheap, unless both register classes do not
8610 // explicitly share a common sub class.
8611 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8614 // Check if it will be merged with the load.
8615 // 1. Check the alignment constraint.
8616 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8617 ResVT.getTypeForEVT(*DAG->getContext()));
8619 if (RequiredAlignment > getAlignment())
8622 // 2. Check that the load is a legal operation for that type.
8623 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8626 // 3. Check that we do not have a zext in the way.
8627 if (Inst->getValueType(0) != getLoadedType())
8635 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8636 /// \p UsedBits looks like 0..0 1..1 0..0.
8637 static bool areUsedBitsDense(const APInt &UsedBits) {
8638 // If all the bits are one, this is dense!
8639 if (UsedBits.isAllOnesValue())
8642 // Get rid of the unused bits on the right.
8643 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8644 // Get rid of the unused bits on the left.
8645 if (NarrowedUsedBits.countLeadingZeros())
8646 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8647 // Check that the chunk of bits is completely used.
8648 return NarrowedUsedBits.isAllOnesValue();
8651 /// \brief Check whether or not \p First and \p Second are next to each other
8652 /// in memory. This means that there is no hole between the bits loaded
8653 /// by \p First and the bits loaded by \p Second.
8654 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8655 const LoadedSlice &Second) {
8656 assert(First.Origin == Second.Origin && First.Origin &&
8657 "Unable to match different memory origins.");
8658 APInt UsedBits = First.getUsedBits();
8659 assert((UsedBits & Second.getUsedBits()) == 0 &&
8660 "Slices are not supposed to overlap.");
8661 UsedBits |= Second.getUsedBits();
8662 return areUsedBitsDense(UsedBits);
8665 /// \brief Adjust the \p GlobalLSCost according to the target
8666 /// paring capabilities and the layout of the slices.
8667 /// \pre \p GlobalLSCost should account for at least as many loads as
8668 /// there is in the slices in \p LoadedSlices.
8669 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8670 LoadedSlice::Cost &GlobalLSCost) {
8671 unsigned NumberOfSlices = LoadedSlices.size();
8672 // If there is less than 2 elements, no pairing is possible.
8673 if (NumberOfSlices < 2)
8676 // Sort the slices so that elements that are likely to be next to each
8677 // other in memory are next to each other in the list.
8678 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8679 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8680 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8681 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8683 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8684 // First (resp. Second) is the first (resp. Second) potentially candidate
8685 // to be placed in a paired load.
8686 const LoadedSlice *First = nullptr;
8687 const LoadedSlice *Second = nullptr;
8688 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8689 // Set the beginning of the pair.
8692 Second = &LoadedSlices[CurrSlice];
8694 // If First is NULL, it means we start a new pair.
8695 // Get to the next slice.
8699 EVT LoadedType = First->getLoadedType();
8701 // If the types of the slices are different, we cannot pair them.
8702 if (LoadedType != Second->getLoadedType())
8705 // Check if the target supplies paired loads for this type.
8706 unsigned RequiredAlignment = 0;
8707 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8708 // move to the next pair, this type is hopeless.
8712 // Check if we meet the alignment requirement.
8713 if (RequiredAlignment > First->getAlignment())
8716 // Check that both loads are next to each other in memory.
8717 if (!areSlicesNextToEachOther(*First, *Second))
8720 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8721 --GlobalLSCost.Loads;
8722 // Move to the next pair.
8727 /// \brief Check the profitability of all involved LoadedSlice.
8728 /// Currently, it is considered profitable if there is exactly two
8729 /// involved slices (1) which are (2) next to each other in memory, and
8730 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8732 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8733 /// the elements themselves.
8735 /// FIXME: When the cost model will be mature enough, we can relax
8736 /// constraints (1) and (2).
8737 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8738 const APInt &UsedBits, bool ForCodeSize) {
8739 unsigned NumberOfSlices = LoadedSlices.size();
8740 if (StressLoadSlicing)
8741 return NumberOfSlices > 1;
8744 if (NumberOfSlices != 2)
8748 if (!areUsedBitsDense(UsedBits))
8752 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8753 // The original code has one big load.
8755 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8756 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8757 // Accumulate the cost of all the slices.
8758 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8759 GlobalSlicingCost += SliceCost;
8761 // Account as cost in the original configuration the gain obtained
8762 // with the current slices.
8763 OrigCost.addSliceGain(LS);
8766 // If the target supports paired load, adjust the cost accordingly.
8767 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8768 return OrigCost > GlobalSlicingCost;
8771 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8772 /// operations, split it in the various pieces being extracted.
8774 /// This sort of thing is introduced by SROA.
8775 /// This slicing takes care not to insert overlapping loads.
8776 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8777 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8778 if (Level < AfterLegalizeDAG)
8781 LoadSDNode *LD = cast<LoadSDNode>(N);
8782 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8783 !LD->getValueType(0).isInteger())
8786 // Keep track of already used bits to detect overlapping values.
8787 // In that case, we will just abort the transformation.
8788 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8790 SmallVector<LoadedSlice, 4> LoadedSlices;
8792 // Check if this load is used as several smaller chunks of bits.
8793 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8794 // of computation for each trunc.
8795 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8796 UI != UIEnd; ++UI) {
8797 // Skip the uses of the chain.
8798 if (UI.getUse().getResNo() != 0)
8804 // Check if this is a trunc(lshr).
8805 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8806 isa<ConstantSDNode>(User->getOperand(1))) {
8807 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8808 User = *User->use_begin();
8811 // At this point, User is a Truncate, iff we encountered, trunc or
8813 if (User->getOpcode() != ISD::TRUNCATE)
8816 // The width of the type must be a power of 2 and greater than 8-bits.
8817 // Otherwise the load cannot be represented in LLVM IR.
8818 // Moreover, if we shifted with a non-8-bits multiple, the slice
8819 // will be across several bytes. We do not support that.
8820 unsigned Width = User->getValueSizeInBits(0);
8821 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8824 // Build the slice for this chain of computations.
8825 LoadedSlice LS(User, LD, Shift, &DAG);
8826 APInt CurrentUsedBits = LS.getUsedBits();
8828 // Check if this slice overlaps with another.
8829 if ((CurrentUsedBits & UsedBits) != 0)
8831 // Update the bits used globally.
8832 UsedBits |= CurrentUsedBits;
8834 // Check if the new slice would be legal.
8838 // Record the slice.
8839 LoadedSlices.push_back(LS);
8842 // Abort slicing if it does not seem to be profitable.
8843 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8848 // Rewrite each chain to use an independent load.
8849 // By construction, each chain can be represented by a unique load.
8851 // Prepare the argument for the new token factor for all the slices.
8852 SmallVector<SDValue, 8> ArgChains;
8853 for (SmallVectorImpl<LoadedSlice>::const_iterator
8854 LSIt = LoadedSlices.begin(),
8855 LSItEnd = LoadedSlices.end();
8856 LSIt != LSItEnd; ++LSIt) {
8857 SDValue SliceInst = LSIt->loadSlice();
8858 CombineTo(LSIt->Inst, SliceInst, true);
8859 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8860 SliceInst = SliceInst.getOperand(0);
8861 assert(SliceInst->getOpcode() == ISD::LOAD &&
8862 "It takes more than a zext to get to the loaded slice!!");
8863 ArgChains.push_back(SliceInst.getValue(1));
8866 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8868 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8872 /// Check to see if V is (and load (ptr), imm), where the load is having
8873 /// specific bytes cleared out. If so, return the byte size being masked out
8874 /// and the shift amount.
8875 static std::pair<unsigned, unsigned>
8876 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8877 std::pair<unsigned, unsigned> Result(0, 0);
8879 // Check for the structure we're looking for.
8880 if (V->getOpcode() != ISD::AND ||
8881 !isa<ConstantSDNode>(V->getOperand(1)) ||
8882 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8885 // Check the chain and pointer.
8886 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8887 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8889 // The store should be chained directly to the load or be an operand of a
8891 if (LD == Chain.getNode())
8893 else if (Chain->getOpcode() != ISD::TokenFactor)
8894 return Result; // Fail.
8897 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8898 if (Chain->getOperand(i).getNode() == LD) {
8902 if (!isOk) return Result;
8905 // This only handles simple types.
8906 if (V.getValueType() != MVT::i16 &&
8907 V.getValueType() != MVT::i32 &&
8908 V.getValueType() != MVT::i64)
8911 // Check the constant mask. Invert it so that the bits being masked out are
8912 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8913 // follow the sign bit for uniformity.
8914 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8915 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8916 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8917 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8918 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8919 if (NotMaskLZ == 64) return Result; // All zero mask.
8921 // See if we have a continuous run of bits. If so, we have 0*1+0*
8922 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8925 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8926 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8927 NotMaskLZ -= 64-V.getValueSizeInBits();
8929 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8930 switch (MaskedBytes) {
8934 default: return Result; // All one mask, or 5-byte mask.
8937 // Verify that the first bit starts at a multiple of mask so that the access
8938 // is aligned the same as the access width.
8939 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8941 Result.first = MaskedBytes;
8942 Result.second = NotMaskTZ/8;
8947 /// Check to see if IVal is something that provides a value as specified by
8948 /// MaskInfo. If so, replace the specified store with a narrower store of
8951 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8952 SDValue IVal, StoreSDNode *St,
8954 unsigned NumBytes = MaskInfo.first;
8955 unsigned ByteShift = MaskInfo.second;
8956 SelectionDAG &DAG = DC->getDAG();
8958 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8959 // that uses this. If not, this is not a replacement.
8960 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8961 ByteShift*8, (ByteShift+NumBytes)*8);
8962 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8964 // Check that it is legal on the target to do this. It is legal if the new
8965 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8967 MVT VT = MVT::getIntegerVT(NumBytes*8);
8968 if (!DC->isTypeLegal(VT))
8971 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8972 // shifted by ByteShift and truncated down to NumBytes.
8974 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8975 DAG.getConstant(ByteShift*8,
8976 DC->getShiftAmountTy(IVal.getValueType())));
8978 // Figure out the offset for the store and the alignment of the access.
8980 unsigned NewAlign = St->getAlignment();
8982 if (DAG.getTargetLoweringInfo().isLittleEndian())
8983 StOffset = ByteShift;
8985 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8987 SDValue Ptr = St->getBasePtr();
8989 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8990 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8991 NewAlign = MinAlign(NewAlign, StOffset);
8994 // Truncate down to the new size.
8995 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8998 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8999 St->getPointerInfo().getWithOffset(StOffset),
9000 false, false, NewAlign).getNode();
9004 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9005 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9006 /// narrowing the load and store if it would end up being a win for performance
9008 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9009 StoreSDNode *ST = cast<StoreSDNode>(N);
9010 if (ST->isVolatile())
9013 SDValue Chain = ST->getChain();
9014 SDValue Value = ST->getValue();
9015 SDValue Ptr = ST->getBasePtr();
9016 EVT VT = Value.getValueType();
9018 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9021 unsigned Opc = Value.getOpcode();
9023 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9024 // is a byte mask indicating a consecutive number of bytes, check to see if
9025 // Y is known to provide just those bytes. If so, we try to replace the
9026 // load + replace + store sequence with a single (narrower) store, which makes
9028 if (Opc == ISD::OR) {
9029 std::pair<unsigned, unsigned> MaskedLoad;
9030 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9031 if (MaskedLoad.first)
9032 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9033 Value.getOperand(1), ST,this))
9034 return SDValue(NewST, 0);
9036 // Or is commutative, so try swapping X and Y.
9037 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9038 if (MaskedLoad.first)
9039 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9040 Value.getOperand(0), ST,this))
9041 return SDValue(NewST, 0);
9044 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9045 Value.getOperand(1).getOpcode() != ISD::Constant)
9048 SDValue N0 = Value.getOperand(0);
9049 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9050 Chain == SDValue(N0.getNode(), 1)) {
9051 LoadSDNode *LD = cast<LoadSDNode>(N0);
9052 if (LD->getBasePtr() != Ptr ||
9053 LD->getPointerInfo().getAddrSpace() !=
9054 ST->getPointerInfo().getAddrSpace())
9057 // Find the type to narrow it the load / op / store to.
9058 SDValue N1 = Value.getOperand(1);
9059 unsigned BitWidth = N1.getValueSizeInBits();
9060 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9061 if (Opc == ISD::AND)
9062 Imm ^= APInt::getAllOnesValue(BitWidth);
9063 if (Imm == 0 || Imm.isAllOnesValue())
9065 unsigned ShAmt = Imm.countTrailingZeros();
9066 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9067 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9068 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9069 while (NewBW < BitWidth &&
9070 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9071 TLI.isNarrowingProfitable(VT, NewVT))) {
9072 NewBW = NextPowerOf2(NewBW);
9073 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9075 if (NewBW >= BitWidth)
9078 // If the lsb changed does not start at the type bitwidth boundary,
9079 // start at the previous one.
9081 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9082 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9083 std::min(BitWidth, ShAmt + NewBW));
9084 if ((Imm & Mask) == Imm) {
9085 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9086 if (Opc == ISD::AND)
9087 NewImm ^= APInt::getAllOnesValue(NewBW);
9088 uint64_t PtrOff = ShAmt / 8;
9089 // For big endian targets, we need to adjust the offset to the pointer to
9090 // load the correct bytes.
9091 if (TLI.isBigEndian())
9092 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9094 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9095 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9096 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9099 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9100 Ptr.getValueType(), Ptr,
9101 DAG.getConstant(PtrOff, Ptr.getValueType()));
9102 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9103 LD->getChain(), NewPtr,
9104 LD->getPointerInfo().getWithOffset(PtrOff),
9105 LD->isVolatile(), LD->isNonTemporal(),
9106 LD->isInvariant(), NewAlign,
9108 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9109 DAG.getConstant(NewImm, NewVT));
9110 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9112 ST->getPointerInfo().getWithOffset(PtrOff),
9113 false, false, NewAlign);
9115 AddToWorklist(NewPtr.getNode());
9116 AddToWorklist(NewLD.getNode());
9117 AddToWorklist(NewVal.getNode());
9118 WorklistRemover DeadNodes(*this);
9119 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9128 /// For a given floating point load / store pair, if the load value isn't used
9129 /// by any other operations, then consider transforming the pair to integer
9130 /// load / store operations if the target deems the transformation profitable.
9131 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9132 StoreSDNode *ST = cast<StoreSDNode>(N);
9133 SDValue Chain = ST->getChain();
9134 SDValue Value = ST->getValue();
9135 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9136 Value.hasOneUse() &&
9137 Chain == SDValue(Value.getNode(), 1)) {
9138 LoadSDNode *LD = cast<LoadSDNode>(Value);
9139 EVT VT = LD->getMemoryVT();
9140 if (!VT.isFloatingPoint() ||
9141 VT != ST->getMemoryVT() ||
9142 LD->isNonTemporal() ||
9143 ST->isNonTemporal() ||
9144 LD->getPointerInfo().getAddrSpace() != 0 ||
9145 ST->getPointerInfo().getAddrSpace() != 0)
9148 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9149 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9150 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9151 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9152 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9155 unsigned LDAlign = LD->getAlignment();
9156 unsigned STAlign = ST->getAlignment();
9157 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9158 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9159 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9162 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9163 LD->getChain(), LD->getBasePtr(),
9164 LD->getPointerInfo(),
9165 false, false, false, LDAlign);
9167 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9168 NewLD, ST->getBasePtr(),
9169 ST->getPointerInfo(),
9170 false, false, STAlign);
9172 AddToWorklist(NewLD.getNode());
9173 AddToWorklist(NewST.getNode());
9174 WorklistRemover DeadNodes(*this);
9175 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9183 /// Helper struct to parse and store a memory address as base + index + offset.
9184 /// We ignore sign extensions when it is safe to do so.
9185 /// The following two expressions are not equivalent. To differentiate we need
9186 /// to store whether there was a sign extension involved in the index
9188 /// (load (i64 add (i64 copyfromreg %c)
9189 /// (i64 signextend (add (i8 load %index)
9193 /// (load (i64 add (i64 copyfromreg %c)
9194 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9196 struct BaseIndexOffset {
9200 bool IsIndexSignExt;
9202 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9204 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9205 bool IsIndexSignExt) :
9206 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9208 bool equalBaseIndex(const BaseIndexOffset &Other) {
9209 return Other.Base == Base && Other.Index == Index &&
9210 Other.IsIndexSignExt == IsIndexSignExt;
9213 /// Parses tree in Ptr for base, index, offset addresses.
9214 static BaseIndexOffset match(SDValue Ptr) {
9215 bool IsIndexSignExt = false;
9217 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9218 // instruction, then it could be just the BASE or everything else we don't
9219 // know how to handle. Just use Ptr as BASE and give up.
9220 if (Ptr->getOpcode() != ISD::ADD)
9221 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9223 // We know that we have at least an ADD instruction. Try to pattern match
9224 // the simple case of BASE + OFFSET.
9225 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9226 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9227 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9231 // Inside a loop the current BASE pointer is calculated using an ADD and a
9232 // MUL instruction. In this case Ptr is the actual BASE pointer.
9233 // (i64 add (i64 %array_ptr)
9234 // (i64 mul (i64 %induction_var)
9235 // (i64 %element_size)))
9236 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9237 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9239 // Look at Base + Index + Offset cases.
9240 SDValue Base = Ptr->getOperand(0);
9241 SDValue IndexOffset = Ptr->getOperand(1);
9243 // Skip signextends.
9244 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9245 IndexOffset = IndexOffset->getOperand(0);
9246 IsIndexSignExt = true;
9249 // Either the case of Base + Index (no offset) or something else.
9250 if (IndexOffset->getOpcode() != ISD::ADD)
9251 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9253 // Now we have the case of Base + Index + offset.
9254 SDValue Index = IndexOffset->getOperand(0);
9255 SDValue Offset = IndexOffset->getOperand(1);
9257 if (!isa<ConstantSDNode>(Offset))
9258 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9260 // Ignore signextends.
9261 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9262 Index = Index->getOperand(0);
9263 IsIndexSignExt = true;
9264 } else IsIndexSignExt = false;
9266 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9267 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9271 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9272 /// is located in a sequence of memory operations connected by a chain.
9274 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9275 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9276 // Ptr to the mem node.
9277 LSBaseSDNode *MemNode;
9278 // Offset from the base ptr.
9279 int64_t OffsetFromBase;
9280 // What is the sequence number of this mem node.
9281 // Lowest mem operand in the DAG starts at zero.
9282 unsigned SequenceNum;
9285 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9286 EVT MemVT = St->getMemoryVT();
9287 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9288 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9289 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9291 // Don't merge vectors into wider inputs.
9292 if (MemVT.isVector() || !MemVT.isSimple())
9295 // Perform an early exit check. Do not bother looking at stored values that
9296 // are not constants or loads.
9297 SDValue StoredVal = St->getValue();
9298 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9299 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9303 // Only look at ends of store sequences.
9304 SDValue Chain = SDValue(St, 0);
9305 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9308 // This holds the base pointer, index, and the offset in bytes from the base
9310 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9312 // We must have a base and an offset.
9313 if (!BasePtr.Base.getNode())
9316 // Do not handle stores to undef base pointers.
9317 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9320 // Save the LoadSDNodes that we find in the chain.
9321 // We need to make sure that these nodes do not interfere with
9322 // any of the store nodes.
9323 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9325 // Save the StoreSDNodes that we find in the chain.
9326 SmallVector<MemOpLink, 8> StoreNodes;
9328 // Walk up the chain and look for nodes with offsets from the same
9329 // base pointer. Stop when reaching an instruction with a different kind
9330 // or instruction which has a different base pointer.
9332 StoreSDNode *Index = St;
9334 // If the chain has more than one use, then we can't reorder the mem ops.
9335 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9338 // Find the base pointer and offset for this memory node.
9339 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9341 // Check that the base pointer is the same as the original one.
9342 if (!Ptr.equalBaseIndex(BasePtr))
9345 // Check that the alignment is the same.
9346 if (Index->getAlignment() != St->getAlignment())
9349 // The memory operands must not be volatile.
9350 if (Index->isVolatile() || Index->isIndexed())
9354 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9355 if (St->isTruncatingStore())
9358 // The stored memory type must be the same.
9359 if (Index->getMemoryVT() != MemVT)
9362 // We do not allow unaligned stores because we want to prevent overriding
9364 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9367 // We found a potential memory operand to merge.
9368 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9370 // Find the next memory operand in the chain. If the next operand in the
9371 // chain is a store then move up and continue the scan with the next
9372 // memory operand. If the next operand is a load save it and use alias
9373 // information to check if it interferes with anything.
9374 SDNode *NextInChain = Index->getChain().getNode();
9376 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9377 // We found a store node. Use it for the next iteration.
9380 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9381 if (Ldn->isVolatile()) {
9386 // Save the load node for later. Continue the scan.
9387 AliasLoadNodes.push_back(Ldn);
9388 NextInChain = Ldn->getChain().getNode();
9397 // Check if there is anything to merge.
9398 if (StoreNodes.size() < 2)
9401 // Sort the memory operands according to their distance from the base pointer.
9402 std::sort(StoreNodes.begin(), StoreNodes.end(),
9403 [](MemOpLink LHS, MemOpLink RHS) {
9404 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9405 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9406 LHS.SequenceNum > RHS.SequenceNum);
9409 // Scan the memory operations on the chain and find the first non-consecutive
9410 // store memory address.
9411 unsigned LastConsecutiveStore = 0;
9412 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9413 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9415 // Check that the addresses are consecutive starting from the second
9416 // element in the list of stores.
9418 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9419 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9424 // Check if this store interferes with any of the loads that we found.
9425 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9426 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9430 // We found a load that alias with this store. Stop the sequence.
9434 // Mark this node as useful.
9435 LastConsecutiveStore = i;
9438 // The node with the lowest store address.
9439 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9441 // Store the constants into memory as one consecutive store.
9443 unsigned LastLegalType = 0;
9444 unsigned LastLegalVectorType = 0;
9445 bool NonZero = false;
9446 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9447 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9448 SDValue StoredVal = St->getValue();
9450 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9451 NonZero |= !C->isNullValue();
9452 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9453 NonZero |= !C->getConstantFPValue()->isNullValue();
9459 // Find a legal type for the constant store.
9460 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9461 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9462 if (TLI.isTypeLegal(StoreTy))
9463 LastLegalType = i+1;
9464 // Or check whether a truncstore is legal.
9465 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9466 TargetLowering::TypePromoteInteger) {
9467 EVT LegalizedStoredValueTy =
9468 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9469 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9470 LastLegalType = i+1;
9473 // Find a legal type for the vector store.
9474 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9475 if (TLI.isTypeLegal(Ty))
9476 LastLegalVectorType = i + 1;
9479 // We only use vectors if the constant is known to be zero and the
9480 // function is not marked with the noimplicitfloat attribute.
9481 if (NonZero || NoVectors)
9482 LastLegalVectorType = 0;
9484 // Check if we found a legal integer type to store.
9485 if (LastLegalType == 0 && LastLegalVectorType == 0)
9488 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9489 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9491 // Make sure we have something to merge.
9495 unsigned EarliestNodeUsed = 0;
9496 for (unsigned i=0; i < NumElem; ++i) {
9497 // Find a chain for the new wide-store operand. Notice that some
9498 // of the store nodes that we found may not be selected for inclusion
9499 // in the wide store. The chain we use needs to be the chain of the
9500 // earliest store node which is *used* and replaced by the wide store.
9501 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9502 EarliestNodeUsed = i;
9505 // The earliest Node in the DAG.
9506 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9507 SDLoc DL(StoreNodes[0].MemNode);
9511 // Find a legal type for the vector store.
9512 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9513 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9514 StoredVal = DAG.getConstant(0, Ty);
9516 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9517 APInt StoreInt(StoreBW, 0);
9519 // Construct a single integer constant which is made of the smaller
9521 bool IsLE = TLI.isLittleEndian();
9522 for (unsigned i = 0; i < NumElem ; ++i) {
9523 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9524 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9525 SDValue Val = St->getValue();
9526 StoreInt<<=ElementSizeBytes*8;
9527 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9528 StoreInt|=C->getAPIntValue().zext(StoreBW);
9529 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9530 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9532 assert(false && "Invalid constant element type");
9536 // Create the new Load and Store operations.
9537 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9538 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9541 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9542 FirstInChain->getBasePtr(),
9543 FirstInChain->getPointerInfo(),
9545 FirstInChain->getAlignment());
9547 // Replace the first store with the new store
9548 CombineTo(EarliestOp, NewStore);
9549 // Erase all other stores.
9550 for (unsigned i = 0; i < NumElem ; ++i) {
9551 if (StoreNodes[i].MemNode == EarliestOp)
9553 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9554 // ReplaceAllUsesWith will replace all uses that existed when it was
9555 // called, but graph optimizations may cause new ones to appear. For
9556 // example, the case in pr14333 looks like
9558 // St's chain -> St -> another store -> X
9560 // And the only difference from St to the other store is the chain.
9561 // When we change it's chain to be St's chain they become identical,
9562 // get CSEed and the net result is that X is now a use of St.
9563 // Since we know that St is redundant, just iterate.
9564 while (!St->use_empty())
9565 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9566 deleteAndRecombine(St);
9572 // Below we handle the case of multiple consecutive stores that
9573 // come from multiple consecutive loads. We merge them into a single
9574 // wide load and a single wide store.
9576 // Look for load nodes which are used by the stored values.
9577 SmallVector<MemOpLink, 8> LoadNodes;
9579 // Find acceptable loads. Loads need to have the same chain (token factor),
9580 // must not be zext, volatile, indexed, and they must be consecutive.
9581 BaseIndexOffset LdBasePtr;
9582 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9583 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9584 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9587 // Loads must only have one use.
9588 if (!Ld->hasNUsesOfValue(1, 0))
9591 // Check that the alignment is the same as the stores.
9592 if (Ld->getAlignment() != St->getAlignment())
9595 // The memory operands must not be volatile.
9596 if (Ld->isVolatile() || Ld->isIndexed())
9599 // We do not accept ext loads.
9600 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9603 // The stored memory type must be the same.
9604 if (Ld->getMemoryVT() != MemVT)
9607 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9608 // If this is not the first ptr that we check.
9609 if (LdBasePtr.Base.getNode()) {
9610 // The base ptr must be the same.
9611 if (!LdPtr.equalBaseIndex(LdBasePtr))
9614 // Check that all other base pointers are the same as this one.
9618 // We found a potential memory operand to merge.
9619 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9622 if (LoadNodes.size() < 2)
9625 // If we have load/store pair instructions and we only have two values,
9627 unsigned RequiredAlignment;
9628 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9629 St->getAlignment() >= RequiredAlignment)
9632 // Scan the memory operations on the chain and find the first non-consecutive
9633 // load memory address. These variables hold the index in the store node
9635 unsigned LastConsecutiveLoad = 0;
9636 // This variable refers to the size and not index in the array.
9637 unsigned LastLegalVectorType = 0;
9638 unsigned LastLegalIntegerType = 0;
9639 StartAddress = LoadNodes[0].OffsetFromBase;
9640 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9641 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9642 // All loads much share the same chain.
9643 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9646 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9647 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9649 LastConsecutiveLoad = i;
9651 // Find a legal type for the vector store.
9652 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9653 if (TLI.isTypeLegal(StoreTy))
9654 LastLegalVectorType = i + 1;
9656 // Find a legal type for the integer store.
9657 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9658 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9659 if (TLI.isTypeLegal(StoreTy))
9660 LastLegalIntegerType = i + 1;
9661 // Or check whether a truncstore and extload is legal.
9662 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9663 TargetLowering::TypePromoteInteger) {
9664 EVT LegalizedStoredValueTy =
9665 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9666 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9667 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9668 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9669 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9670 LastLegalIntegerType = i+1;
9674 // Only use vector types if the vector type is larger than the integer type.
9675 // If they are the same, use integers.
9676 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9677 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9679 // We add +1 here because the LastXXX variables refer to location while
9680 // the NumElem refers to array/index size.
9681 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9682 NumElem = std::min(LastLegalType, NumElem);
9687 // The earliest Node in the DAG.
9688 unsigned EarliestNodeUsed = 0;
9689 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9690 for (unsigned i=1; i<NumElem; ++i) {
9691 // Find a chain for the new wide-store operand. Notice that some
9692 // of the store nodes that we found may not be selected for inclusion
9693 // in the wide store. The chain we use needs to be the chain of the
9694 // earliest store node which is *used* and replaced by the wide store.
9695 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9696 EarliestNodeUsed = i;
9699 // Find if it is better to use vectors or integers to load and store
9703 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9705 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9706 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9709 SDLoc LoadDL(LoadNodes[0].MemNode);
9710 SDLoc StoreDL(StoreNodes[0].MemNode);
9712 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9713 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9714 FirstLoad->getChain(),
9715 FirstLoad->getBasePtr(),
9716 FirstLoad->getPointerInfo(),
9717 false, false, false,
9718 FirstLoad->getAlignment());
9720 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9721 FirstInChain->getBasePtr(),
9722 FirstInChain->getPointerInfo(), false, false,
9723 FirstInChain->getAlignment());
9725 // Replace one of the loads with the new load.
9726 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9727 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9728 SDValue(NewLoad.getNode(), 1));
9730 // Remove the rest of the load chains.
9731 for (unsigned i = 1; i < NumElem ; ++i) {
9732 // Replace all chain users of the old load nodes with the chain of the new
9734 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9735 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9738 // Replace the first store with the new store.
9739 CombineTo(EarliestOp, NewStore);
9740 // Erase all other stores.
9741 for (unsigned i = 0; i < NumElem ; ++i) {
9742 // Remove all Store nodes.
9743 if (StoreNodes[i].MemNode == EarliestOp)
9745 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9746 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9747 deleteAndRecombine(St);
9753 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9754 StoreSDNode *ST = cast<StoreSDNode>(N);
9755 SDValue Chain = ST->getChain();
9756 SDValue Value = ST->getValue();
9757 SDValue Ptr = ST->getBasePtr();
9759 // If this is a store of a bit convert, store the input value if the
9760 // resultant store does not need a higher alignment than the original.
9761 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9762 ST->isUnindexed()) {
9763 unsigned OrigAlign = ST->getAlignment();
9764 EVT SVT = Value.getOperand(0).getValueType();
9765 unsigned Align = TLI.getDataLayout()->
9766 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9767 if (Align <= OrigAlign &&
9768 ((!LegalOperations && !ST->isVolatile()) ||
9769 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9770 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9771 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9772 ST->isNonTemporal(), OrigAlign,
9776 // Turn 'store undef, Ptr' -> nothing.
9777 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9780 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9781 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9782 // NOTE: If the original store is volatile, this transform must not increase
9783 // the number of stores. For example, on x86-32 an f64 can be stored in one
9784 // processor operation but an i64 (which is not legal) requires two. So the
9785 // transform should not be done in this case.
9786 if (Value.getOpcode() != ISD::TargetConstantFP) {
9788 switch (CFP->getSimpleValueType(0).SimpleTy) {
9789 default: llvm_unreachable("Unknown FP type");
9790 case MVT::f16: // We don't do this for these yet.
9796 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9797 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9798 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9799 bitcastToAPInt().getZExtValue(), MVT::i32);
9800 return DAG.getStore(Chain, SDLoc(N), Tmp,
9801 Ptr, ST->getMemOperand());
9805 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9806 !ST->isVolatile()) ||
9807 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9808 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9809 getZExtValue(), MVT::i64);
9810 return DAG.getStore(Chain, SDLoc(N), Tmp,
9811 Ptr, ST->getMemOperand());
9814 if (!ST->isVolatile() &&
9815 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9816 // Many FP stores are not made apparent until after legalize, e.g. for
9817 // argument passing. Since this is so common, custom legalize the
9818 // 64-bit integer store into two 32-bit stores.
9819 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9820 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9821 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9822 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9824 unsigned Alignment = ST->getAlignment();
9825 bool isVolatile = ST->isVolatile();
9826 bool isNonTemporal = ST->isNonTemporal();
9827 AAMDNodes AAInfo = ST->getAAInfo();
9829 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9830 Ptr, ST->getPointerInfo(),
9831 isVolatile, isNonTemporal,
9832 ST->getAlignment(), AAInfo);
9833 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9834 DAG.getConstant(4, Ptr.getValueType()));
9835 Alignment = MinAlign(Alignment, 4U);
9836 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9837 Ptr, ST->getPointerInfo().getWithOffset(4),
9838 isVolatile, isNonTemporal,
9840 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9849 // Try to infer better alignment information than the store already has.
9850 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9851 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9852 if (Align > ST->getAlignment())
9853 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9854 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9855 ST->isVolatile(), ST->isNonTemporal(), Align,
9860 // Try transforming a pair floating point load / store ops to integer
9861 // load / store ops.
9862 SDValue NewST = TransformFPLoadStorePair(N);
9863 if (NewST.getNode())
9866 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9867 : DAG.getSubtarget().useAA();
9869 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9870 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9873 if (UseAA && ST->isUnindexed()) {
9874 // Walk up chain skipping non-aliasing memory nodes.
9875 SDValue BetterChain = FindBetterChain(N, Chain);
9877 // If there is a better chain.
9878 if (Chain != BetterChain) {
9881 // Replace the chain to avoid dependency.
9882 if (ST->isTruncatingStore()) {
9883 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9884 ST->getMemoryVT(), ST->getMemOperand());
9886 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9887 ST->getMemOperand());
9890 // Create token to keep both nodes around.
9891 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9892 MVT::Other, Chain, ReplStore);
9894 // Make sure the new and old chains are cleaned up.
9895 AddToWorklist(Token.getNode());
9897 // Don't add users to work list.
9898 return CombineTo(N, Token, false);
9902 // Try transforming N to an indexed store.
9903 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9904 return SDValue(N, 0);
9906 // FIXME: is there such a thing as a truncating indexed store?
9907 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9908 Value.getValueType().isInteger()) {
9909 // See if we can simplify the input to this truncstore with knowledge that
9910 // only the low bits are being used. For example:
9911 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9913 GetDemandedBits(Value,
9914 APInt::getLowBitsSet(
9915 Value.getValueType().getScalarType().getSizeInBits(),
9916 ST->getMemoryVT().getScalarType().getSizeInBits()));
9917 AddToWorklist(Value.getNode());
9918 if (Shorter.getNode())
9919 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9920 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9922 // Otherwise, see if we can simplify the operation with
9923 // SimplifyDemandedBits, which only works if the value has a single use.
9924 if (SimplifyDemandedBits(Value,
9925 APInt::getLowBitsSet(
9926 Value.getValueType().getScalarType().getSizeInBits(),
9927 ST->getMemoryVT().getScalarType().getSizeInBits())))
9928 return SDValue(N, 0);
9931 // If this is a load followed by a store to the same location, then the store
9933 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9934 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9935 ST->isUnindexed() && !ST->isVolatile() &&
9936 // There can't be any side effects between the load and store, such as
9938 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9939 // The store is dead, remove it.
9944 // If this is a store followed by a store with the same value to the same
9945 // location, then the store is dead/noop.
9946 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9947 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9948 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9949 ST1->isUnindexed() && !ST1->isVolatile()) {
9950 // The store is dead, remove it.
9955 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9956 // truncating store. We can do this even if this is already a truncstore.
9957 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9958 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9959 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9960 ST->getMemoryVT())) {
9961 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9962 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9965 // Only perform this optimization before the types are legal, because we
9966 // don't want to perform this optimization on every DAGCombine invocation.
9968 bool EverChanged = false;
9971 // There can be multiple store sequences on the same chain.
9972 // Keep trying to merge store sequences until we are unable to do so
9973 // or until we merge the last store on the chain.
9974 bool Changed = MergeConsecutiveStores(ST);
9975 EverChanged |= Changed;
9976 if (!Changed) break;
9977 } while (ST->getOpcode() != ISD::DELETED_NODE);
9980 return SDValue(N, 0);
9983 return ReduceLoadOpStoreWidth(N);
9986 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9987 SDValue InVec = N->getOperand(0);
9988 SDValue InVal = N->getOperand(1);
9989 SDValue EltNo = N->getOperand(2);
9992 // If the inserted element is an UNDEF, just use the input vector.
9993 if (InVal.getOpcode() == ISD::UNDEF)
9996 EVT VT = InVec.getValueType();
9998 // If we can't generate a legal BUILD_VECTOR, exit
9999 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10002 // Check that we know which element is being inserted
10003 if (!isa<ConstantSDNode>(EltNo))
10005 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10007 // Canonicalize insert_vector_elt dag nodes.
10009 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10010 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10012 // Do this only if the child insert_vector node has one use; also
10013 // do this only if indices are both constants and Idx1 < Idx0.
10014 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10015 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10016 unsigned OtherElt =
10017 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10018 if (Elt < OtherElt) {
10020 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10021 InVec.getOperand(0), InVal, EltNo);
10022 AddToWorklist(NewOp.getNode());
10023 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10024 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10028 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10029 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10030 // vector elements.
10031 SmallVector<SDValue, 8> Ops;
10032 // Do not combine these two vectors if the output vector will not replace
10033 // the input vector.
10034 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10035 Ops.append(InVec.getNode()->op_begin(),
10036 InVec.getNode()->op_end());
10037 } else if (InVec.getOpcode() == ISD::UNDEF) {
10038 unsigned NElts = VT.getVectorNumElements();
10039 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10044 // Insert the element
10045 if (Elt < Ops.size()) {
10046 // All the operands of BUILD_VECTOR must have the same type;
10047 // we enforce that here.
10048 EVT OpVT = Ops[0].getValueType();
10049 if (InVal.getValueType() != OpVT)
10050 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10051 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10052 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10056 // Return the new vector
10057 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10060 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10061 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10062 EVT ResultVT = EVE->getValueType(0);
10063 EVT VecEltVT = InVecVT.getVectorElementType();
10064 unsigned Align = OriginalLoad->getAlignment();
10065 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10066 VecEltVT.getTypeForEVT(*DAG.getContext()));
10068 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10073 SDValue NewPtr = OriginalLoad->getBasePtr();
10075 EVT PtrType = NewPtr.getValueType();
10076 MachinePointerInfo MPI;
10077 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10078 int Elt = ConstEltNo->getZExtValue();
10079 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10080 if (TLI.isBigEndian())
10081 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10082 Offset = DAG.getConstant(PtrOff, PtrType);
10083 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10085 Offset = DAG.getNode(
10086 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10087 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10088 if (TLI.isBigEndian())
10089 Offset = DAG.getNode(
10090 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10091 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10092 MPI = OriginalLoad->getPointerInfo();
10094 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10096 // The replacement we need to do here is a little tricky: we need to
10097 // replace an extractelement of a load with a load.
10098 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10099 // Note that this replacement assumes that the extractvalue is the only
10100 // use of the load; that's okay because we don't want to perform this
10101 // transformation in other cases anyway.
10104 if (ResultVT.bitsGT(VecEltVT)) {
10105 // If the result type of vextract is wider than the load, then issue an
10106 // extending load instead.
10107 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10110 Load = DAG.getExtLoad(
10111 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10112 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10113 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10114 Chain = Load.getValue(1);
10116 Load = DAG.getLoad(
10117 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10118 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10119 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10120 Chain = Load.getValue(1);
10121 if (ResultVT.bitsLT(VecEltVT))
10122 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10124 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10126 WorklistRemover DeadNodes(*this);
10127 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10128 SDValue To[] = { Load, Chain };
10129 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10130 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10131 // worklist explicitly as well.
10132 AddToWorklist(Load.getNode());
10133 AddUsersToWorklist(Load.getNode()); // Add users too
10134 // Make sure to revisit this node to clean it up; it will usually be dead.
10135 AddToWorklist(EVE);
10137 return SDValue(EVE, 0);
10140 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10141 // (vextract (scalar_to_vector val, 0) -> val
10142 SDValue InVec = N->getOperand(0);
10143 EVT VT = InVec.getValueType();
10144 EVT NVT = N->getValueType(0);
10146 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10147 // Check if the result type doesn't match the inserted element type. A
10148 // SCALAR_TO_VECTOR may truncate the inserted element and the
10149 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10150 SDValue InOp = InVec.getOperand(0);
10151 if (InOp.getValueType() != NVT) {
10152 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10153 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10158 SDValue EltNo = N->getOperand(1);
10159 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10161 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10162 // We only perform this optimization before the op legalization phase because
10163 // we may introduce new vector instructions which are not backed by TD
10164 // patterns. For example on AVX, extracting elements from a wide vector
10165 // without using extract_subvector. However, if we can find an underlying
10166 // scalar value, then we can always use that.
10167 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10169 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10170 int NumElem = VT.getVectorNumElements();
10171 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10172 // Find the new index to extract from.
10173 int OrigElt = SVOp->getMaskElt(Elt);
10175 // Extracting an undef index is undef.
10177 return DAG.getUNDEF(NVT);
10179 // Select the right vector half to extract from.
10181 if (OrigElt < NumElem) {
10182 SVInVec = InVec->getOperand(0);
10184 SVInVec = InVec->getOperand(1);
10185 OrigElt -= NumElem;
10188 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10189 SDValue InOp = SVInVec.getOperand(OrigElt);
10190 if (InOp.getValueType() != NVT) {
10191 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10192 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10198 // FIXME: We should handle recursing on other vector shuffles and
10199 // scalar_to_vector here as well.
10201 if (!LegalOperations) {
10202 EVT IndexTy = TLI.getVectorIdxTy();
10203 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10204 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10208 bool BCNumEltsChanged = false;
10209 EVT ExtVT = VT.getVectorElementType();
10212 // If the result of load has to be truncated, then it's not necessarily
10214 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10217 if (InVec.getOpcode() == ISD::BITCAST) {
10218 // Don't duplicate a load with other uses.
10219 if (!InVec.hasOneUse())
10222 EVT BCVT = InVec.getOperand(0).getValueType();
10223 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10225 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10226 BCNumEltsChanged = true;
10227 InVec = InVec.getOperand(0);
10228 ExtVT = BCVT.getVectorElementType();
10231 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10232 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10233 ISD::isNormalLoad(InVec.getNode()) &&
10234 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10235 SDValue Index = N->getOperand(1);
10236 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10237 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10241 // Perform only after legalization to ensure build_vector / vector_shuffle
10242 // optimizations have already been done.
10243 if (!LegalOperations) return SDValue();
10245 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10246 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10247 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10250 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10252 LoadSDNode *LN0 = nullptr;
10253 const ShuffleVectorSDNode *SVN = nullptr;
10254 if (ISD::isNormalLoad(InVec.getNode())) {
10255 LN0 = cast<LoadSDNode>(InVec);
10256 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10257 InVec.getOperand(0).getValueType() == ExtVT &&
10258 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10259 // Don't duplicate a load with other uses.
10260 if (!InVec.hasOneUse())
10263 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10264 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10265 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10267 // (load $addr+1*size)
10269 // Don't duplicate a load with other uses.
10270 if (!InVec.hasOneUse())
10273 // If the bit convert changed the number of elements, it is unsafe
10274 // to examine the mask.
10275 if (BCNumEltsChanged)
10278 // Select the input vector, guarding against out of range extract vector.
10279 unsigned NumElems = VT.getVectorNumElements();
10280 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10281 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10283 if (InVec.getOpcode() == ISD::BITCAST) {
10284 // Don't duplicate a load with other uses.
10285 if (!InVec.hasOneUse())
10288 InVec = InVec.getOperand(0);
10290 if (ISD::isNormalLoad(InVec.getNode())) {
10291 LN0 = cast<LoadSDNode>(InVec);
10292 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10293 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10297 // Make sure we found a non-volatile load and the extractelement is
10299 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10302 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10304 return DAG.getUNDEF(LVT);
10306 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10312 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10313 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10314 // We perform this optimization post type-legalization because
10315 // the type-legalizer often scalarizes integer-promoted vectors.
10316 // Performing this optimization before may create bit-casts which
10317 // will be type-legalized to complex code sequences.
10318 // We perform this optimization only before the operation legalizer because we
10319 // may introduce illegal operations.
10320 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10323 unsigned NumInScalars = N->getNumOperands();
10325 EVT VT = N->getValueType(0);
10327 // Check to see if this is a BUILD_VECTOR of a bunch of values
10328 // which come from any_extend or zero_extend nodes. If so, we can create
10329 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10330 // optimizations. We do not handle sign-extend because we can't fill the sign
10332 EVT SourceType = MVT::Other;
10333 bool AllAnyExt = true;
10335 for (unsigned i = 0; i != NumInScalars; ++i) {
10336 SDValue In = N->getOperand(i);
10337 // Ignore undef inputs.
10338 if (In.getOpcode() == ISD::UNDEF) continue;
10340 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10341 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10343 // Abort if the element is not an extension.
10344 if (!ZeroExt && !AnyExt) {
10345 SourceType = MVT::Other;
10349 // The input is a ZeroExt or AnyExt. Check the original type.
10350 EVT InTy = In.getOperand(0).getValueType();
10352 // Check that all of the widened source types are the same.
10353 if (SourceType == MVT::Other)
10356 else if (InTy != SourceType) {
10357 // Multiple income types. Abort.
10358 SourceType = MVT::Other;
10362 // Check if all of the extends are ANY_EXTENDs.
10363 AllAnyExt &= AnyExt;
10366 // In order to have valid types, all of the inputs must be extended from the
10367 // same source type and all of the inputs must be any or zero extend.
10368 // Scalar sizes must be a power of two.
10369 EVT OutScalarTy = VT.getScalarType();
10370 bool ValidTypes = SourceType != MVT::Other &&
10371 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10372 isPowerOf2_32(SourceType.getSizeInBits());
10374 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10375 // turn into a single shuffle instruction.
10379 bool isLE = TLI.isLittleEndian();
10380 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10381 assert(ElemRatio > 1 && "Invalid element size ratio");
10382 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10383 DAG.getConstant(0, SourceType);
10385 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10386 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10388 // Populate the new build_vector
10389 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10390 SDValue Cast = N->getOperand(i);
10391 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10392 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10393 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10395 if (Cast.getOpcode() == ISD::UNDEF)
10396 In = DAG.getUNDEF(SourceType);
10398 In = Cast->getOperand(0);
10399 unsigned Index = isLE ? (i * ElemRatio) :
10400 (i * ElemRatio + (ElemRatio - 1));
10402 assert(Index < Ops.size() && "Invalid index");
10406 // The type of the new BUILD_VECTOR node.
10407 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10408 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10409 "Invalid vector size");
10410 // Check if the new vector type is legal.
10411 if (!isTypeLegal(VecVT)) return SDValue();
10413 // Make the new BUILD_VECTOR.
10414 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10416 // The new BUILD_VECTOR node has the potential to be further optimized.
10417 AddToWorklist(BV.getNode());
10418 // Bitcast to the desired type.
10419 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10422 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10423 EVT VT = N->getValueType(0);
10425 unsigned NumInScalars = N->getNumOperands();
10428 EVT SrcVT = MVT::Other;
10429 unsigned Opcode = ISD::DELETED_NODE;
10430 unsigned NumDefs = 0;
10432 for (unsigned i = 0; i != NumInScalars; ++i) {
10433 SDValue In = N->getOperand(i);
10434 unsigned Opc = In.getOpcode();
10436 if (Opc == ISD::UNDEF)
10439 // If all scalar values are floats and converted from integers.
10440 if (Opcode == ISD::DELETED_NODE &&
10441 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10448 EVT InVT = In.getOperand(0).getValueType();
10450 // If all scalar values are typed differently, bail out. It's chosen to
10451 // simplify BUILD_VECTOR of integer types.
10452 if (SrcVT == MVT::Other)
10459 // If the vector has just one element defined, it's not worth to fold it into
10460 // a vectorized one.
10464 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10465 && "Should only handle conversion from integer to float.");
10466 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10468 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10470 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10473 SmallVector<SDValue, 8> Opnds;
10474 for (unsigned i = 0; i != NumInScalars; ++i) {
10475 SDValue In = N->getOperand(i);
10477 if (In.getOpcode() == ISD::UNDEF)
10478 Opnds.push_back(DAG.getUNDEF(SrcVT));
10480 Opnds.push_back(In.getOperand(0));
10482 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10483 AddToWorklist(BV.getNode());
10485 return DAG.getNode(Opcode, dl, VT, BV);
10488 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10489 unsigned NumInScalars = N->getNumOperands();
10491 EVT VT = N->getValueType(0);
10493 // A vector built entirely of undefs is undef.
10494 if (ISD::allOperandsUndef(N))
10495 return DAG.getUNDEF(VT);
10497 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10501 V = reduceBuildVecConvertToConvertBuildVec(N);
10505 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10506 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10507 // at most two distinct vectors, turn this into a shuffle node.
10509 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10510 if (!isTypeLegal(VT))
10513 // May only combine to shuffle after legalize if shuffle is legal.
10514 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10517 SDValue VecIn1, VecIn2;
10518 for (unsigned i = 0; i != NumInScalars; ++i) {
10519 // Ignore undef inputs.
10520 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10522 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10523 // constant index, bail out.
10524 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10525 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10526 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10530 // We allow up to two distinct input vectors.
10531 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10532 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10535 if (!VecIn1.getNode()) {
10536 VecIn1 = ExtractedFromVec;
10537 } else if (!VecIn2.getNode()) {
10538 VecIn2 = ExtractedFromVec;
10540 // Too many inputs.
10541 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10546 // If everything is good, we can make a shuffle operation.
10547 if (VecIn1.getNode()) {
10548 SmallVector<int, 8> Mask;
10549 for (unsigned i = 0; i != NumInScalars; ++i) {
10550 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10551 Mask.push_back(-1);
10555 // If extracting from the first vector, just use the index directly.
10556 SDValue Extract = N->getOperand(i);
10557 SDValue ExtVal = Extract.getOperand(1);
10558 if (Extract.getOperand(0) == VecIn1) {
10559 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10560 if (ExtIndex > VT.getVectorNumElements())
10563 Mask.push_back(ExtIndex);
10567 // Otherwise, use InIdx + VecSize
10568 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10569 Mask.push_back(Idx+NumInScalars);
10572 // We can't generate a shuffle node with mismatched input and output types.
10573 // Attempt to transform a single input vector to the correct type.
10574 if ((VT != VecIn1.getValueType())) {
10575 // We don't support shuffeling between TWO values of different types.
10576 if (VecIn2.getNode())
10579 // We only support widening of vectors which are half the size of the
10580 // output registers. For example XMM->YMM widening on X86 with AVX.
10581 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10584 // If the input vector type has a different base type to the output
10585 // vector type, bail out.
10586 if (VecIn1.getValueType().getVectorElementType() !=
10587 VT.getVectorElementType())
10590 // Widen the input vector by adding undef values.
10591 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10592 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10595 // If VecIn2 is unused then change it to undef.
10596 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10598 // Check that we were able to transform all incoming values to the same
10600 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10601 VecIn1.getValueType() != VT)
10604 // Return the new VECTOR_SHUFFLE node.
10608 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10614 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10615 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10616 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10617 // inputs come from at most two distinct vectors, turn this into a shuffle
10620 // If we only have one input vector, we don't need to do any concatenation.
10621 if (N->getNumOperands() == 1)
10622 return N->getOperand(0);
10624 // Check if all of the operands are undefs.
10625 EVT VT = N->getValueType(0);
10626 if (ISD::allOperandsUndef(N))
10627 return DAG.getUNDEF(VT);
10629 // Optimize concat_vectors where one of the vectors is undef.
10630 if (N->getNumOperands() == 2 &&
10631 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10632 SDValue In = N->getOperand(0);
10633 assert(In.getValueType().isVector() && "Must concat vectors");
10635 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10636 if (In->getOpcode() == ISD::BITCAST &&
10637 !In->getOperand(0)->getValueType(0).isVector()) {
10638 SDValue Scalar = In->getOperand(0);
10639 EVT SclTy = Scalar->getValueType(0);
10641 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10644 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10645 VT.getSizeInBits() / SclTy.getSizeInBits());
10646 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10649 SDLoc dl = SDLoc(N);
10650 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10651 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10655 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10656 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10657 if (N->getNumOperands() == 2 &&
10658 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10659 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10660 EVT VT = N->getValueType(0);
10661 SDValue N0 = N->getOperand(0);
10662 SDValue N1 = N->getOperand(1);
10663 SmallVector<SDValue, 8> Opnds;
10664 unsigned BuildVecNumElts = N0.getNumOperands();
10666 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10667 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10668 if (SclTy0.isFloatingPoint()) {
10669 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10670 Opnds.push_back(N0.getOperand(i));
10671 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10672 Opnds.push_back(N1.getOperand(i));
10674 // If BUILD_VECTOR are from built from integer, they may have different
10675 // operand types. Get the smaller type and truncate all operands to it.
10676 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10677 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10678 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10679 N0.getOperand(i)));
10680 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10681 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10682 N1.getOperand(i)));
10685 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10688 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10689 // nodes often generate nop CONCAT_VECTOR nodes.
10690 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10691 // place the incoming vectors at the exact same location.
10692 SDValue SingleSource = SDValue();
10693 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10695 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10696 SDValue Op = N->getOperand(i);
10698 if (Op.getOpcode() == ISD::UNDEF)
10701 // Check if this is the identity extract:
10702 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10705 // Find the single incoming vector for the extract_subvector.
10706 if (SingleSource.getNode()) {
10707 if (Op.getOperand(0) != SingleSource)
10710 SingleSource = Op.getOperand(0);
10712 // Check the source type is the same as the type of the result.
10713 // If not, this concat may extend the vector, so we can not
10714 // optimize it away.
10715 if (SingleSource.getValueType() != N->getValueType(0))
10719 unsigned IdentityIndex = i * PartNumElem;
10720 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10721 // The extract index must be constant.
10725 // Check that we are reading from the identity index.
10726 if (CS->getZExtValue() != IdentityIndex)
10730 if (SingleSource.getNode())
10731 return SingleSource;
10736 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10737 EVT NVT = N->getValueType(0);
10738 SDValue V = N->getOperand(0);
10740 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10742 // (extract_subvec (concat V1, V2, ...), i)
10745 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10747 if (V->getOperand(0).getValueType() != NVT)
10749 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10750 unsigned NumElems = NVT.getVectorNumElements();
10751 assert((Idx % NumElems) == 0 &&
10752 "IDX in concat is not a multiple of the result vector length.");
10753 return V->getOperand(Idx / NumElems);
10757 if (V->getOpcode() == ISD::BITCAST)
10758 V = V.getOperand(0);
10760 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10762 // Handle only simple case where vector being inserted and vector
10763 // being extracted are of same type, and are half size of larger vectors.
10764 EVT BigVT = V->getOperand(0).getValueType();
10765 EVT SmallVT = V->getOperand(1).getValueType();
10766 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10769 // Only handle cases where both indexes are constants with the same type.
10770 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10771 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10773 if (InsIdx && ExtIdx &&
10774 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10775 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10777 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10779 // indices are equal or bit offsets are equal => V1
10780 // otherwise => (extract_subvec V1, ExtIdx)
10781 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10782 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10783 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10784 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10785 DAG.getNode(ISD::BITCAST, dl,
10786 N->getOperand(0).getValueType(),
10787 V->getOperand(0)), N->getOperand(1));
10794 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
10795 SDValue V, SelectionDAG &DAG) {
10797 EVT VT = V.getValueType();
10799 switch (V.getOpcode()) {
10803 case ISD::CONCAT_VECTORS: {
10804 EVT OpVT = V->getOperand(0).getValueType();
10805 int OpSize = OpVT.getVectorNumElements();
10806 SmallBitVector OpUsedElements(OpSize, false);
10807 bool FoundSimplification = false;
10808 SmallVector<SDValue, 4> NewOps;
10809 NewOps.reserve(V->getNumOperands());
10810 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
10811 SDValue Op = V->getOperand(i);
10812 bool OpUsed = false;
10813 for (int j = 0; j < OpSize; ++j)
10814 if (UsedElements[i * OpSize + j]) {
10815 OpUsedElements[j] = true;
10819 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
10820 : DAG.getUNDEF(OpVT));
10821 FoundSimplification |= Op == NewOps.back();
10822 OpUsedElements.reset();
10824 if (FoundSimplification)
10825 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
10829 case ISD::INSERT_SUBVECTOR: {
10830 SDValue BaseV = V->getOperand(0);
10831 SDValue SubV = V->getOperand(1);
10832 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
10836 int SubSize = SubV.getValueType().getVectorNumElements();
10837 int Idx = IdxN->getZExtValue();
10838 bool SubVectorUsed = false;
10839 SmallBitVector SubUsedElements(SubSize, false);
10840 for (int i = 0; i < SubSize; ++i)
10841 if (UsedElements[i + Idx]) {
10842 SubVectorUsed = true;
10843 SubUsedElements[i] = true;
10844 UsedElements[i + Idx] = false;
10847 // Now recurse on both the base and sub vectors.
10848 SDValue SimplifiedSubV =
10850 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
10851 : DAG.getUNDEF(SubV.getValueType());
10852 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
10853 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
10854 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
10855 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
10861 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
10862 SDValue N1, SelectionDAG &DAG) {
10863 EVT VT = SVN->getValueType(0);
10864 int NumElts = VT.getVectorNumElements();
10865 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
10866 for (int M : SVN->getMask())
10867 if (M >= 0 && M < NumElts)
10868 N0UsedElements[M] = true;
10869 else if (M >= NumElts)
10870 N1UsedElements[M - NumElts] = true;
10872 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
10873 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
10874 if (S0 == N0 && S1 == N1)
10877 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
10880 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10881 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10882 EVT VT = N->getValueType(0);
10883 unsigned NumElts = VT.getVectorNumElements();
10885 SDValue N0 = N->getOperand(0);
10886 SDValue N1 = N->getOperand(1);
10887 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10889 SmallVector<SDValue, 4> Ops;
10890 EVT ConcatVT = N0.getOperand(0).getValueType();
10891 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10892 unsigned NumConcats = NumElts / NumElemsPerConcat;
10894 // Look at every vector that's inserted. We're looking for exact
10895 // subvector-sized copies from a concatenated vector
10896 for (unsigned I = 0; I != NumConcats; ++I) {
10897 // Make sure we're dealing with a copy.
10898 unsigned Begin = I * NumElemsPerConcat;
10899 bool AllUndef = true, NoUndef = true;
10900 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10901 if (SVN->getMaskElt(J) >= 0)
10908 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10911 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10912 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10915 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10916 if (FirstElt < N0.getNumOperands())
10917 Ops.push_back(N0.getOperand(FirstElt));
10919 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10921 } else if (AllUndef) {
10922 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10923 } else { // Mixed with general masks and undefs, can't do optimization.
10928 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10931 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10932 EVT VT = N->getValueType(0);
10933 unsigned NumElts = VT.getVectorNumElements();
10935 SDValue N0 = N->getOperand(0);
10936 SDValue N1 = N->getOperand(1);
10938 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10940 // Canonicalize shuffle undef, undef -> undef
10941 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10942 return DAG.getUNDEF(VT);
10944 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10946 // Canonicalize shuffle v, v -> v, undef
10948 SmallVector<int, 8> NewMask;
10949 for (unsigned i = 0; i != NumElts; ++i) {
10950 int Idx = SVN->getMaskElt(i);
10951 if (Idx >= (int)NumElts) Idx -= NumElts;
10952 NewMask.push_back(Idx);
10954 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10958 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10959 if (N0.getOpcode() == ISD::UNDEF) {
10960 SmallVector<int, 8> NewMask;
10961 for (unsigned i = 0; i != NumElts; ++i) {
10962 int Idx = SVN->getMaskElt(i);
10964 if (Idx >= (int)NumElts)
10967 Idx = -1; // remove reference to lhs
10969 NewMask.push_back(Idx);
10971 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10975 // Remove references to rhs if it is undef
10976 if (N1.getOpcode() == ISD::UNDEF) {
10977 bool Changed = false;
10978 SmallVector<int, 8> NewMask;
10979 for (unsigned i = 0; i != NumElts; ++i) {
10980 int Idx = SVN->getMaskElt(i);
10981 if (Idx >= (int)NumElts) {
10985 NewMask.push_back(Idx);
10988 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10991 // If it is a splat, check if the argument vector is another splat or a
10992 // build_vector with all scalar elements the same.
10993 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10994 SDNode *V = N0.getNode();
10996 // If this is a bit convert that changes the element type of the vector but
10997 // not the number of vector elements, look through it. Be careful not to
10998 // look though conversions that change things like v4f32 to v2f64.
10999 if (V->getOpcode() == ISD::BITCAST) {
11000 SDValue ConvInput = V->getOperand(0);
11001 if (ConvInput.getValueType().isVector() &&
11002 ConvInput.getValueType().getVectorNumElements() == NumElts)
11003 V = ConvInput.getNode();
11006 if (V->getOpcode() == ISD::BUILD_VECTOR) {
11007 assert(V->getNumOperands() == NumElts &&
11008 "BUILD_VECTOR has wrong number of operands");
11010 bool AllSame = true;
11011 for (unsigned i = 0; i != NumElts; ++i) {
11012 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11013 Base = V->getOperand(i);
11017 // Splat of <u, u, u, u>, return <u, u, u, u>
11018 if (!Base.getNode())
11020 for (unsigned i = 0; i != NumElts; ++i) {
11021 if (V->getOperand(i) != Base) {
11026 // Splat of <x, x, x, x>, return <x, x, x, x>
11032 // There are various patterns used to build up a vector from smaller vectors,
11033 // subvectors, or elements. Scan chains of these and replace unused insertions
11034 // or components with undef.
11035 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11038 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11039 Level < AfterLegalizeVectorOps &&
11040 (N1.getOpcode() == ISD::UNDEF ||
11041 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11042 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11043 SDValue V = partitionShuffleOfConcats(N, DAG);
11049 // If this shuffle node is simply a swizzle of another shuffle node,
11050 // then try to simplify it.
11051 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11052 N1.getOpcode() == ISD::UNDEF) {
11054 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11056 // The incoming shuffle must be of the same type as the result of the
11057 // current shuffle.
11058 assert(OtherSV->getOperand(0).getValueType() == VT &&
11059 "Shuffle types don't match");
11061 SmallVector<int, 4> Mask;
11062 // Compute the combined shuffle mask.
11063 for (unsigned i = 0; i != NumElts; ++i) {
11064 int Idx = SVN->getMaskElt(i);
11065 assert(Idx < (int)NumElts && "Index references undef operand");
11066 // Next, this index comes from the first value, which is the incoming
11067 // shuffle. Adopt the incoming index.
11069 Idx = OtherSV->getMaskElt(Idx);
11070 Mask.push_back(Idx);
11073 // Check if all indices in Mask are Undef. In case, propagate Undef.
11074 bool isUndefMask = true;
11075 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11076 isUndefMask &= Mask[i] < 0;
11079 return DAG.getUNDEF(VT);
11081 bool CommuteOperands = false;
11082 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
11083 // To be valid, the combine shuffle mask should only reference elements
11084 // from one of the two vectors in input to the inner shufflevector.
11085 bool IsValidMask = true;
11086 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11087 // See if the combined mask only reference undefs or elements coming
11088 // from the first shufflevector operand.
11089 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
11091 if (!IsValidMask) {
11092 IsValidMask = true;
11093 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11094 // Check that all the elements come from the second shuffle operand.
11095 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
11096 CommuteOperands = IsValidMask;
11099 // Early exit if the combined shuffle mask is not valid.
11104 // See if this pair of shuffles can be safely folded according to either
11105 // of the following rules:
11106 // shuffle(shuffle(x, y), undef) -> x
11107 // shuffle(shuffle(x, undef), undef) -> x
11108 // shuffle(shuffle(x, y), undef) -> y
11109 bool IsIdentityMask = true;
11110 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
11111 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
11116 // The combined shuffle must map each index to itself.
11117 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
11120 if (IsIdentityMask) {
11121 if (CommuteOperands)
11122 // optimize shuffle(shuffle(x, y), undef) -> y.
11123 return OtherSV->getOperand(1);
11125 // optimize shuffle(shuffle(x, undef), undef) -> x
11126 // optimize shuffle(shuffle(x, y), undef) -> x
11127 return OtherSV->getOperand(0);
11130 // It may still be beneficial to combine the two shuffles if the
11131 // resulting shuffle is legal.
11132 if (TLI.isTypeLegal(VT)) {
11133 if (!CommuteOperands) {
11134 if (TLI.isShuffleMaskLegal(Mask, VT))
11135 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
11136 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
11137 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
11140 // Compute the commuted shuffle mask.
11141 for (unsigned i = 0; i != NumElts; ++i) {
11145 else if (idx < (int)NumElts)
11146 Mask[i] = idx + NumElts;
11148 Mask[i] = idx - NumElts;
11151 if (TLI.isShuffleMaskLegal(Mask, VT))
11152 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
11153 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
11159 // Canonicalize shuffles according to rules:
11160 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11161 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11162 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11163 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
11164 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11165 TLI.isTypeLegal(VT)) {
11166 // The incoming shuffle must be of the same type as the result of the
11167 // current shuffle.
11168 assert(N1->getOperand(0).getValueType() == VT &&
11169 "Shuffle types don't match");
11171 SDValue SV0 = N1->getOperand(0);
11172 SDValue SV1 = N1->getOperand(1);
11173 bool HasSameOp0 = N0 == SV0;
11174 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11175 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11176 // Commute the operands of this shuffle so that next rule
11178 return DAG.getCommutedVectorShuffle(*SVN);
11181 // Try to fold according to rules:
11182 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
11183 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
11184 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11185 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11186 // Don't try to fold shuffles with illegal type.
11187 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11188 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
11189 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11191 // The incoming shuffle must be of the same type as the result of the
11192 // current shuffle.
11193 assert(OtherSV->getOperand(0).getValueType() == VT &&
11194 "Shuffle types don't match");
11196 SDValue SV0 = OtherSV->getOperand(0);
11197 SDValue SV1 = OtherSV->getOperand(1);
11198 bool HasSameOp0 = N1 == SV0;
11199 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11200 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
11204 SmallVector<int, 4> Mask;
11205 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11206 // operand, and SV1 as the second operand.
11207 for (unsigned i = 0; i != NumElts; ++i) {
11208 int Idx = SVN->getMaskElt(i);
11210 // Propagate Undef.
11211 Mask.push_back(Idx);
11215 if (Idx < (int)NumElts) {
11216 Idx = OtherSV->getMaskElt(Idx);
11217 if (IsSV1Undef && Idx >= (int) NumElts)
11218 Idx = -1; // Propagate Undef.
11220 Idx = HasSameOp0 ? Idx - NumElts : Idx;
11222 Mask.push_back(Idx);
11225 // Check if all indices in Mask are Undef. In case, propagate Undef.
11226 bool isUndefMask = true;
11227 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11228 isUndefMask &= Mask[i] < 0;
11231 return DAG.getUNDEF(VT);
11233 // Avoid introducing shuffles with illegal mask.
11234 if (TLI.isShuffleMaskLegal(Mask, VT)) {
11236 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11237 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11238 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11239 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11246 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11247 SDValue N0 = N->getOperand(0);
11248 SDValue N2 = N->getOperand(2);
11250 // If the input vector is a concatenation, and the insert replaces
11251 // one of the halves, we can optimize into a single concat_vectors.
11252 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11253 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11254 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11255 EVT VT = N->getValueType(0);
11257 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11258 // (concat_vectors Z, Y)
11260 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11261 N->getOperand(1), N0.getOperand(1));
11263 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11264 // (concat_vectors X, Z)
11265 if (InsIdx == VT.getVectorNumElements()/2)
11266 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11267 N0.getOperand(0), N->getOperand(1));
11273 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11274 /// with the destination vector and a zero vector.
11275 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11276 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11277 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11278 EVT VT = N->getValueType(0);
11280 SDValue LHS = N->getOperand(0);
11281 SDValue RHS = N->getOperand(1);
11282 if (N->getOpcode() == ISD::AND) {
11283 if (RHS.getOpcode() == ISD::BITCAST)
11284 RHS = RHS.getOperand(0);
11285 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11286 SmallVector<int, 8> Indices;
11287 unsigned NumElts = RHS.getNumOperands();
11288 for (unsigned i = 0; i != NumElts; ++i) {
11289 SDValue Elt = RHS.getOperand(i);
11290 if (!isa<ConstantSDNode>(Elt))
11293 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11294 Indices.push_back(i);
11295 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11296 Indices.push_back(NumElts);
11301 // Let's see if the target supports this vector_shuffle.
11302 EVT RVT = RHS.getValueType();
11303 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11306 // Return the new VECTOR_SHUFFLE node.
11307 EVT EltVT = RVT.getVectorElementType();
11308 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11309 DAG.getConstant(0, EltVT));
11310 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11311 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11312 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11313 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11320 /// Visit a binary vector operation, like ADD.
11321 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11322 assert(N->getValueType(0).isVector() &&
11323 "SimplifyVBinOp only works on vectors!");
11325 SDValue LHS = N->getOperand(0);
11326 SDValue RHS = N->getOperand(1);
11327 SDValue Shuffle = XformToShuffleWithZero(N);
11328 if (Shuffle.getNode()) return Shuffle;
11330 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11332 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11333 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11334 // Check if both vectors are constants. If not bail out.
11335 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11336 cast<BuildVectorSDNode>(RHS)->isConstant()))
11339 SmallVector<SDValue, 8> Ops;
11340 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11341 SDValue LHSOp = LHS.getOperand(i);
11342 SDValue RHSOp = RHS.getOperand(i);
11344 // Can't fold divide by zero.
11345 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11346 N->getOpcode() == ISD::FDIV) {
11347 if ((RHSOp.getOpcode() == ISD::Constant &&
11348 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11349 (RHSOp.getOpcode() == ISD::ConstantFP &&
11350 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11354 EVT VT = LHSOp.getValueType();
11355 EVT RVT = RHSOp.getValueType();
11357 // Integer BUILD_VECTOR operands may have types larger than the element
11358 // size (e.g., when the element type is not legal). Prior to type
11359 // legalization, the types may not match between the two BUILD_VECTORS.
11360 // Truncate one of the operands to make them match.
11361 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11362 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11364 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11368 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11370 if (FoldOp.getOpcode() != ISD::UNDEF &&
11371 FoldOp.getOpcode() != ISD::Constant &&
11372 FoldOp.getOpcode() != ISD::ConstantFP)
11374 Ops.push_back(FoldOp);
11375 AddToWorklist(FoldOp.getNode());
11378 if (Ops.size() == LHS.getNumOperands())
11379 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11382 // Type legalization might introduce new shuffles in the DAG.
11383 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11384 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11385 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11386 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11387 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11388 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11389 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11390 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11392 if (SVN0->getMask().equals(SVN1->getMask())) {
11393 EVT VT = N->getValueType(0);
11394 SDValue UndefVector = LHS.getOperand(1);
11395 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11396 LHS.getOperand(0), RHS.getOperand(0));
11397 AddUsersToWorklist(N);
11398 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11399 &SVN0->getMask()[0]);
11406 /// Visit a binary vector operation, like FABS/FNEG.
11407 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11408 assert(N->getValueType(0).isVector() &&
11409 "SimplifyVUnaryOp only works on vectors!");
11411 SDValue N0 = N->getOperand(0);
11413 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11416 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11417 SmallVector<SDValue, 8> Ops;
11418 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11419 SDValue Op = N0.getOperand(i);
11420 if (Op.getOpcode() != ISD::UNDEF &&
11421 Op.getOpcode() != ISD::ConstantFP)
11423 EVT EltVT = Op.getValueType();
11424 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11425 if (FoldOp.getOpcode() != ISD::UNDEF &&
11426 FoldOp.getOpcode() != ISD::ConstantFP)
11428 Ops.push_back(FoldOp);
11429 AddToWorklist(FoldOp.getNode());
11432 if (Ops.size() != N0.getNumOperands())
11435 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11438 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11439 SDValue N1, SDValue N2){
11440 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11442 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11443 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11445 // If we got a simplified select_cc node back from SimplifySelectCC, then
11446 // break it down into a new SETCC node, and a new SELECT node, and then return
11447 // the SELECT node, since we were called with a SELECT node.
11448 if (SCC.getNode()) {
11449 // Check to see if we got a select_cc back (to turn into setcc/select).
11450 // Otherwise, just return whatever node we got back, like fabs.
11451 if (SCC.getOpcode() == ISD::SELECT_CC) {
11452 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11454 SCC.getOperand(0), SCC.getOperand(1),
11455 SCC.getOperand(4));
11456 AddToWorklist(SETCC.getNode());
11457 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11458 SCC.getOperand(2), SCC.getOperand(3));
11466 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11467 /// being selected between, see if we can simplify the select. Callers of this
11468 /// should assume that TheSelect is deleted if this returns true. As such, they
11469 /// should return the appropriate thing (e.g. the node) back to the top-level of
11470 /// the DAG combiner loop to avoid it being looked at.
11471 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11474 // Cannot simplify select with vector condition
11475 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11477 // If this is a select from two identical things, try to pull the operation
11478 // through the select.
11479 if (LHS.getOpcode() != RHS.getOpcode() ||
11480 !LHS.hasOneUse() || !RHS.hasOneUse())
11483 // If this is a load and the token chain is identical, replace the select
11484 // of two loads with a load through a select of the address to load from.
11485 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11486 // constants have been dropped into the constant pool.
11487 if (LHS.getOpcode() == ISD::LOAD) {
11488 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11489 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11491 // Token chains must be identical.
11492 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11493 // Do not let this transformation reduce the number of volatile loads.
11494 LLD->isVolatile() || RLD->isVolatile() ||
11495 // If this is an EXTLOAD, the VT's must match.
11496 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11497 // If this is an EXTLOAD, the kind of extension must match.
11498 (LLD->getExtensionType() != RLD->getExtensionType() &&
11499 // The only exception is if one of the extensions is anyext.
11500 LLD->getExtensionType() != ISD::EXTLOAD &&
11501 RLD->getExtensionType() != ISD::EXTLOAD) ||
11502 // FIXME: this discards src value information. This is
11503 // over-conservative. It would be beneficial to be able to remember
11504 // both potential memory locations. Since we are discarding
11505 // src value info, don't do the transformation if the memory
11506 // locations are not in the default address space.
11507 LLD->getPointerInfo().getAddrSpace() != 0 ||
11508 RLD->getPointerInfo().getAddrSpace() != 0 ||
11509 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11510 LLD->getBasePtr().getValueType()))
11513 // Check that the select condition doesn't reach either load. If so,
11514 // folding this will induce a cycle into the DAG. If not, this is safe to
11515 // xform, so create a select of the addresses.
11517 if (TheSelect->getOpcode() == ISD::SELECT) {
11518 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11519 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11520 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11522 // The loads must not depend on one another.
11523 if (LLD->isPredecessorOf(RLD) ||
11524 RLD->isPredecessorOf(LLD))
11526 Addr = DAG.getSelect(SDLoc(TheSelect),
11527 LLD->getBasePtr().getValueType(),
11528 TheSelect->getOperand(0), LLD->getBasePtr(),
11529 RLD->getBasePtr());
11530 } else { // Otherwise SELECT_CC
11531 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11532 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11534 if ((LLD->hasAnyUseOfValue(1) &&
11535 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11536 (RLD->hasAnyUseOfValue(1) &&
11537 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11540 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11541 LLD->getBasePtr().getValueType(),
11542 TheSelect->getOperand(0),
11543 TheSelect->getOperand(1),
11544 LLD->getBasePtr(), RLD->getBasePtr(),
11545 TheSelect->getOperand(4));
11549 // It is safe to replace the two loads if they have different alignments,
11550 // but the new load must be the minimum (most restrictive) alignment of the
11552 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11553 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11554 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11555 Load = DAG.getLoad(TheSelect->getValueType(0),
11557 // FIXME: Discards pointer and AA info.
11558 LLD->getChain(), Addr, MachinePointerInfo(),
11559 LLD->isVolatile(), LLD->isNonTemporal(),
11560 isInvariant, Alignment);
11562 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11563 RLD->getExtensionType() : LLD->getExtensionType(),
11565 TheSelect->getValueType(0),
11566 // FIXME: Discards pointer and AA info.
11567 LLD->getChain(), Addr, MachinePointerInfo(),
11568 LLD->getMemoryVT(), LLD->isVolatile(),
11569 LLD->isNonTemporal(), isInvariant, Alignment);
11572 // Users of the select now use the result of the load.
11573 CombineTo(TheSelect, Load);
11575 // Users of the old loads now use the new load's chain. We know the
11576 // old-load value is dead now.
11577 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11578 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11585 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11586 /// where 'cond' is the comparison specified by CC.
11587 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11588 SDValue N2, SDValue N3,
11589 ISD::CondCode CC, bool NotExtCompare) {
11590 // (x ? y : y) -> y.
11591 if (N2 == N3) return N2;
11593 EVT VT = N2.getValueType();
11594 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11595 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11596 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11598 // Determine if the condition we're dealing with is constant
11599 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11600 N0, N1, CC, DL, false);
11601 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11602 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11604 // fold select_cc true, x, y -> x
11605 if (SCCC && !SCCC->isNullValue())
11607 // fold select_cc false, x, y -> y
11608 if (SCCC && SCCC->isNullValue())
11611 // Check to see if we can simplify the select into an fabs node
11612 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11613 // Allow either -0.0 or 0.0
11614 if (CFP->getValueAPF().isZero()) {
11615 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11616 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11617 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11618 N2 == N3.getOperand(0))
11619 return DAG.getNode(ISD::FABS, DL, VT, N0);
11621 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11622 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11623 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11624 N2.getOperand(0) == N3)
11625 return DAG.getNode(ISD::FABS, DL, VT, N3);
11629 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11630 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11631 // in it. This is a win when the constant is not otherwise available because
11632 // it replaces two constant pool loads with one. We only do this if the FP
11633 // type is known to be legal, because if it isn't, then we are before legalize
11634 // types an we want the other legalization to happen first (e.g. to avoid
11635 // messing with soft float) and if the ConstantFP is not legal, because if
11636 // it is legal, we may not need to store the FP constant in a constant pool.
11637 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11638 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11639 if (TLI.isTypeLegal(N2.getValueType()) &&
11640 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11641 TargetLowering::Legal &&
11642 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11643 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11644 // If both constants have multiple uses, then we won't need to do an
11645 // extra load, they are likely around in registers for other users.
11646 (TV->hasOneUse() || FV->hasOneUse())) {
11647 Constant *Elts[] = {
11648 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11649 const_cast<ConstantFP*>(TV->getConstantFPValue())
11651 Type *FPTy = Elts[0]->getType();
11652 const DataLayout &TD = *TLI.getDataLayout();
11654 // Create a ConstantArray of the two constants.
11655 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11656 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11657 TD.getPrefTypeAlignment(FPTy));
11658 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11660 // Get the offsets to the 0 and 1 element of the array so that we can
11661 // select between them.
11662 SDValue Zero = DAG.getIntPtrConstant(0);
11663 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11664 SDValue One = DAG.getIntPtrConstant(EltSize);
11666 SDValue Cond = DAG.getSetCC(DL,
11667 getSetCCResultType(N0.getValueType()),
11669 AddToWorklist(Cond.getNode());
11670 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11672 AddToWorklist(CstOffset.getNode());
11673 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11675 AddToWorklist(CPIdx.getNode());
11676 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11677 MachinePointerInfo::getConstantPool(), false,
11678 false, false, Alignment);
11683 // Check to see if we can perform the "gzip trick", transforming
11684 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11685 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11686 (N1C->isNullValue() || // (a < 0) ? b : 0
11687 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11688 EVT XType = N0.getValueType();
11689 EVT AType = N2.getValueType();
11690 if (XType.bitsGE(AType)) {
11691 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11692 // single-bit constant.
11693 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11694 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11695 ShCtV = XType.getSizeInBits()-ShCtV-1;
11696 SDValue ShCt = DAG.getConstant(ShCtV,
11697 getShiftAmountTy(N0.getValueType()));
11698 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11700 AddToWorklist(Shift.getNode());
11702 if (XType.bitsGT(AType)) {
11703 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11704 AddToWorklist(Shift.getNode());
11707 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11710 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11712 DAG.getConstant(XType.getSizeInBits()-1,
11713 getShiftAmountTy(N0.getValueType())));
11714 AddToWorklist(Shift.getNode());
11716 if (XType.bitsGT(AType)) {
11717 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11718 AddToWorklist(Shift.getNode());
11721 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11725 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11726 // where y is has a single bit set.
11727 // A plaintext description would be, we can turn the SELECT_CC into an AND
11728 // when the condition can be materialized as an all-ones register. Any
11729 // single bit-test can be materialized as an all-ones register with
11730 // shift-left and shift-right-arith.
11731 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11732 N0->getValueType(0) == VT &&
11733 N1C && N1C->isNullValue() &&
11734 N2C && N2C->isNullValue()) {
11735 SDValue AndLHS = N0->getOperand(0);
11736 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11737 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11738 // Shift the tested bit over the sign bit.
11739 APInt AndMask = ConstAndRHS->getAPIntValue();
11741 DAG.getConstant(AndMask.countLeadingZeros(),
11742 getShiftAmountTy(AndLHS.getValueType()));
11743 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11745 // Now arithmetic right shift it all the way over, so the result is either
11746 // all-ones, or zero.
11748 DAG.getConstant(AndMask.getBitWidth()-1,
11749 getShiftAmountTy(Shl.getValueType()));
11750 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11752 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11756 // fold select C, 16, 0 -> shl C, 4
11757 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11758 TLI.getBooleanContents(N0.getValueType()) ==
11759 TargetLowering::ZeroOrOneBooleanContent) {
11761 // If the caller doesn't want us to simplify this into a zext of a compare,
11763 if (NotExtCompare && N2C->getAPIntValue() == 1)
11766 // Get a SetCC of the condition
11767 // NOTE: Don't create a SETCC if it's not legal on this target.
11768 if (!LegalOperations ||
11769 TLI.isOperationLegal(ISD::SETCC,
11770 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11772 // cast from setcc result type to select result type
11774 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11776 if (N2.getValueType().bitsLT(SCC.getValueType()))
11777 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11778 N2.getValueType());
11780 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11781 N2.getValueType(), SCC);
11783 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11784 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11785 N2.getValueType(), SCC);
11788 AddToWorklist(SCC.getNode());
11789 AddToWorklist(Temp.getNode());
11791 if (N2C->getAPIntValue() == 1)
11794 // shl setcc result by log2 n2c
11795 return DAG.getNode(
11796 ISD::SHL, DL, N2.getValueType(), Temp,
11797 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11798 getShiftAmountTy(Temp.getValueType())));
11802 // Check to see if this is the equivalent of setcc
11803 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11804 // otherwise, go ahead with the folds.
11805 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11806 EVT XType = N0.getValueType();
11807 if (!LegalOperations ||
11808 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11809 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11810 if (Res.getValueType() != VT)
11811 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11815 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11816 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11817 (!LegalOperations ||
11818 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11819 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11820 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11821 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11822 getShiftAmountTy(Ctlz.getValueType())));
11824 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11825 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11826 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11827 XType, DAG.getConstant(0, XType), N0);
11828 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11829 return DAG.getNode(ISD::SRL, DL, XType,
11830 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11831 DAG.getConstant(XType.getSizeInBits()-1,
11832 getShiftAmountTy(XType)));
11834 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11835 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11836 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11837 DAG.getConstant(XType.getSizeInBits()-1,
11838 getShiftAmountTy(N0.getValueType())));
11839 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11843 // Check to see if this is an integer abs.
11844 // select_cc setg[te] X, 0, X, -X ->
11845 // select_cc setgt X, -1, X, -X ->
11846 // select_cc setl[te] X, 0, -X, X ->
11847 // select_cc setlt X, 1, -X, X ->
11848 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11850 ConstantSDNode *SubC = nullptr;
11851 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11852 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11853 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11854 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11855 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11856 (N1C->isOne() && CC == ISD::SETLT)) &&
11857 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11858 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11860 EVT XType = N0.getValueType();
11861 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11862 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11864 DAG.getConstant(XType.getSizeInBits()-1,
11865 getShiftAmountTy(N0.getValueType())));
11866 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11868 AddToWorklist(Shift.getNode());
11869 AddToWorklist(Add.getNode());
11870 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11877 /// This is a stub for TargetLowering::SimplifySetCC.
11878 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11879 SDValue N1, ISD::CondCode Cond,
11880 SDLoc DL, bool foldBooleans) {
11881 TargetLowering::DAGCombinerInfo
11882 DagCombineInfo(DAG, Level, false, this);
11883 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11886 /// Given an ISD::SDIV node expressing a divide by constant, return
11887 /// a DAG expression to select that will generate the same value by multiplying
11888 /// by a magic number.
11889 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11890 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11891 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11895 // Avoid division by zero.
11896 if (!C->getAPIntValue())
11899 std::vector<SDNode*> Built;
11901 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11903 for (SDNode *N : Built)
11908 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11909 /// DAG expression that will generate the same value by right shifting.
11910 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11911 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11915 // Avoid division by zero.
11916 if (!C->getAPIntValue())
11919 std::vector<SDNode *> Built;
11920 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11922 for (SDNode *N : Built)
11927 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11928 /// expression that will generate the same value by multiplying by a magic
11930 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11931 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11932 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11936 // Avoid division by zero.
11937 if (!C->getAPIntValue())
11940 std::vector<SDNode*> Built;
11942 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11944 for (SDNode *N : Built)
11949 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11950 if (Level >= AfterLegalizeDAG)
11953 // Expose the DAG combiner to the target combiner implementations.
11954 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11956 unsigned Iterations = 0;
11957 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
11959 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11960 // For the reciprocal, we need to find the zero of the function:
11961 // F(X) = A X - 1 [which has a zero at X = 1/A]
11963 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11964 // does not require additional intermediate precision]
11965 EVT VT = Op.getValueType();
11967 SDValue FPOne = DAG.getConstantFP(1.0, VT);
11969 AddToWorklist(Est.getNode());
11971 // Newton iterations: Est = Est + Est (1 - Arg * Est)
11972 for (unsigned i = 0; i < Iterations; ++i) {
11973 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11974 AddToWorklist(NewEst.getNode());
11976 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
11977 AddToWorklist(NewEst.getNode());
11979 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11980 AddToWorklist(NewEst.getNode());
11982 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
11983 AddToWorklist(Est.getNode());
11992 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11993 /// For the reciprocal sqrt, we need to find the zero of the function:
11994 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
11996 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
11997 /// As a result, we precompute A/2 prior to the iteration loop.
11998 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
11999 unsigned Iterations) {
12000 EVT VT = Arg.getValueType();
12002 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12004 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12005 // this entire sequence requires only one FP constant.
12006 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12007 AddToWorklist(HalfArg.getNode());
12009 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12010 AddToWorklist(HalfArg.getNode());
12012 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12013 for (unsigned i = 0; i < Iterations; ++i) {
12014 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12015 AddToWorklist(NewEst.getNode());
12017 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12018 AddToWorklist(NewEst.getNode());
12020 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12021 AddToWorklist(NewEst.getNode());
12023 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12024 AddToWorklist(Est.getNode());
12029 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12030 /// For the reciprocal sqrt, we need to find the zero of the function:
12031 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12033 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12034 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12035 unsigned Iterations) {
12036 EVT VT = Arg.getValueType();
12038 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12039 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12041 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12042 for (unsigned i = 0; i < Iterations; ++i) {
12043 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12044 AddToWorklist(HalfEst.getNode());
12046 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12047 AddToWorklist(Est.getNode());
12049 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12050 AddToWorklist(Est.getNode());
12052 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12053 AddToWorklist(Est.getNode());
12055 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12056 AddToWorklist(Est.getNode());
12061 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12062 if (Level >= AfterLegalizeDAG)
12065 // Expose the DAG combiner to the target combiner implementations.
12066 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12067 unsigned Iterations = 0;
12068 bool UseOneConstNR = false;
12069 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12070 AddToWorklist(Est.getNode());
12072 Est = UseOneConstNR ?
12073 BuildRsqrtNROneConst(Op, Est, Iterations) :
12074 BuildRsqrtNRTwoConst(Op, Est, Iterations);
12082 /// Return true if base is a frame index, which is known not to alias with
12083 /// anything but itself. Provides base object and offset as results.
12084 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12085 const GlobalValue *&GV, const void *&CV) {
12086 // Assume it is a primitive operation.
12087 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12089 // If it's an adding a simple constant then integrate the offset.
12090 if (Base.getOpcode() == ISD::ADD) {
12091 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12092 Base = Base.getOperand(0);
12093 Offset += C->getZExtValue();
12097 // Return the underlying GlobalValue, and update the Offset. Return false
12098 // for GlobalAddressSDNode since the same GlobalAddress may be represented
12099 // by multiple nodes with different offsets.
12100 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12101 GV = G->getGlobal();
12102 Offset += G->getOffset();
12106 // Return the underlying Constant value, and update the Offset. Return false
12107 // for ConstantSDNodes since the same constant pool entry may be represented
12108 // by multiple nodes with different offsets.
12109 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12110 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12111 : (const void *)C->getConstVal();
12112 Offset += C->getOffset();
12115 // If it's any of the following then it can't alias with anything but itself.
12116 return isa<FrameIndexSDNode>(Base);
12119 /// Return true if there is any possibility that the two addresses overlap.
12120 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12121 // If they are the same then they must be aliases.
12122 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12124 // If they are both volatile then they cannot be reordered.
12125 if (Op0->isVolatile() && Op1->isVolatile()) return true;
12127 // Gather base node and offset information.
12128 SDValue Base1, Base2;
12129 int64_t Offset1, Offset2;
12130 const GlobalValue *GV1, *GV2;
12131 const void *CV1, *CV2;
12132 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12133 Base1, Offset1, GV1, CV1);
12134 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12135 Base2, Offset2, GV2, CV2);
12137 // If they have a same base address then check to see if they overlap.
12138 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12139 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12140 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12142 // It is possible for different frame indices to alias each other, mostly
12143 // when tail call optimization reuses return address slots for arguments.
12144 // To catch this case, look up the actual index of frame indices to compute
12145 // the real alias relationship.
12146 if (isFrameIndex1 && isFrameIndex2) {
12147 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12148 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12149 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12150 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12151 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12154 // Otherwise, if we know what the bases are, and they aren't identical, then
12155 // we know they cannot alias.
12156 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12159 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12160 // compared to the size and offset of the access, we may be able to prove they
12161 // do not alias. This check is conservative for now to catch cases created by
12162 // splitting vector types.
12163 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12164 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12165 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12166 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12167 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12168 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12169 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12171 // There is no overlap between these relatively aligned accesses of similar
12172 // size, return no alias.
12173 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12174 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12178 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12180 : DAG.getSubtarget().useAA();
12182 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12183 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12187 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12188 // Use alias analysis information.
12189 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12190 Op1->getSrcValueOffset());
12191 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12192 Op0->getSrcValueOffset() - MinOffset;
12193 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12194 Op1->getSrcValueOffset() - MinOffset;
12195 AliasAnalysis::AliasResult AAResult =
12196 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12198 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12199 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12201 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12202 if (AAResult == AliasAnalysis::NoAlias)
12206 // Otherwise we have to assume they alias.
12210 /// Walk up chain skipping non-aliasing memory nodes,
12211 /// looking for aliasing nodes and adding them to the Aliases vector.
12212 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12213 SmallVectorImpl<SDValue> &Aliases) {
12214 SmallVector<SDValue, 8> Chains; // List of chains to visit.
12215 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
12217 // Get alias information for node.
12218 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12221 Chains.push_back(OriginalChain);
12222 unsigned Depth = 0;
12224 // Look at each chain and determine if it is an alias. If so, add it to the
12225 // aliases list. If not, then continue up the chain looking for the next
12227 while (!Chains.empty()) {
12228 SDValue Chain = Chains.back();
12231 // For TokenFactor nodes, look at each operand and only continue up the
12232 // chain until we find two aliases. If we've seen two aliases, assume we'll
12233 // find more and revert to original chain since the xform is unlikely to be
12236 // FIXME: The depth check could be made to return the last non-aliasing
12237 // chain we found before we hit a tokenfactor rather than the original
12239 if (Depth > 6 || Aliases.size() == 2) {
12241 Aliases.push_back(OriginalChain);
12245 // Don't bother if we've been before.
12246 if (!Visited.insert(Chain.getNode()))
12249 switch (Chain.getOpcode()) {
12250 case ISD::EntryToken:
12251 // Entry token is ideal chain operand, but handled in FindBetterChain.
12256 // Get alias information for Chain.
12257 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12258 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12260 // If chain is alias then stop here.
12261 if (!(IsLoad && IsOpLoad) &&
12262 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12263 Aliases.push_back(Chain);
12265 // Look further up the chain.
12266 Chains.push_back(Chain.getOperand(0));
12272 case ISD::TokenFactor:
12273 // We have to check each of the operands of the token factor for "small"
12274 // token factors, so we queue them up. Adding the operands to the queue
12275 // (stack) in reverse order maintains the original order and increases the
12276 // likelihood that getNode will find a matching token factor (CSE.)
12277 if (Chain.getNumOperands() > 16) {
12278 Aliases.push_back(Chain);
12281 for (unsigned n = Chain.getNumOperands(); n;)
12282 Chains.push_back(Chain.getOperand(--n));
12287 // For all other instructions we will just have to take what we can get.
12288 Aliases.push_back(Chain);
12293 // We need to be careful here to also search for aliases through the
12294 // value operand of a store, etc. Consider the following situation:
12296 // L1 = load Token1, %52
12297 // S1 = store Token1, L1, %51
12298 // L2 = load Token1, %52+8
12299 // S2 = store Token1, L2, %51+8
12300 // Token2 = Token(S1, S2)
12301 // L3 = load Token2, %53
12302 // S3 = store Token2, L3, %52
12303 // L4 = load Token2, %53+8
12304 // S4 = store Token2, L4, %52+8
12305 // If we search for aliases of S3 (which loads address %52), and we look
12306 // only through the chain, then we'll miss the trivial dependence on L1
12307 // (which also loads from %52). We then might change all loads and
12308 // stores to use Token1 as their chain operand, which could result in
12309 // copying %53 into %52 before copying %52 into %51 (which should
12312 // The problem is, however, that searching for such data dependencies
12313 // can become expensive, and the cost is not directly related to the
12314 // chain depth. Instead, we'll rule out such configurations here by
12315 // insisting that we've visited all chain users (except for users
12316 // of the original chain, which is not necessary). When doing this,
12317 // we need to look through nodes we don't care about (otherwise, things
12318 // like register copies will interfere with trivial cases).
12320 SmallVector<const SDNode *, 16> Worklist;
12321 for (const SDNode *N : Visited)
12322 if (N != OriginalChain.getNode())
12323 Worklist.push_back(N);
12325 while (!Worklist.empty()) {
12326 const SDNode *M = Worklist.pop_back_val();
12328 // We have already visited M, and want to make sure we've visited any uses
12329 // of M that we care about. For uses that we've not visisted, and don't
12330 // care about, queue them to the worklist.
12332 for (SDNode::use_iterator UI = M->use_begin(),
12333 UIE = M->use_end(); UI != UIE; ++UI)
12334 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
12335 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12336 // We've not visited this use, and we care about it (it could have an
12337 // ordering dependency with the original node).
12339 Aliases.push_back(OriginalChain);
12343 // We've not visited this use, but we don't care about it. Mark it as
12344 // visited and enqueue it to the worklist.
12345 Worklist.push_back(*UI);
12350 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12351 /// (aliasing node.)
12352 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12353 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
12355 // Accumulate all the aliases to this node.
12356 GatherAllAliases(N, OldChain, Aliases);
12358 // If no operands then chain to entry token.
12359 if (Aliases.size() == 0)
12360 return DAG.getEntryNode();
12362 // If a single operand then chain to it. We don't need to revisit it.
12363 if (Aliases.size() == 1)
12366 // Construct a custom tailored token factor.
12367 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12370 /// This is the entry point for the file.
12371 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12372 CodeGenOpt::Level OptLevel) {
12373 /// This is the main entry point to this class.
12374 DAGCombiner(*this, AA, OptLevel).Run(Level);