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/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.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 "
80 //------------------------------ DAGCombiner ---------------------------------//
84 const TargetLowering &TLI;
86 CodeGenOpt::Level OptLevel;
91 /// \brief Worklist of all of the nodes that need to be simplified.
93 /// This must behave as a stack -- new nodes to process are pushed onto the
94 /// back and when processing we pop off of the back.
96 /// The worklist will not contain duplicates but may contain null entries
97 /// due to nodes being deleted from the underlying DAG.
98 SmallVector<SDNode *, 64> Worklist;
100 /// \brief Mapping from an SDNode to its position on the worklist.
102 /// This is used to find and remove nodes from the worklist (by nulling
103 /// them) when they are deleted from the underlying DAG. It relies on
104 /// stable indices of nodes within the worklist.
105 DenseMap<SDNode *, unsigned> WorklistMap;
107 /// \brief Set of nodes which have been combined (at least once).
109 /// This is used to allow us to reliably add any operands of a DAG node
110 /// which have not yet been combined to the worklist.
111 SmallPtrSet<SDNode *, 64> CombinedNodes;
113 // AA - Used for DAG load/store alias analysis.
116 /// AddUsersToWorklist - When an instruction is simplified, add all users of
117 /// the instruction to the work lists because they might get more simplified
120 void AddUsersToWorklist(SDNode *N) {
121 for (SDNode *Node : N->uses())
125 /// visit - call the node-specific routine that knows how to fold each
126 /// particular type of node.
127 SDValue visit(SDNode *N);
130 /// AddToWorklist - Add to the work list making sure its instance is at the
131 /// back (next to be processed.)
132 void AddToWorklist(SDNode *N) {
133 // Skip handle nodes as they can't usefully be combined and confuse the
134 // zero-use deletion strategy.
135 if (N->getOpcode() == ISD::HANDLENODE)
138 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139 Worklist.push_back(N);
142 /// removeFromWorklist - 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 /// SimplifyDemandedBits - Check the specified integer node value to see if
177 /// it can be simplified or if things it uses can be simplified by bit
178 /// propagation. 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 bool SliceUpLoad(SDNode *N);
191 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
194 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
195 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
196 /// \param EltNo index of the vector element to load.
197 /// \param OriginalLoad load that EVE came from to be replaced.
198 /// \returns EVE on success SDValue() on failure.
199 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
200 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
201 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
202 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
203 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
204 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue PromoteIntBinOp(SDValue Op);
206 SDValue PromoteIntShiftOp(SDValue Op);
207 SDValue PromoteExtend(SDValue Op);
208 bool PromoteLoad(SDValue Op);
210 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
211 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
212 ISD::NodeType ExtType);
214 /// combine - call the node-specific routine that knows how to fold each
215 /// particular type of node. If that doesn't do anything, try the
216 /// target-specific DAG combines.
217 SDValue combine(SDNode *N);
219 // Visitation implementation - Implement dag node combining for different
220 // node types. The semantics are as follows:
222 // SDValue.getNode() == 0 - No change was made
223 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
224 // otherwise - N should be replaced by the returned Operand.
226 SDValue visitTokenFactor(SDNode *N);
227 SDValue visitMERGE_VALUES(SDNode *N);
228 SDValue visitADD(SDNode *N);
229 SDValue visitSUB(SDNode *N);
230 SDValue visitADDC(SDNode *N);
231 SDValue visitSUBC(SDNode *N);
232 SDValue visitADDE(SDNode *N);
233 SDValue visitSUBE(SDNode *N);
234 SDValue visitMUL(SDNode *N);
235 SDValue visitSDIV(SDNode *N);
236 SDValue visitUDIV(SDNode *N);
237 SDValue visitSREM(SDNode *N);
238 SDValue visitUREM(SDNode *N);
239 SDValue visitMULHU(SDNode *N);
240 SDValue visitMULHS(SDNode *N);
241 SDValue visitSMUL_LOHI(SDNode *N);
242 SDValue visitUMUL_LOHI(SDNode *N);
243 SDValue visitSMULO(SDNode *N);
244 SDValue visitUMULO(SDNode *N);
245 SDValue visitSDIVREM(SDNode *N);
246 SDValue visitUDIVREM(SDNode *N);
247 SDValue visitAND(SDNode *N);
248 SDValue visitOR(SDNode *N);
249 SDValue visitXOR(SDNode *N);
250 SDValue SimplifyVBinOp(SDNode *N);
251 SDValue SimplifyVUnaryOp(SDNode *N);
252 SDValue visitSHL(SDNode *N);
253 SDValue visitSRA(SDNode *N);
254 SDValue visitSRL(SDNode *N);
255 SDValue visitRotate(SDNode *N);
256 SDValue visitCTLZ(SDNode *N);
257 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
258 SDValue visitCTTZ(SDNode *N);
259 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
260 SDValue visitCTPOP(SDNode *N);
261 SDValue visitSELECT(SDNode *N);
262 SDValue visitVSELECT(SDNode *N);
263 SDValue visitSELECT_CC(SDNode *N);
264 SDValue visitSETCC(SDNode *N);
265 SDValue visitSIGN_EXTEND(SDNode *N);
266 SDValue visitZERO_EXTEND(SDNode *N);
267 SDValue visitANY_EXTEND(SDNode *N);
268 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
269 SDValue visitTRUNCATE(SDNode *N);
270 SDValue visitBITCAST(SDNode *N);
271 SDValue visitBUILD_PAIR(SDNode *N);
272 SDValue visitFADD(SDNode *N);
273 SDValue visitFSUB(SDNode *N);
274 SDValue visitFMUL(SDNode *N);
275 SDValue visitFMA(SDNode *N);
276 SDValue visitFDIV(SDNode *N);
277 SDValue visitFREM(SDNode *N);
278 SDValue visitFCOPYSIGN(SDNode *N);
279 SDValue visitSINT_TO_FP(SDNode *N);
280 SDValue visitUINT_TO_FP(SDNode *N);
281 SDValue visitFP_TO_SINT(SDNode *N);
282 SDValue visitFP_TO_UINT(SDNode *N);
283 SDValue visitFP_ROUND(SDNode *N);
284 SDValue visitFP_ROUND_INREG(SDNode *N);
285 SDValue visitFP_EXTEND(SDNode *N);
286 SDValue visitFNEG(SDNode *N);
287 SDValue visitFABS(SDNode *N);
288 SDValue visitFCEIL(SDNode *N);
289 SDValue visitFTRUNC(SDNode *N);
290 SDValue visitFFLOOR(SDNode *N);
291 SDValue visitBRCOND(SDNode *N);
292 SDValue visitBR_CC(SDNode *N);
293 SDValue visitLOAD(SDNode *N);
294 SDValue visitSTORE(SDNode *N);
295 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
296 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
297 SDValue visitBUILD_VECTOR(SDNode *N);
298 SDValue visitCONCAT_VECTORS(SDNode *N);
299 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
300 SDValue visitVECTOR_SHUFFLE(SDNode *N);
301 SDValue visitINSERT_SUBVECTOR(SDNode *N);
303 SDValue XformToShuffleWithZero(SDNode *N);
304 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
306 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
308 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
309 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
310 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
311 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
312 SDValue N3, ISD::CondCode CC,
313 bool NotExtCompare = false);
314 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
315 SDLoc DL, bool foldBooleans = true);
317 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
319 bool isOneUseSetCC(SDValue N) const;
321 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
323 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
324 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
325 SDValue BuildSDIV(SDNode *N);
326 SDValue BuildSDIVPow2(SDNode *N);
327 SDValue BuildUDIV(SDNode *N);
328 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
329 bool DemandHighBits = true);
330 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
331 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
332 SDValue InnerPos, SDValue InnerNeg,
333 unsigned PosOpcode, unsigned NegOpcode,
335 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
336 SDValue ReduceLoadWidth(SDNode *N);
337 SDValue ReduceLoadOpStoreWidth(SDNode *N);
338 SDValue TransformFPLoadStorePair(SDNode *N);
339 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
340 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
342 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
344 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
345 /// looking for aliasing nodes and adding them to the Aliases vector.
346 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
347 SmallVectorImpl<SDValue> &Aliases);
349 /// isAlias - Return true if there is any possibility that the two addresses
351 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
353 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
354 /// looking for a better chain (aliasing node.)
355 SDValue FindBetterChain(SDNode *N, SDValue Chain);
357 /// Merge consecutive store operations into a wide store.
358 /// This optimization uses wide integers or vectors when possible.
359 /// \return True if some memory operations were changed.
360 bool MergeConsecutiveStores(StoreSDNode *N);
362 /// \brief Try to transform a truncation where C is a constant:
363 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
365 /// \p N needs to be a truncation and its first operand an AND. Other
366 /// requirements are checked by the function (e.g. that trunc is
367 /// single-use) and if missed an empty SDValue is returned.
368 SDValue distributeTruncateThroughAnd(SDNode *N);
371 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
372 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
373 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
374 AttributeSet FnAttrs =
375 DAG.getMachineFunction().getFunction()->getAttributes();
377 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
378 Attribute::OptimizeForSize) ||
379 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
382 /// Run - runs the dag combiner on all nodes in the work list
383 void Run(CombineLevel AtLevel);
385 SelectionDAG &getDAG() const { return DAG; }
387 /// getShiftAmountTy - Returns a type large enough to hold any valid
388 /// shift amount - before type legalization these can be huge.
389 EVT getShiftAmountTy(EVT LHSTy) {
390 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
391 if (LHSTy.isVector())
393 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
394 : TLI.getPointerTy();
397 /// isTypeLegal - This method returns true if we are running before type
398 /// legalization or if the specified VT is legal.
399 bool isTypeLegal(const EVT &VT) {
400 if (!LegalTypes) return true;
401 return TLI.isTypeLegal(VT);
404 /// getSetCCResultType - Convenience wrapper around
405 /// TargetLowering::getSetCCResultType
406 EVT getSetCCResultType(EVT VT) const {
407 return TLI.getSetCCResultType(*DAG.getContext(), VT);
414 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
415 /// nodes from the worklist.
416 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
419 explicit WorklistRemover(DAGCombiner &dc)
420 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
422 void NodeDeleted(SDNode *N, SDNode *E) override {
423 DC.removeFromWorklist(N);
428 //===----------------------------------------------------------------------===//
429 // TargetLowering::DAGCombinerInfo implementation
430 //===----------------------------------------------------------------------===//
432 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
433 ((DAGCombiner*)DC)->AddToWorklist(N);
436 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
437 ((DAGCombiner*)DC)->removeFromWorklist(N);
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
442 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
445 SDValue TargetLowering::DAGCombinerInfo::
446 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
447 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
451 SDValue TargetLowering::DAGCombinerInfo::
452 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
453 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
456 void TargetLowering::DAGCombinerInfo::
457 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
458 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
461 //===----------------------------------------------------------------------===//
463 //===----------------------------------------------------------------------===//
465 void DAGCombiner::deleteAndRecombine(SDNode *N) {
466 removeFromWorklist(N);
468 // If the operands of this node are only used by the node, they will now be
469 // dead. Make sure to re-visit them and recursively delete dead nodes.
470 for (const SDValue &Op : N->ops())
472 AddToWorklist(Op.getNode());
477 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
478 /// specified expression for the same cost as the expression itself, or 2 if we
479 /// can compute the negated form more cheaply than the expression itself.
480 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
481 const TargetLowering &TLI,
482 const TargetOptions *Options,
483 unsigned Depth = 0) {
484 // fneg is removable even if it has multiple uses.
485 if (Op.getOpcode() == ISD::FNEG) return 2;
487 // Don't allow anything with multiple uses.
488 if (!Op.hasOneUse()) return 0;
490 // Don't recurse exponentially.
491 if (Depth > 6) return 0;
493 switch (Op.getOpcode()) {
494 default: return false;
495 case ISD::ConstantFP:
496 // Don't invert constant FP values after legalize. The negated constant
497 // isn't necessarily legal.
498 return LegalOperations ? 0 : 1;
500 // FIXME: determine better conditions for this xform.
501 if (!Options->UnsafeFPMath) return 0;
503 // After operation legalization, it might not be legal to create new FSUBs.
504 if (LegalOperations &&
505 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
508 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
509 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
512 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
513 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
516 // We can't turn -(A-B) into B-A when we honor signed zeros.
517 if (!Options->UnsafeFPMath) return 0;
519 // fold (fneg (fsub A, B)) -> (fsub B, A)
524 if (Options->HonorSignDependentRoundingFPMath()) return 0;
526 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
527 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
531 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
537 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
542 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
543 /// returns the newly negated expression.
544 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
545 bool LegalOperations, unsigned Depth = 0) {
546 // fneg is removable even if it has multiple uses.
547 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
549 // Don't allow anything with multiple uses.
550 assert(Op.hasOneUse() && "Unknown reuse!");
552 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
553 switch (Op.getOpcode()) {
554 default: llvm_unreachable("Unknown code");
555 case ISD::ConstantFP: {
556 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
558 return DAG.getConstantFP(V, Op.getValueType());
561 // FIXME: determine better conditions for this xform.
562 assert(DAG.getTarget().Options.UnsafeFPMath);
564 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
565 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
566 DAG.getTargetLoweringInfo(),
567 &DAG.getTarget().Options, Depth+1))
568 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
569 GetNegatedExpression(Op.getOperand(0), DAG,
570 LegalOperations, Depth+1),
572 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
573 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
574 GetNegatedExpression(Op.getOperand(1), DAG,
575 LegalOperations, Depth+1),
578 // We can't turn -(A-B) into B-A when we honor signed zeros.
579 assert(DAG.getTarget().Options.UnsafeFPMath);
581 // fold (fneg (fsub 0, B)) -> B
582 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
583 if (N0CFP->getValueAPF().isZero())
584 return Op.getOperand(1);
586 // fold (fneg (fsub A, B)) -> (fsub B, A)
587 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
588 Op.getOperand(1), Op.getOperand(0));
592 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
594 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
595 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
596 DAG.getTargetLoweringInfo(),
597 &DAG.getTarget().Options, Depth+1))
598 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
599 GetNegatedExpression(Op.getOperand(0), DAG,
600 LegalOperations, Depth+1),
603 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
604 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
606 GetNegatedExpression(Op.getOperand(1), DAG,
607 LegalOperations, Depth+1));
611 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
612 GetNegatedExpression(Op.getOperand(0), DAG,
613 LegalOperations, Depth+1));
615 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
616 GetNegatedExpression(Op.getOperand(0), DAG,
617 LegalOperations, Depth+1),
622 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
623 // that selects between the target values used for true and false, making it
624 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
625 // the appropriate nodes based on the type of node we are checking. This
626 // simplifies life a bit for the callers.
627 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
629 if (N.getOpcode() == ISD::SETCC) {
630 LHS = N.getOperand(0);
631 RHS = N.getOperand(1);
632 CC = N.getOperand(2);
636 if (N.getOpcode() != ISD::SELECT_CC ||
637 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
638 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
641 LHS = N.getOperand(0);
642 RHS = N.getOperand(1);
643 CC = N.getOperand(4);
647 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
648 // one use. If this is true, it allows the users to invert the operation for
649 // free when it is profitable to do so.
650 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
652 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
657 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
658 /// elements are all the same constant or undefined.
659 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
660 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
665 unsigned SplatBitSize;
667 EVT EltVT = N->getValueType(0).getVectorElementType();
668 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
670 EltVT.getSizeInBits() >= SplatBitSize);
673 // \brief Returns the SDNode if it is a constant BuildVector or constant.
674 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
675 if (isa<ConstantSDNode>(N))
677 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
678 if(BV && BV->isConstant())
683 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
685 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
686 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
689 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
690 BitVector UndefElements;
691 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
693 // BuildVectors can truncate their operands. Ignore that case here.
694 // FIXME: We blindly ignore splats which include undef which is overly
696 if (CN && UndefElements.none() &&
697 CN->getValueType(0) == N.getValueType().getScalarType())
704 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
706 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
707 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
710 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
711 BitVector UndefElements;
712 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
714 // BuildVectors can truncate their operands. Ignore that case here.
715 // FIXME: We blindly ignore splats which include undef which is overly
717 if (CN && UndefElements.none() &&
718 CN->getValueType(0) == N.getValueType().getScalarType())
725 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
726 SDValue N0, SDValue N1) {
727 EVT VT = N0.getValueType();
728 if (N0.getOpcode() == Opc) {
729 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
730 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
731 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
732 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
733 if (!OpNode.getNode())
735 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
737 if (N0.hasOneUse()) {
738 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
740 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
741 if (!OpNode.getNode())
743 AddToWorklist(OpNode.getNode());
744 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
749 if (N1.getOpcode() == Opc) {
750 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
751 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
752 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
753 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
754 if (!OpNode.getNode())
756 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
758 if (N1.hasOneUse()) {
759 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
761 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
762 if (!OpNode.getNode())
764 AddToWorklist(OpNode.getNode());
765 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
773 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
775 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
777 DEBUG(dbgs() << "\nReplacing.1 ";
779 dbgs() << "\nWith: ";
780 To[0].getNode()->dump(&DAG);
781 dbgs() << " and " << NumTo-1 << " other values\n";
782 for (unsigned i = 0, e = NumTo; i != e; ++i)
783 assert((!To[i].getNode() ||
784 N->getValueType(i) == To[i].getValueType()) &&
785 "Cannot combine value to value of different type!"));
786 WorklistRemover DeadNodes(*this);
787 DAG.ReplaceAllUsesWith(N, To);
789 // Push the new nodes and any users onto the worklist
790 for (unsigned i = 0, e = NumTo; i != e; ++i) {
791 if (To[i].getNode()) {
792 AddToWorklist(To[i].getNode());
793 AddUsersToWorklist(To[i].getNode());
798 // Finally, if the node is now dead, remove it from the graph. The node
799 // may not be dead if the replacement process recursively simplified to
800 // something else needing this node.
802 deleteAndRecombine(N);
803 return SDValue(N, 0);
807 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
808 // Replace all uses. If any nodes become isomorphic to other nodes and
809 // are deleted, make sure to remove them from our worklist.
810 WorklistRemover DeadNodes(*this);
811 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
813 // Push the new node and any (possibly new) users onto the worklist.
814 AddToWorklist(TLO.New.getNode());
815 AddUsersToWorklist(TLO.New.getNode());
817 // Finally, if the node is now dead, remove it from the graph. The node
818 // may not be dead if the replacement process recursively simplified to
819 // something else needing this node.
820 if (TLO.Old.getNode()->use_empty())
821 deleteAndRecombine(TLO.Old.getNode());
824 /// SimplifyDemandedBits - Check the specified integer node value to see if
825 /// it can be simplified or if things it uses can be simplified by bit
826 /// propagation. If so, return true.
827 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
828 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
829 APInt KnownZero, KnownOne;
830 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
834 AddToWorklist(Op.getNode());
836 // Replace the old value with the new one.
838 DEBUG(dbgs() << "\nReplacing.2 ";
839 TLO.Old.getNode()->dump(&DAG);
840 dbgs() << "\nWith: ";
841 TLO.New.getNode()->dump(&DAG);
844 CommitTargetLoweringOpt(TLO);
848 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
850 EVT VT = Load->getValueType(0);
851 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
853 DEBUG(dbgs() << "\nReplacing.9 ";
855 dbgs() << "\nWith: ";
856 Trunc.getNode()->dump(&DAG);
858 WorklistRemover DeadNodes(*this);
859 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
860 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
861 deleteAndRecombine(Load);
862 AddToWorklist(Trunc.getNode());
865 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
868 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
869 EVT MemVT = LD->getMemoryVT();
870 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
871 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
873 : LD->getExtensionType();
875 return DAG.getExtLoad(ExtType, dl, PVT,
876 LD->getChain(), LD->getBasePtr(),
877 MemVT, LD->getMemOperand());
880 unsigned Opc = Op.getOpcode();
883 case ISD::AssertSext:
884 return DAG.getNode(ISD::AssertSext, dl, PVT,
885 SExtPromoteOperand(Op.getOperand(0), PVT),
887 case ISD::AssertZext:
888 return DAG.getNode(ISD::AssertZext, dl, PVT,
889 ZExtPromoteOperand(Op.getOperand(0), PVT),
891 case ISD::Constant: {
893 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
894 return DAG.getNode(ExtOpc, dl, PVT, Op);
898 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
900 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
903 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
904 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
906 EVT OldVT = Op.getValueType();
908 bool Replace = false;
909 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
910 if (!NewOp.getNode())
912 AddToWorklist(NewOp.getNode());
915 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
916 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
917 DAG.getValueType(OldVT));
920 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
921 EVT OldVT = Op.getValueType();
923 bool Replace = false;
924 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
925 if (!NewOp.getNode())
927 AddToWorklist(NewOp.getNode());
930 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
931 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
934 /// PromoteIntBinOp - Promote the specified integer binary operation if the
935 /// target indicates it is beneficial. e.g. On x86, it's usually better to
936 /// promote i16 operations to i32 since i16 instructions are longer.
937 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
938 if (!LegalOperations)
941 EVT VT = Op.getValueType();
942 if (VT.isVector() || !VT.isInteger())
945 // If operation type is 'undesirable', e.g. i16 on x86, consider
947 unsigned Opc = Op.getOpcode();
948 if (TLI.isTypeDesirableForOp(Opc, VT))
952 // Consult target whether it is a good idea to promote this operation and
953 // what's the right type to promote it to.
954 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
955 assert(PVT != VT && "Don't know what type to promote to!");
957 bool Replace0 = false;
958 SDValue N0 = Op.getOperand(0);
959 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
963 bool Replace1 = false;
964 SDValue N1 = Op.getOperand(1);
969 NN1 = PromoteOperand(N1, PVT, Replace1);
974 AddToWorklist(NN0.getNode());
976 AddToWorklist(NN1.getNode());
979 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
981 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
983 DEBUG(dbgs() << "\nPromoting ";
984 Op.getNode()->dump(&DAG));
986 return DAG.getNode(ISD::TRUNCATE, dl, VT,
987 DAG.getNode(Opc, dl, PVT, NN0, NN1));
992 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
993 /// target indicates it is beneficial. e.g. On x86, it's usually better to
994 /// promote i16 operations to i32 since i16 instructions are longer.
995 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
996 if (!LegalOperations)
999 EVT VT = Op.getValueType();
1000 if (VT.isVector() || !VT.isInteger())
1003 // If operation type is 'undesirable', e.g. i16 on x86, consider
1005 unsigned Opc = Op.getOpcode();
1006 if (TLI.isTypeDesirableForOp(Opc, VT))
1010 // Consult target whether it is a good idea to promote this operation and
1011 // what's the right type to promote it to.
1012 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1013 assert(PVT != VT && "Don't know what type to promote to!");
1015 bool Replace = false;
1016 SDValue N0 = Op.getOperand(0);
1017 if (Opc == ISD::SRA)
1018 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1019 else if (Opc == ISD::SRL)
1020 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1022 N0 = PromoteOperand(N0, PVT, Replace);
1026 AddToWorklist(N0.getNode());
1028 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1030 DEBUG(dbgs() << "\nPromoting ";
1031 Op.getNode()->dump(&DAG));
1033 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1034 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1039 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1040 if (!LegalOperations)
1043 EVT VT = Op.getValueType();
1044 if (VT.isVector() || !VT.isInteger())
1047 // If operation type is 'undesirable', e.g. i16 on x86, consider
1049 unsigned Opc = Op.getOpcode();
1050 if (TLI.isTypeDesirableForOp(Opc, VT))
1054 // Consult target whether it is a good idea to promote this operation and
1055 // what's the right type to promote it to.
1056 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1057 assert(PVT != VT && "Don't know what type to promote to!");
1058 // fold (aext (aext x)) -> (aext x)
1059 // fold (aext (zext x)) -> (zext x)
1060 // fold (aext (sext x)) -> (sext x)
1061 DEBUG(dbgs() << "\nPromoting ";
1062 Op.getNode()->dump(&DAG));
1063 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1068 bool DAGCombiner::PromoteLoad(SDValue Op) {
1069 if (!LegalOperations)
1072 EVT VT = Op.getValueType();
1073 if (VT.isVector() || !VT.isInteger())
1076 // If operation type is 'undesirable', e.g. i16 on x86, consider
1078 unsigned Opc = Op.getOpcode();
1079 if (TLI.isTypeDesirableForOp(Opc, VT))
1083 // Consult target whether it is a good idea to promote this operation and
1084 // what's the right type to promote it to.
1085 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1086 assert(PVT != VT && "Don't know what type to promote to!");
1089 SDNode *N = Op.getNode();
1090 LoadSDNode *LD = cast<LoadSDNode>(N);
1091 EVT MemVT = LD->getMemoryVT();
1092 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1093 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1095 : LD->getExtensionType();
1096 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1097 LD->getChain(), LD->getBasePtr(),
1098 MemVT, LD->getMemOperand());
1099 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1101 DEBUG(dbgs() << "\nPromoting ";
1104 Result.getNode()->dump(&DAG);
1106 WorklistRemover DeadNodes(*this);
1107 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1108 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1109 deleteAndRecombine(N);
1110 AddToWorklist(Result.getNode());
1116 /// \brief Recursively delete a node which has no uses and any operands for
1117 /// which it is the only use.
1119 /// Note that this both deletes the nodes and removes them from the worklist.
1120 /// It also adds any nodes who have had a user deleted to the worklist as they
1121 /// may now have only one use and subject to other combines.
1122 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1123 if (!N->use_empty())
1126 SmallSetVector<SDNode *, 16> Nodes;
1129 N = Nodes.pop_back_val();
1133 if (N->use_empty()) {
1134 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1135 Nodes.insert(N->getOperand(i).getNode());
1137 removeFromWorklist(N);
1142 } while (!Nodes.empty());
1146 //===----------------------------------------------------------------------===//
1147 // Main DAG Combiner implementation
1148 //===----------------------------------------------------------------------===//
1150 void DAGCombiner::Run(CombineLevel AtLevel) {
1151 // set the instance variables, so that the various visit routines may use it.
1153 LegalOperations = Level >= AfterLegalizeVectorOps;
1154 LegalTypes = Level >= AfterLegalizeTypes;
1156 // Add all the dag nodes to the worklist.
1157 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1158 E = DAG.allnodes_end(); I != E; ++I)
1161 // Create a dummy node (which is not added to allnodes), that adds a reference
1162 // to the root node, preventing it from being deleted, and tracking any
1163 // changes of the root.
1164 HandleSDNode Dummy(DAG.getRoot());
1166 // while the worklist isn't empty, find a node and
1167 // try and combine it.
1168 while (!WorklistMap.empty()) {
1170 // The Worklist holds the SDNodes in order, but it may contain null entries.
1172 N = Worklist.pop_back_val();
1175 bool GoodWorklistEntry = WorklistMap.erase(N);
1176 (void)GoodWorklistEntry;
1177 assert(GoodWorklistEntry &&
1178 "Found a worklist entry without a corresponding map entry!");
1180 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1181 // N is deleted from the DAG, since they too may now be dead or may have a
1182 // reduced number of uses, allowing other xforms.
1183 if (recursivelyDeleteUnusedNodes(N))
1186 WorklistRemover DeadNodes(*this);
1188 // If this combine is running after legalizing the DAG, re-legalize any
1189 // nodes pulled off the worklist.
1190 if (Level == AfterLegalizeDAG) {
1191 SmallSetVector<SDNode *, 16> UpdatedNodes;
1192 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1194 for (SDNode *LN : UpdatedNodes) {
1196 AddUsersToWorklist(LN);
1202 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1204 // Add any operands of the new node which have not yet been combined to the
1205 // worklist as well. Because the worklist uniques things already, this
1206 // won't repeatedly process the same operand.
1207 CombinedNodes.insert(N);
1208 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1209 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1210 AddToWorklist(N->getOperand(i).getNode());
1212 SDValue RV = combine(N);
1219 // If we get back the same node we passed in, rather than a new node or
1220 // zero, we know that the node must have defined multiple values and
1221 // CombineTo was used. Since CombineTo takes care of the worklist
1222 // mechanics for us, we have no work to do in this case.
1223 if (RV.getNode() == N)
1226 assert(N->getOpcode() != ISD::DELETED_NODE &&
1227 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1228 "Node was deleted but visit returned new node!");
1230 DEBUG(dbgs() << " ... into: ";
1231 RV.getNode()->dump(&DAG));
1233 // Transfer debug value.
1234 DAG.TransferDbgValues(SDValue(N, 0), RV);
1235 if (N->getNumValues() == RV.getNode()->getNumValues())
1236 DAG.ReplaceAllUsesWith(N, RV.getNode());
1238 assert(N->getValueType(0) == RV.getValueType() &&
1239 N->getNumValues() == 1 && "Type mismatch");
1241 DAG.ReplaceAllUsesWith(N, &OpV);
1244 // Push the new node and any users onto the worklist
1245 AddToWorklist(RV.getNode());
1246 AddUsersToWorklist(RV.getNode());
1248 // Finally, if the node is now dead, remove it from the graph. The node
1249 // may not be dead if the replacement process recursively simplified to
1250 // something else needing this node. This will also take care of adding any
1251 // operands which have lost a user to the worklist.
1252 recursivelyDeleteUnusedNodes(N);
1255 // If the root changed (e.g. it was a dead load, update the root).
1256 DAG.setRoot(Dummy.getValue());
1257 DAG.RemoveDeadNodes();
1260 SDValue DAGCombiner::visit(SDNode *N) {
1261 switch (N->getOpcode()) {
1263 case ISD::TokenFactor: return visitTokenFactor(N);
1264 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1265 case ISD::ADD: return visitADD(N);
1266 case ISD::SUB: return visitSUB(N);
1267 case ISD::ADDC: return visitADDC(N);
1268 case ISD::SUBC: return visitSUBC(N);
1269 case ISD::ADDE: return visitADDE(N);
1270 case ISD::SUBE: return visitSUBE(N);
1271 case ISD::MUL: return visitMUL(N);
1272 case ISD::SDIV: return visitSDIV(N);
1273 case ISD::UDIV: return visitUDIV(N);
1274 case ISD::SREM: return visitSREM(N);
1275 case ISD::UREM: return visitUREM(N);
1276 case ISD::MULHU: return visitMULHU(N);
1277 case ISD::MULHS: return visitMULHS(N);
1278 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1279 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1280 case ISD::SMULO: return visitSMULO(N);
1281 case ISD::UMULO: return visitUMULO(N);
1282 case ISD::SDIVREM: return visitSDIVREM(N);
1283 case ISD::UDIVREM: return visitUDIVREM(N);
1284 case ISD::AND: return visitAND(N);
1285 case ISD::OR: return visitOR(N);
1286 case ISD::XOR: return visitXOR(N);
1287 case ISD::SHL: return visitSHL(N);
1288 case ISD::SRA: return visitSRA(N);
1289 case ISD::SRL: return visitSRL(N);
1291 case ISD::ROTL: return visitRotate(N);
1292 case ISD::CTLZ: return visitCTLZ(N);
1293 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1294 case ISD::CTTZ: return visitCTTZ(N);
1295 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1296 case ISD::CTPOP: return visitCTPOP(N);
1297 case ISD::SELECT: return visitSELECT(N);
1298 case ISD::VSELECT: return visitVSELECT(N);
1299 case ISD::SELECT_CC: return visitSELECT_CC(N);
1300 case ISD::SETCC: return visitSETCC(N);
1301 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1302 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1303 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1304 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1305 case ISD::TRUNCATE: return visitTRUNCATE(N);
1306 case ISD::BITCAST: return visitBITCAST(N);
1307 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1308 case ISD::FADD: return visitFADD(N);
1309 case ISD::FSUB: return visitFSUB(N);
1310 case ISD::FMUL: return visitFMUL(N);
1311 case ISD::FMA: return visitFMA(N);
1312 case ISD::FDIV: return visitFDIV(N);
1313 case ISD::FREM: return visitFREM(N);
1314 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1315 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1316 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1317 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1318 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1319 case ISD::FP_ROUND: return visitFP_ROUND(N);
1320 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1321 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1322 case ISD::FNEG: return visitFNEG(N);
1323 case ISD::FABS: return visitFABS(N);
1324 case ISD::FFLOOR: return visitFFLOOR(N);
1325 case ISD::FCEIL: return visitFCEIL(N);
1326 case ISD::FTRUNC: return visitFTRUNC(N);
1327 case ISD::BRCOND: return visitBRCOND(N);
1328 case ISD::BR_CC: return visitBR_CC(N);
1329 case ISD::LOAD: return visitLOAD(N);
1330 case ISD::STORE: return visitSTORE(N);
1331 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1332 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1333 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1334 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1335 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1336 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1337 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1342 SDValue DAGCombiner::combine(SDNode *N) {
1343 SDValue RV = visit(N);
1345 // If nothing happened, try a target-specific DAG combine.
1346 if (!RV.getNode()) {
1347 assert(N->getOpcode() != ISD::DELETED_NODE &&
1348 "Node was deleted but visit returned NULL!");
1350 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1351 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1353 // Expose the DAG combiner to the target combiner impls.
1354 TargetLowering::DAGCombinerInfo
1355 DagCombineInfo(DAG, Level, false, this);
1357 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1361 // If nothing happened still, try promoting the operation.
1362 if (!RV.getNode()) {
1363 switch (N->getOpcode()) {
1371 RV = PromoteIntBinOp(SDValue(N, 0));
1376 RV = PromoteIntShiftOp(SDValue(N, 0));
1378 case ISD::SIGN_EXTEND:
1379 case ISD::ZERO_EXTEND:
1380 case ISD::ANY_EXTEND:
1381 RV = PromoteExtend(SDValue(N, 0));
1384 if (PromoteLoad(SDValue(N, 0)))
1390 // If N is a commutative binary node, try commuting it to enable more
1392 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1393 N->getNumValues() == 1) {
1394 SDValue N0 = N->getOperand(0);
1395 SDValue N1 = N->getOperand(1);
1397 // Constant operands are canonicalized to RHS.
1398 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1399 SDValue Ops[] = {N1, N0};
1401 if (const BinaryWithFlagsSDNode *BinNode =
1402 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1403 CSENode = DAG.getNodeIfExists(
1404 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1405 BinNode->hasNoSignedWrap(), BinNode->isExact());
1407 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1410 return SDValue(CSENode, 0);
1417 /// getInputChainForNode - Given a node, return its input chain if it has one,
1418 /// otherwise return a null sd operand.
1419 static SDValue getInputChainForNode(SDNode *N) {
1420 if (unsigned NumOps = N->getNumOperands()) {
1421 if (N->getOperand(0).getValueType() == MVT::Other)
1422 return N->getOperand(0);
1423 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1424 return N->getOperand(NumOps-1);
1425 for (unsigned i = 1; i < NumOps-1; ++i)
1426 if (N->getOperand(i).getValueType() == MVT::Other)
1427 return N->getOperand(i);
1432 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1433 // If N has two operands, where one has an input chain equal to the other,
1434 // the 'other' chain is redundant.
1435 if (N->getNumOperands() == 2) {
1436 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1437 return N->getOperand(0);
1438 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1439 return N->getOperand(1);
1442 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1443 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1444 SmallPtrSet<SDNode*, 16> SeenOps;
1445 bool Changed = false; // If we should replace this token factor.
1447 // Start out with this token factor.
1450 // Iterate through token factors. The TFs grows when new token factors are
1452 for (unsigned i = 0; i < TFs.size(); ++i) {
1453 SDNode *TF = TFs[i];
1455 // Check each of the operands.
1456 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1457 SDValue Op = TF->getOperand(i);
1459 switch (Op.getOpcode()) {
1460 case ISD::EntryToken:
1461 // Entry tokens don't need to be added to the list. They are
1466 case ISD::TokenFactor:
1467 if (Op.hasOneUse() &&
1468 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1469 // Queue up for processing.
1470 TFs.push_back(Op.getNode());
1471 // Clean up in case the token factor is removed.
1472 AddToWorklist(Op.getNode());
1479 // Only add if it isn't already in the list.
1480 if (SeenOps.insert(Op.getNode()))
1491 // If we've change things around then replace token factor.
1494 // The entry token is the only possible outcome.
1495 Result = DAG.getEntryNode();
1497 // New and improved token factor.
1498 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1501 // Don't add users to work list.
1502 return CombineTo(N, Result, false);
1508 /// MERGE_VALUES can always be eliminated.
1509 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1510 WorklistRemover DeadNodes(*this);
1511 // Replacing results may cause a different MERGE_VALUES to suddenly
1512 // be CSE'd with N, and carry its uses with it. Iterate until no
1513 // uses remain, to ensure that the node can be safely deleted.
1514 // First add the users of this node to the work list so that they
1515 // can be tried again once they have new operands.
1516 AddUsersToWorklist(N);
1518 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1519 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1520 } while (!N->use_empty());
1521 deleteAndRecombine(N);
1522 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1526 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1527 SelectionDAG &DAG) {
1528 EVT VT = N0.getValueType();
1529 SDValue N00 = N0.getOperand(0);
1530 SDValue N01 = N0.getOperand(1);
1531 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1533 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1534 isa<ConstantSDNode>(N00.getOperand(1))) {
1535 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1536 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1537 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1538 N00.getOperand(0), N01),
1539 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1540 N00.getOperand(1), N01));
1541 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1547 SDValue DAGCombiner::visitADD(SDNode *N) {
1548 SDValue N0 = N->getOperand(0);
1549 SDValue N1 = N->getOperand(1);
1550 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1551 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1552 EVT VT = N0.getValueType();
1555 if (VT.isVector()) {
1556 SDValue FoldedVOp = SimplifyVBinOp(N);
1557 if (FoldedVOp.getNode()) return FoldedVOp;
1559 // fold (add x, 0) -> x, vector edition
1560 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1562 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1566 // fold (add x, undef) -> undef
1567 if (N0.getOpcode() == ISD::UNDEF)
1569 if (N1.getOpcode() == ISD::UNDEF)
1571 // fold (add c1, c2) -> c1+c2
1573 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1574 // canonicalize constant to RHS
1576 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1577 // fold (add x, 0) -> x
1578 if (N1C && N1C->isNullValue())
1580 // fold (add Sym, c) -> Sym+c
1581 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1582 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1583 GA->getOpcode() == ISD::GlobalAddress)
1584 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1586 (uint64_t)N1C->getSExtValue());
1587 // fold ((c1-A)+c2) -> (c1+c2)-A
1588 if (N1C && N0.getOpcode() == ISD::SUB)
1589 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1590 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1591 DAG.getConstant(N1C->getAPIntValue()+
1592 N0C->getAPIntValue(), VT),
1595 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1598 // fold ((0-A) + B) -> B-A
1599 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1600 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1601 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1602 // fold (A + (0-B)) -> A-B
1603 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1604 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1605 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1606 // fold (A+(B-A)) -> B
1607 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1608 return N1.getOperand(0);
1609 // fold ((B-A)+A) -> B
1610 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1611 return N0.getOperand(0);
1612 // fold (A+(B-(A+C))) to (B-C)
1613 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1614 N0 == N1.getOperand(1).getOperand(0))
1615 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1616 N1.getOperand(1).getOperand(1));
1617 // fold (A+(B-(C+A))) to (B-C)
1618 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1619 N0 == N1.getOperand(1).getOperand(1))
1620 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1621 N1.getOperand(1).getOperand(0));
1622 // fold (A+((B-A)+or-C)) to (B+or-C)
1623 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1624 N1.getOperand(0).getOpcode() == ISD::SUB &&
1625 N0 == N1.getOperand(0).getOperand(1))
1626 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1627 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1629 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1630 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1631 SDValue N00 = N0.getOperand(0);
1632 SDValue N01 = N0.getOperand(1);
1633 SDValue N10 = N1.getOperand(0);
1634 SDValue N11 = N1.getOperand(1);
1636 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1637 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1638 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1639 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1642 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1643 return SDValue(N, 0);
1645 // fold (a+b) -> (a|b) iff a and b share no bits.
1646 if (VT.isInteger() && !VT.isVector()) {
1647 APInt LHSZero, LHSOne;
1648 APInt RHSZero, RHSOne;
1649 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1651 if (LHSZero.getBoolValue()) {
1652 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1654 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1655 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1656 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1657 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1658 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1663 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1664 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1665 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1666 if (Result.getNode()) return Result;
1668 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1669 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1670 if (Result.getNode()) return Result;
1673 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1674 if (N1.getOpcode() == ISD::SHL &&
1675 N1.getOperand(0).getOpcode() == ISD::SUB)
1676 if (ConstantSDNode *C =
1677 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1678 if (C->getAPIntValue() == 0)
1679 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1680 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1681 N1.getOperand(0).getOperand(1),
1683 if (N0.getOpcode() == ISD::SHL &&
1684 N0.getOperand(0).getOpcode() == ISD::SUB)
1685 if (ConstantSDNode *C =
1686 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1687 if (C->getAPIntValue() == 0)
1688 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1689 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1690 N0.getOperand(0).getOperand(1),
1693 if (N1.getOpcode() == ISD::AND) {
1694 SDValue AndOp0 = N1.getOperand(0);
1695 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1696 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1697 unsigned DestBits = VT.getScalarType().getSizeInBits();
1699 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1700 // and similar xforms where the inner op is either ~0 or 0.
1701 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1703 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1707 // add (sext i1), X -> sub X, (zext i1)
1708 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1709 N0.getOperand(0).getValueType() == MVT::i1 &&
1710 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1712 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1713 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1719 SDValue DAGCombiner::visitADDC(SDNode *N) {
1720 SDValue N0 = N->getOperand(0);
1721 SDValue N1 = N->getOperand(1);
1722 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1723 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1724 EVT VT = N0.getValueType();
1726 // If the flag result is dead, turn this into an ADD.
1727 if (!N->hasAnyUseOfValue(1))
1728 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1729 DAG.getNode(ISD::CARRY_FALSE,
1730 SDLoc(N), MVT::Glue));
1732 // canonicalize constant to RHS.
1734 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1736 // fold (addc x, 0) -> x + no carry out
1737 if (N1C && N1C->isNullValue())
1738 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1739 SDLoc(N), MVT::Glue));
1741 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1742 APInt LHSZero, LHSOne;
1743 APInt RHSZero, RHSOne;
1744 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1746 if (LHSZero.getBoolValue()) {
1747 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1749 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1750 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1751 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1752 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1753 DAG.getNode(ISD::CARRY_FALSE,
1754 SDLoc(N), MVT::Glue));
1760 SDValue DAGCombiner::visitADDE(SDNode *N) {
1761 SDValue N0 = N->getOperand(0);
1762 SDValue N1 = N->getOperand(1);
1763 SDValue CarryIn = N->getOperand(2);
1764 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1765 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1767 // canonicalize constant to RHS
1769 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1772 // fold (adde x, y, false) -> (addc x, y)
1773 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1774 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1779 // Since it may not be valid to emit a fold to zero for vector initializers
1780 // check if we can before folding.
1781 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1783 bool LegalOperations, bool LegalTypes) {
1785 return DAG.getConstant(0, VT);
1786 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1787 return DAG.getConstant(0, VT);
1791 SDValue DAGCombiner::visitSUB(SDNode *N) {
1792 SDValue N0 = N->getOperand(0);
1793 SDValue N1 = N->getOperand(1);
1794 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1795 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1796 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1797 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1798 EVT VT = N0.getValueType();
1801 if (VT.isVector()) {
1802 SDValue FoldedVOp = SimplifyVBinOp(N);
1803 if (FoldedVOp.getNode()) return FoldedVOp;
1805 // fold (sub x, 0) -> x, vector edition
1806 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1810 // fold (sub x, x) -> 0
1811 // FIXME: Refactor this and xor and other similar operations together.
1813 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1814 // fold (sub c1, c2) -> c1-c2
1816 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1817 // fold (sub x, c) -> (add x, -c)
1819 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1820 DAG.getConstant(-N1C->getAPIntValue(), VT));
1821 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1822 if (N0C && N0C->isAllOnesValue())
1823 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1824 // fold A-(A-B) -> B
1825 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1826 return N1.getOperand(1);
1827 // fold (A+B)-A -> B
1828 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1829 return N0.getOperand(1);
1830 // fold (A+B)-B -> A
1831 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1832 return N0.getOperand(0);
1833 // fold C2-(A+C1) -> (C2-C1)-A
1834 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1835 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1837 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1840 // fold ((A+(B+or-C))-B) -> A+or-C
1841 if (N0.getOpcode() == ISD::ADD &&
1842 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1843 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1844 N0.getOperand(1).getOperand(0) == N1)
1845 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1846 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1847 // fold ((A+(C+B))-B) -> A+C
1848 if (N0.getOpcode() == ISD::ADD &&
1849 N0.getOperand(1).getOpcode() == ISD::ADD &&
1850 N0.getOperand(1).getOperand(1) == N1)
1851 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1852 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1853 // fold ((A-(B-C))-C) -> A-B
1854 if (N0.getOpcode() == ISD::SUB &&
1855 N0.getOperand(1).getOpcode() == ISD::SUB &&
1856 N0.getOperand(1).getOperand(1) == N1)
1857 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1858 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1860 // If either operand of a sub is undef, the result is undef
1861 if (N0.getOpcode() == ISD::UNDEF)
1863 if (N1.getOpcode() == ISD::UNDEF)
1866 // If the relocation model supports it, consider symbol offsets.
1867 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1868 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1869 // fold (sub Sym, c) -> Sym-c
1870 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1871 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1873 (uint64_t)N1C->getSExtValue());
1874 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1875 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1876 if (GA->getGlobal() == GB->getGlobal())
1877 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1884 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1885 SDValue N0 = N->getOperand(0);
1886 SDValue N1 = N->getOperand(1);
1887 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1888 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1889 EVT VT = N0.getValueType();
1891 // If the flag result is dead, turn this into an SUB.
1892 if (!N->hasAnyUseOfValue(1))
1893 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1894 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1897 // fold (subc x, x) -> 0 + no borrow
1899 return CombineTo(N, DAG.getConstant(0, VT),
1900 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1903 // fold (subc x, 0) -> x + no borrow
1904 if (N1C && N1C->isNullValue())
1905 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1908 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1909 if (N0C && N0C->isAllOnesValue())
1910 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1911 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1917 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1918 SDValue N0 = N->getOperand(0);
1919 SDValue N1 = N->getOperand(1);
1920 SDValue CarryIn = N->getOperand(2);
1922 // fold (sube x, y, false) -> (subc x, y)
1923 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1924 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1929 SDValue DAGCombiner::visitMUL(SDNode *N) {
1930 SDValue N0 = N->getOperand(0);
1931 SDValue N1 = N->getOperand(1);
1932 EVT VT = N0.getValueType();
1934 // fold (mul x, undef) -> 0
1935 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1936 return DAG.getConstant(0, VT);
1938 bool N0IsConst = false;
1939 bool N1IsConst = false;
1940 APInt ConstValue0, ConstValue1;
1942 if (VT.isVector()) {
1943 SDValue FoldedVOp = SimplifyVBinOp(N);
1944 if (FoldedVOp.getNode()) return FoldedVOp;
1946 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1947 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1949 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1950 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1952 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1953 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1957 // fold (mul c1, c2) -> c1*c2
1958 if (N0IsConst && N1IsConst)
1959 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1961 // canonicalize constant to RHS
1962 if (N0IsConst && !N1IsConst)
1963 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1964 // fold (mul x, 0) -> 0
1965 if (N1IsConst && ConstValue1 == 0)
1967 // We require a splat of the entire scalar bit width for non-contiguous
1970 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1971 // fold (mul x, 1) -> x
1972 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1974 // fold (mul x, -1) -> 0-x
1975 if (N1IsConst && ConstValue1.isAllOnesValue())
1976 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1977 DAG.getConstant(0, VT), N0);
1978 // fold (mul x, (1 << c)) -> x << c
1979 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1980 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1981 DAG.getConstant(ConstValue1.logBase2(),
1982 getShiftAmountTy(N0.getValueType())));
1983 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1984 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1985 unsigned Log2Val = (-ConstValue1).logBase2();
1986 // FIXME: If the input is something that is easily negated (e.g. a
1987 // single-use add), we should put the negate there.
1988 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1989 DAG.getConstant(0, VT),
1990 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1991 DAG.getConstant(Log2Val,
1992 getShiftAmountTy(N0.getValueType()))));
1996 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1997 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1998 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1999 isa<ConstantSDNode>(N0.getOperand(1)))) {
2000 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2001 N1, N0.getOperand(1));
2002 AddToWorklist(C3.getNode());
2003 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2004 N0.getOperand(0), C3);
2007 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2010 SDValue Sh(nullptr,0), Y(nullptr,0);
2011 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2012 if (N0.getOpcode() == ISD::SHL &&
2013 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2014 isa<ConstantSDNode>(N0.getOperand(1))) &&
2015 N0.getNode()->hasOneUse()) {
2017 } else if (N1.getOpcode() == ISD::SHL &&
2018 isa<ConstantSDNode>(N1.getOperand(1)) &&
2019 N1.getNode()->hasOneUse()) {
2024 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2025 Sh.getOperand(0), Y);
2026 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2027 Mul, Sh.getOperand(1));
2031 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2032 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2033 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2034 isa<ConstantSDNode>(N0.getOperand(1))))
2035 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2036 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2037 N0.getOperand(0), N1),
2038 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2039 N0.getOperand(1), N1));
2042 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2049 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2050 SDValue N0 = N->getOperand(0);
2051 SDValue N1 = N->getOperand(1);
2052 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2053 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2054 EVT VT = N->getValueType(0);
2057 if (VT.isVector()) {
2058 SDValue FoldedVOp = SimplifyVBinOp(N);
2059 if (FoldedVOp.getNode()) return FoldedVOp;
2062 // fold (sdiv c1, c2) -> c1/c2
2063 if (N0C && N1C && !N1C->isNullValue())
2064 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2065 // fold (sdiv X, 1) -> X
2066 if (N1C && N1C->getAPIntValue() == 1LL)
2068 // fold (sdiv X, -1) -> 0-X
2069 if (N1C && N1C->isAllOnesValue())
2070 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2071 DAG.getConstant(0, VT), N0);
2072 // If we know the sign bits of both operands are zero, strength reduce to a
2073 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2074 if (!VT.isVector()) {
2075 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2076 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2080 // fold (sdiv X, pow2) -> simple ops after legalize
2081 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2082 (-N1C->getAPIntValue()).isPowerOf2())) {
2083 // If dividing by powers of two is cheap, then don't perform the following
2085 if (TLI.isPow2DivCheap())
2088 // Target-specific implementation of sdiv x, pow2.
2089 SDValue Res = BuildSDIVPow2(N);
2093 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2095 // Splat the sign bit into the register
2097 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2098 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2099 getShiftAmountTy(N0.getValueType())));
2100 AddToWorklist(SGN.getNode());
2102 // Add (N0 < 0) ? abs2 - 1 : 0;
2104 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2105 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2106 getShiftAmountTy(SGN.getValueType())));
2107 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2108 AddToWorklist(SRL.getNode());
2109 AddToWorklist(ADD.getNode()); // Divide by pow2
2110 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2111 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2113 // If we're dividing by a positive value, we're done. Otherwise, we must
2114 // negate the result.
2115 if (N1C->getAPIntValue().isNonNegative())
2118 AddToWorklist(SRA.getNode());
2119 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2122 // if integer divide is expensive and we satisfy the requirements, emit an
2123 // alternate sequence.
2124 if (N1C && !TLI.isIntDivCheap()) {
2125 SDValue Op = BuildSDIV(N);
2126 if (Op.getNode()) return Op;
2130 if (N0.getOpcode() == ISD::UNDEF)
2131 return DAG.getConstant(0, VT);
2132 // X / undef -> undef
2133 if (N1.getOpcode() == ISD::UNDEF)
2139 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2140 SDValue N0 = N->getOperand(0);
2141 SDValue N1 = N->getOperand(1);
2142 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2143 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2144 EVT VT = N->getValueType(0);
2147 if (VT.isVector()) {
2148 SDValue FoldedVOp = SimplifyVBinOp(N);
2149 if (FoldedVOp.getNode()) return FoldedVOp;
2152 // fold (udiv c1, c2) -> c1/c2
2153 if (N0C && N1C && !N1C->isNullValue())
2154 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2155 // fold (udiv x, (1 << c)) -> x >>u c
2156 if (N1C && N1C->getAPIntValue().isPowerOf2())
2157 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2158 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2159 getShiftAmountTy(N0.getValueType())));
2160 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2161 if (N1.getOpcode() == ISD::SHL) {
2162 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2163 if (SHC->getAPIntValue().isPowerOf2()) {
2164 EVT ADDVT = N1.getOperand(1).getValueType();
2165 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2167 DAG.getConstant(SHC->getAPIntValue()
2170 AddToWorklist(Add.getNode());
2171 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2175 // fold (udiv x, c) -> alternate
2176 if (N1C && !TLI.isIntDivCheap()) {
2177 SDValue Op = BuildUDIV(N);
2178 if (Op.getNode()) return Op;
2182 if (N0.getOpcode() == ISD::UNDEF)
2183 return DAG.getConstant(0, VT);
2184 // X / undef -> undef
2185 if (N1.getOpcode() == ISD::UNDEF)
2191 SDValue DAGCombiner::visitSREM(SDNode *N) {
2192 SDValue N0 = N->getOperand(0);
2193 SDValue N1 = N->getOperand(1);
2194 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2195 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2196 EVT VT = N->getValueType(0);
2198 // fold (srem c1, c2) -> c1%c2
2199 if (N0C && N1C && !N1C->isNullValue())
2200 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2201 // If we know the sign bits of both operands are zero, strength reduce to a
2202 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2203 if (!VT.isVector()) {
2204 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2205 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2208 // If X/C can be simplified by the division-by-constant logic, lower
2209 // X%C to the equivalent of X-X/C*C.
2210 if (N1C && !N1C->isNullValue()) {
2211 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2212 AddToWorklist(Div.getNode());
2213 SDValue OptimizedDiv = combine(Div.getNode());
2214 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2215 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2217 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2218 AddToWorklist(Mul.getNode());
2224 if (N0.getOpcode() == ISD::UNDEF)
2225 return DAG.getConstant(0, VT);
2226 // X % undef -> undef
2227 if (N1.getOpcode() == ISD::UNDEF)
2233 SDValue DAGCombiner::visitUREM(SDNode *N) {
2234 SDValue N0 = N->getOperand(0);
2235 SDValue N1 = N->getOperand(1);
2236 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2237 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2238 EVT VT = N->getValueType(0);
2240 // fold (urem c1, c2) -> c1%c2
2241 if (N0C && N1C && !N1C->isNullValue())
2242 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2243 // fold (urem x, pow2) -> (and x, pow2-1)
2244 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2245 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2246 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2247 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2248 if (N1.getOpcode() == ISD::SHL) {
2249 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2250 if (SHC->getAPIntValue().isPowerOf2()) {
2252 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2253 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2255 AddToWorklist(Add.getNode());
2256 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2261 // If X/C can be simplified by the division-by-constant logic, lower
2262 // X%C to the equivalent of X-X/C*C.
2263 if (N1C && !N1C->isNullValue()) {
2264 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2265 AddToWorklist(Div.getNode());
2266 SDValue OptimizedDiv = combine(Div.getNode());
2267 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2268 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2270 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2271 AddToWorklist(Mul.getNode());
2277 if (N0.getOpcode() == ISD::UNDEF)
2278 return DAG.getConstant(0, VT);
2279 // X % undef -> undef
2280 if (N1.getOpcode() == ISD::UNDEF)
2286 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2287 SDValue N0 = N->getOperand(0);
2288 SDValue N1 = N->getOperand(1);
2289 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2290 EVT VT = N->getValueType(0);
2293 // fold (mulhs x, 0) -> 0
2294 if (N1C && N1C->isNullValue())
2296 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2297 if (N1C && N1C->getAPIntValue() == 1)
2298 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2299 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2300 getShiftAmountTy(N0.getValueType())));
2301 // fold (mulhs x, undef) -> 0
2302 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2303 return DAG.getConstant(0, VT);
2305 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2307 if (VT.isSimple() && !VT.isVector()) {
2308 MVT Simple = VT.getSimpleVT();
2309 unsigned SimpleSize = Simple.getSizeInBits();
2310 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2311 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2312 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2313 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2314 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2315 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2316 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2317 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2324 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2325 SDValue N0 = N->getOperand(0);
2326 SDValue N1 = N->getOperand(1);
2327 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2328 EVT VT = N->getValueType(0);
2331 // fold (mulhu x, 0) -> 0
2332 if (N1C && N1C->isNullValue())
2334 // fold (mulhu x, 1) -> 0
2335 if (N1C && N1C->getAPIntValue() == 1)
2336 return DAG.getConstant(0, N0.getValueType());
2337 // fold (mulhu x, undef) -> 0
2338 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2339 return DAG.getConstant(0, VT);
2341 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2343 if (VT.isSimple() && !VT.isVector()) {
2344 MVT Simple = VT.getSimpleVT();
2345 unsigned SimpleSize = Simple.getSizeInBits();
2346 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2347 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2348 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2349 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2350 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2351 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2352 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2353 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2360 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2361 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2362 /// that are being performed. Return true if a simplification was made.
2364 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2366 // If the high half is not needed, just compute the low half.
2367 bool HiExists = N->hasAnyUseOfValue(1);
2369 (!LegalOperations ||
2370 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2371 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2372 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
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),
2382 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2383 return CombineTo(N, Res, Res);
2386 // If both halves are used, return as it is.
2387 if (LoExists && HiExists)
2390 // If the two computed results can be simplified separately, separate them.
2392 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2393 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2394 AddToWorklist(Lo.getNode());
2395 SDValue LoOpt = combine(Lo.getNode());
2396 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2397 (!LegalOperations ||
2398 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2399 return CombineTo(N, LoOpt, LoOpt);
2403 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2404 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2405 AddToWorklist(Hi.getNode());
2406 SDValue HiOpt = combine(Hi.getNode());
2407 if (HiOpt.getNode() && HiOpt != Hi &&
2408 (!LegalOperations ||
2409 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2410 return CombineTo(N, HiOpt, HiOpt);
2416 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2417 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2418 if (Res.getNode()) return Res;
2420 EVT VT = N->getValueType(0);
2423 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2425 if (VT.isSimple() && !VT.isVector()) {
2426 MVT Simple = VT.getSimpleVT();
2427 unsigned SimpleSize = Simple.getSizeInBits();
2428 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2429 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2430 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2431 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2432 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2433 // Compute the high part as N1.
2434 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2435 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2436 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2437 // Compute the low part as N0.
2438 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2439 return CombineTo(N, Lo, Hi);
2446 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2447 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2448 if (Res.getNode()) return Res;
2450 EVT VT = N->getValueType(0);
2453 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2455 if (VT.isSimple() && !VT.isVector()) {
2456 MVT Simple = VT.getSimpleVT();
2457 unsigned SimpleSize = Simple.getSizeInBits();
2458 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2459 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2460 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2461 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2462 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2463 // Compute the high part as N1.
2464 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2465 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2466 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2467 // Compute the low part as N0.
2468 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2469 return CombineTo(N, Lo, Hi);
2476 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2477 // (smulo x, 2) -> (saddo x, x)
2478 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2479 if (C2->getAPIntValue() == 2)
2480 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2481 N->getOperand(0), N->getOperand(0));
2486 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2487 // (umulo x, 2) -> (uaddo x, x)
2488 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2489 if (C2->getAPIntValue() == 2)
2490 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2491 N->getOperand(0), N->getOperand(0));
2496 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2497 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2498 if (Res.getNode()) return Res;
2503 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2504 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2505 if (Res.getNode()) return Res;
2510 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2511 /// two operands of the same opcode, try to simplify it.
2512 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2513 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2514 EVT VT = N0.getValueType();
2515 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2517 // Bail early if none of these transforms apply.
2518 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2520 // For each of OP in AND/OR/XOR:
2521 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2522 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2523 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2524 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2526 // do not sink logical op inside of a vector extend, since it may combine
2528 EVT Op0VT = N0.getOperand(0).getValueType();
2529 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2530 N0.getOpcode() == ISD::SIGN_EXTEND ||
2531 // Avoid infinite looping with PromoteIntBinOp.
2532 (N0.getOpcode() == ISD::ANY_EXTEND &&
2533 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2534 (N0.getOpcode() == ISD::TRUNCATE &&
2535 (!TLI.isZExtFree(VT, Op0VT) ||
2536 !TLI.isTruncateFree(Op0VT, VT)) &&
2537 TLI.isTypeLegal(Op0VT))) &&
2539 Op0VT == N1.getOperand(0).getValueType() &&
2540 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2541 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2542 N0.getOperand(0).getValueType(),
2543 N0.getOperand(0), N1.getOperand(0));
2544 AddToWorklist(ORNode.getNode());
2545 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2548 // For each of OP in SHL/SRL/SRA/AND...
2549 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2550 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2551 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2552 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2553 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2554 N0.getOperand(1) == N1.getOperand(1)) {
2555 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2556 N0.getOperand(0).getValueType(),
2557 N0.getOperand(0), N1.getOperand(0));
2558 AddToWorklist(ORNode.getNode());
2559 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2560 ORNode, N0.getOperand(1));
2563 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2564 // Only perform this optimization after type legalization and before
2565 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2566 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2567 // we don't want to undo this promotion.
2568 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2570 if ((N0.getOpcode() == ISD::BITCAST ||
2571 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2572 Level == AfterLegalizeTypes) {
2573 SDValue In0 = N0.getOperand(0);
2574 SDValue In1 = N1.getOperand(0);
2575 EVT In0Ty = In0.getValueType();
2576 EVT In1Ty = In1.getValueType();
2578 // If both incoming values are integers, and the original types are the
2580 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2581 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2582 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2583 AddToWorklist(Op.getNode());
2588 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2589 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2590 // If both shuffles use the same mask, and both shuffle within a single
2591 // vector, then it is worthwhile to move the swizzle after the operation.
2592 // The type-legalizer generates this pattern when loading illegal
2593 // vector types from memory. In many cases this allows additional shuffle
2595 // There are other cases where moving the shuffle after the xor/and/or
2596 // is profitable even if shuffles don't perform a swizzle.
2597 // If both shuffles use the same mask, and both shuffles have the same first
2598 // or second operand, then it might still be profitable to move the shuffle
2599 // after the xor/and/or operation.
2600 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2601 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2602 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2604 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2605 "Inputs to shuffles are not the same type");
2607 // Check that both shuffles use the same mask. The masks are known to be of
2608 // the same length because the result vector type is the same.
2609 // Check also that shuffles have only one use to avoid introducing extra
2611 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2612 SVN0->getMask().equals(SVN1->getMask())) {
2613 SDValue ShOp = N0->getOperand(1);
2615 // Don't try to fold this node if it requires introducing a
2616 // build vector of all zeros that might be illegal at this stage.
2617 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2619 ShOp = DAG.getConstant(0, VT);
2624 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2625 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2626 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2627 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2628 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2629 N0->getOperand(0), N1->getOperand(0));
2630 AddToWorklist(NewNode.getNode());
2631 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2632 &SVN0->getMask()[0]);
2635 // Don't try to fold this node if it requires introducing a
2636 // build vector of all zeros that might be illegal at this stage.
2637 ShOp = N0->getOperand(0);
2638 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2640 ShOp = DAG.getConstant(0, VT);
2645 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2646 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2647 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2648 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2649 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2650 N0->getOperand(1), N1->getOperand(1));
2651 AddToWorklist(NewNode.getNode());
2652 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2653 &SVN0->getMask()[0]);
2661 SDValue DAGCombiner::visitAND(SDNode *N) {
2662 SDValue N0 = N->getOperand(0);
2663 SDValue N1 = N->getOperand(1);
2664 SDValue LL, LR, RL, RR, CC0, CC1;
2665 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2666 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2667 EVT VT = N1.getValueType();
2668 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2671 if (VT.isVector()) {
2672 SDValue FoldedVOp = SimplifyVBinOp(N);
2673 if (FoldedVOp.getNode()) return FoldedVOp;
2675 // fold (and x, 0) -> 0, vector edition
2676 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2678 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2681 // fold (and x, -1) -> x, vector edition
2682 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2684 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2688 // fold (and x, undef) -> 0
2689 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2690 return DAG.getConstant(0, VT);
2691 // fold (and c1, c2) -> c1&c2
2693 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2694 // canonicalize constant to RHS
2696 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2697 // fold (and x, -1) -> x
2698 if (N1C && N1C->isAllOnesValue())
2700 // if (and x, c) is known to be zero, return 0
2701 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2702 APInt::getAllOnesValue(BitWidth)))
2703 return DAG.getConstant(0, VT);
2705 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2708 // fold (and (or x, C), D) -> D if (C & D) == D
2709 if (N1C && N0.getOpcode() == ISD::OR)
2710 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2711 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2713 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2714 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2715 SDValue N0Op0 = N0.getOperand(0);
2716 APInt Mask = ~N1C->getAPIntValue();
2717 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2718 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2719 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2720 N0.getValueType(), N0Op0);
2722 // Replace uses of the AND with uses of the Zero extend node.
2725 // We actually want to replace all uses of the any_extend with the
2726 // zero_extend, to avoid duplicating things. This will later cause this
2727 // AND to be folded.
2728 CombineTo(N0.getNode(), Zext);
2729 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2732 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2733 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2734 // already be zero by virtue of the width of the base type of the load.
2736 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2738 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2739 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2740 N0.getOpcode() == ISD::LOAD) {
2741 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2742 N0 : N0.getOperand(0) );
2744 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2745 // This can be a pure constant or a vector splat, in which case we treat the
2746 // vector as a scalar and use the splat value.
2747 APInt Constant = APInt::getNullValue(1);
2748 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2749 Constant = C->getAPIntValue();
2750 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2751 APInt SplatValue, SplatUndef;
2752 unsigned SplatBitSize;
2754 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2755 SplatBitSize, HasAnyUndefs);
2757 // Undef bits can contribute to a possible optimisation if set, so
2759 SplatValue |= SplatUndef;
2761 // The splat value may be something like "0x00FFFFFF", which means 0 for
2762 // the first vector value and FF for the rest, repeating. We need a mask
2763 // that will apply equally to all members of the vector, so AND all the
2764 // lanes of the constant together.
2765 EVT VT = Vector->getValueType(0);
2766 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2768 // If the splat value has been compressed to a bitlength lower
2769 // than the size of the vector lane, we need to re-expand it to
2771 if (BitWidth > SplatBitSize)
2772 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2773 SplatBitSize < BitWidth;
2774 SplatBitSize = SplatBitSize * 2)
2775 SplatValue |= SplatValue.shl(SplatBitSize);
2777 Constant = APInt::getAllOnesValue(BitWidth);
2778 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2779 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2783 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2784 // actually legal and isn't going to get expanded, else this is a false
2786 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2787 Load->getMemoryVT());
2789 // Resize the constant to the same size as the original memory access before
2790 // extension. If it is still the AllOnesValue then this AND is completely
2793 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2796 switch (Load->getExtensionType()) {
2797 default: B = false; break;
2798 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2800 case ISD::NON_EXTLOAD: B = true; break;
2803 if (B && Constant.isAllOnesValue()) {
2804 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2805 // preserve semantics once we get rid of the AND.
2806 SDValue NewLoad(Load, 0);
2807 if (Load->getExtensionType() == ISD::EXTLOAD) {
2808 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2809 Load->getValueType(0), SDLoc(Load),
2810 Load->getChain(), Load->getBasePtr(),
2811 Load->getOffset(), Load->getMemoryVT(),
2812 Load->getMemOperand());
2813 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2814 if (Load->getNumValues() == 3) {
2815 // PRE/POST_INC loads have 3 values.
2816 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2817 NewLoad.getValue(2) };
2818 CombineTo(Load, To, 3, true);
2820 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2824 // Fold the AND away, taking care not to fold to the old load node if we
2826 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2828 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2831 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2832 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2833 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2834 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2836 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2837 LL.getValueType().isInteger()) {
2838 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2839 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2840 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2841 LR.getValueType(), LL, RL);
2842 AddToWorklist(ORNode.getNode());
2843 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2845 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2846 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2847 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2848 LR.getValueType(), LL, RL);
2849 AddToWorklist(ANDNode.getNode());
2850 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2852 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2853 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2854 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2855 LR.getValueType(), LL, RL);
2856 AddToWorklist(ORNode.getNode());
2857 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2860 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2861 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2862 Op0 == Op1 && LL.getValueType().isInteger() &&
2863 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2864 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2865 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2866 cast<ConstantSDNode>(RR)->isNullValue()))) {
2867 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2868 LL, DAG.getConstant(1, LL.getValueType()));
2869 AddToWorklist(ADDNode.getNode());
2870 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2871 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2873 // canonicalize equivalent to ll == rl
2874 if (LL == RR && LR == RL) {
2875 Op1 = ISD::getSetCCSwappedOperands(Op1);
2878 if (LL == RL && LR == RR) {
2879 bool isInteger = LL.getValueType().isInteger();
2880 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2881 if (Result != ISD::SETCC_INVALID &&
2882 (!LegalOperations ||
2883 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2884 TLI.isOperationLegal(ISD::SETCC,
2885 getSetCCResultType(N0.getSimpleValueType())))))
2886 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2891 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2892 if (N0.getOpcode() == N1.getOpcode()) {
2893 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2894 if (Tmp.getNode()) return Tmp;
2897 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2898 // fold (and (sra)) -> (and (srl)) when possible.
2899 if (!VT.isVector() &&
2900 SimplifyDemandedBits(SDValue(N, 0)))
2901 return SDValue(N, 0);
2903 // fold (zext_inreg (extload x)) -> (zextload x)
2904 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2905 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2906 EVT MemVT = LN0->getMemoryVT();
2907 // If we zero all the possible extended bits, then we can turn this into
2908 // a zextload if we are running before legalize or the operation is legal.
2909 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2910 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2911 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2912 ((!LegalOperations && !LN0->isVolatile()) ||
2913 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2914 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2915 LN0->getChain(), LN0->getBasePtr(),
2916 MemVT, LN0->getMemOperand());
2918 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2919 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2922 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2923 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2925 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2926 EVT MemVT = LN0->getMemoryVT();
2927 // If we zero all the possible extended bits, then we can turn this into
2928 // a zextload if we are running before legalize or the operation is legal.
2929 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2930 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2931 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2932 ((!LegalOperations && !LN0->isVolatile()) ||
2933 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2934 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2935 LN0->getChain(), LN0->getBasePtr(),
2936 MemVT, LN0->getMemOperand());
2938 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2939 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2943 // fold (and (load x), 255) -> (zextload x, i8)
2944 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2945 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2946 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2947 (N0.getOpcode() == ISD::ANY_EXTEND &&
2948 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2949 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2950 LoadSDNode *LN0 = HasAnyExt
2951 ? cast<LoadSDNode>(N0.getOperand(0))
2952 : cast<LoadSDNode>(N0);
2953 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2954 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2955 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2956 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2957 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2958 EVT LoadedVT = LN0->getMemoryVT();
2960 if (ExtVT == LoadedVT &&
2961 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2962 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2965 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2966 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2967 LN0->getMemOperand());
2969 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2970 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2973 // Do not change the width of a volatile load.
2974 // Do not generate loads of non-round integer types since these can
2975 // be expensive (and would be wrong if the type is not byte sized).
2976 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2977 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2978 EVT PtrType = LN0->getOperand(1).getValueType();
2980 unsigned Alignment = LN0->getAlignment();
2981 SDValue NewPtr = LN0->getBasePtr();
2983 // For big endian targets, we need to add an offset to the pointer
2984 // to load the correct bytes. For little endian systems, we merely
2985 // need to read fewer bytes from the same pointer.
2986 if (TLI.isBigEndian()) {
2987 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2988 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2989 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2990 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2991 NewPtr, DAG.getConstant(PtrOff, PtrType));
2992 Alignment = MinAlign(Alignment, PtrOff);
2995 AddToWorklist(NewPtr.getNode());
2997 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2999 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3000 LN0->getChain(), NewPtr,
3001 LN0->getPointerInfo(),
3002 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3003 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3005 CombineTo(LN0, Load, Load.getValue(1));
3006 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3012 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3013 VT.getSizeInBits() <= 64) {
3014 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3015 APInt ADDC = ADDI->getAPIntValue();
3016 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3017 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3018 // immediate for an add, but it is legal if its top c2 bits are set,
3019 // transform the ADD so the immediate doesn't need to be materialized
3021 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3022 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3023 SRLI->getZExtValue());
3024 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3026 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3028 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3029 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3030 CombineTo(N0.getNode(), NewAdd);
3031 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3039 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3040 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3041 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3042 N0.getOperand(1), false);
3043 if (BSwap.getNode())
3050 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3052 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3053 bool DemandHighBits) {
3054 if (!LegalOperations)
3057 EVT VT = N->getValueType(0);
3058 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3060 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3063 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3064 bool LookPassAnd0 = false;
3065 bool LookPassAnd1 = false;
3066 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3068 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3070 if (N0.getOpcode() == ISD::AND) {
3071 if (!N0.getNode()->hasOneUse())
3073 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3074 if (!N01C || N01C->getZExtValue() != 0xFF00)
3076 N0 = N0.getOperand(0);
3077 LookPassAnd0 = true;
3080 if (N1.getOpcode() == ISD::AND) {
3081 if (!N1.getNode()->hasOneUse())
3083 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3084 if (!N11C || N11C->getZExtValue() != 0xFF)
3086 N1 = N1.getOperand(0);
3087 LookPassAnd1 = true;
3090 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3092 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3094 if (!N0.getNode()->hasOneUse() ||
3095 !N1.getNode()->hasOneUse())
3098 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3099 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3102 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3105 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3106 SDValue N00 = N0->getOperand(0);
3107 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3108 if (!N00.getNode()->hasOneUse())
3110 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3111 if (!N001C || N001C->getZExtValue() != 0xFF)
3113 N00 = N00.getOperand(0);
3114 LookPassAnd0 = true;
3117 SDValue N10 = N1->getOperand(0);
3118 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3119 if (!N10.getNode()->hasOneUse())
3121 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3122 if (!N101C || N101C->getZExtValue() != 0xFF00)
3124 N10 = N10.getOperand(0);
3125 LookPassAnd1 = true;
3131 // Make sure everything beyond the low halfword gets set to zero since the SRL
3132 // 16 will clear the top bits.
3133 unsigned OpSizeInBits = VT.getSizeInBits();
3134 if (DemandHighBits && OpSizeInBits > 16) {
3135 // If the left-shift isn't masked out then the only way this is a bswap is
3136 // if all bits beyond the low 8 are 0. In that case the entire pattern
3137 // reduces to a left shift anyway: leave it for other parts of the combiner.
3141 // However, if the right shift isn't masked out then it might be because
3142 // it's not needed. See if we can spot that too.
3143 if (!LookPassAnd1 &&
3144 !DAG.MaskedValueIsZero(
3145 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3149 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3150 if (OpSizeInBits > 16)
3151 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3152 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3156 /// isBSwapHWordElement - Return true if the specified node is an element
3157 /// that makes up a 32-bit packed halfword byteswap. i.e.
3158 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3159 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3160 if (!N.getNode()->hasOneUse())
3163 unsigned Opc = N.getOpcode();
3164 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3167 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3172 switch (N1C->getZExtValue()) {
3175 case 0xFF: Num = 0; break;
3176 case 0xFF00: Num = 1; break;
3177 case 0xFF0000: Num = 2; break;
3178 case 0xFF000000: Num = 3; break;
3181 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3182 SDValue N0 = N.getOperand(0);
3183 if (Opc == ISD::AND) {
3184 if (Num == 0 || Num == 2) {
3186 // (x >> 8) & 0xff0000
3187 if (N0.getOpcode() != ISD::SRL)
3189 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3190 if (!C || C->getZExtValue() != 8)
3193 // (x << 8) & 0xff00
3194 // (x << 8) & 0xff000000
3195 if (N0.getOpcode() != ISD::SHL)
3197 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3198 if (!C || C->getZExtValue() != 8)
3201 } else if (Opc == ISD::SHL) {
3203 // (x & 0xff0000) << 8
3204 if (Num != 0 && Num != 2)
3206 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3207 if (!C || C->getZExtValue() != 8)
3209 } else { // Opc == ISD::SRL
3210 // (x & 0xff00) >> 8
3211 // (x & 0xff000000) >> 8
3212 if (Num != 1 && Num != 3)
3214 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3215 if (!C || C->getZExtValue() != 8)
3222 Parts[Num] = N0.getOperand(0).getNode();
3226 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3227 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3228 /// => (rotl (bswap x), 16)
3229 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3230 if (!LegalOperations)
3233 EVT VT = N->getValueType(0);
3236 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3239 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3241 // (or (or (and), (and)), (or (and), (and)))
3242 // (or (or (or (and), (and)), (and)), (and))
3243 if (N0.getOpcode() != ISD::OR)
3245 SDValue N00 = N0.getOperand(0);
3246 SDValue N01 = N0.getOperand(1);
3248 if (N1.getOpcode() == ISD::OR &&
3249 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3250 // (or (or (and), (and)), (or (and), (and)))
3251 SDValue N000 = N00.getOperand(0);
3252 if (!isBSwapHWordElement(N000, Parts))
3255 SDValue N001 = N00.getOperand(1);
3256 if (!isBSwapHWordElement(N001, Parts))
3258 SDValue N010 = N01.getOperand(0);
3259 if (!isBSwapHWordElement(N010, Parts))
3261 SDValue N011 = N01.getOperand(1);
3262 if (!isBSwapHWordElement(N011, Parts))
3265 // (or (or (or (and), (and)), (and)), (and))
3266 if (!isBSwapHWordElement(N1, Parts))
3268 if (!isBSwapHWordElement(N01, Parts))
3270 if (N00.getOpcode() != ISD::OR)
3272 SDValue N000 = N00.getOperand(0);
3273 if (!isBSwapHWordElement(N000, Parts))
3275 SDValue N001 = N00.getOperand(1);
3276 if (!isBSwapHWordElement(N001, Parts))
3280 // Make sure the parts are all coming from the same node.
3281 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3284 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3285 SDValue(Parts[0],0));
3287 // Result of the bswap should be rotated by 16. If it's not legal, then
3288 // do (x << 16) | (x >> 16).
3289 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3290 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3291 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3292 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3293 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3294 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3295 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3296 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3299 SDValue DAGCombiner::visitOR(SDNode *N) {
3300 SDValue N0 = N->getOperand(0);
3301 SDValue N1 = N->getOperand(1);
3302 SDValue LL, LR, RL, RR, CC0, CC1;
3303 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3304 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3305 EVT VT = N1.getValueType();
3308 if (VT.isVector()) {
3309 SDValue FoldedVOp = SimplifyVBinOp(N);
3310 if (FoldedVOp.getNode()) return FoldedVOp;
3312 // fold (or x, 0) -> x, vector edition
3313 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3315 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3318 // fold (or x, -1) -> -1, vector edition
3319 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3321 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3324 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3325 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3326 // Do this only if the resulting shuffle is legal.
3327 if (isa<ShuffleVectorSDNode>(N0) &&
3328 isa<ShuffleVectorSDNode>(N1) &&
3329 // Avoid folding a node with illegal type.
3330 TLI.isTypeLegal(VT) &&
3331 N0->getOperand(1) == N1->getOperand(1) &&
3332 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3333 bool CanFold = true;
3334 unsigned NumElts = VT.getVectorNumElements();
3335 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3336 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3337 // We construct two shuffle masks:
3338 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3339 // and N1 as the second operand.
3340 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3341 // and N0 as the second operand.
3342 // We do this because OR is commutable and therefore there might be
3343 // two ways to fold this node into a shuffle.
3344 SmallVector<int,4> Mask1;
3345 SmallVector<int,4> Mask2;
3347 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3348 int M0 = SV0->getMaskElt(i);
3349 int M1 = SV1->getMaskElt(i);
3351 // Both shuffle indexes are undef. Propagate Undef.
3352 if (M0 < 0 && M1 < 0) {
3353 Mask1.push_back(M0);
3354 Mask2.push_back(M0);
3358 if (M0 < 0 || M1 < 0 ||
3359 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3360 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3365 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3366 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3370 // Fold this sequence only if the resulting shuffle is 'legal'.
3371 if (TLI.isShuffleMaskLegal(Mask1, VT))
3372 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3373 N1->getOperand(0), &Mask1[0]);
3374 if (TLI.isShuffleMaskLegal(Mask2, VT))
3375 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3376 N0->getOperand(0), &Mask2[0]);
3381 // fold (or x, undef) -> -1
3382 if (!LegalOperations &&
3383 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3384 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3385 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3387 // fold (or c1, c2) -> c1|c2
3389 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3390 // canonicalize constant to RHS
3392 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3393 // fold (or x, 0) -> x
3394 if (N1C && N1C->isNullValue())
3396 // fold (or x, -1) -> -1
3397 if (N1C && N1C->isAllOnesValue())
3399 // fold (or x, c) -> c iff (x & ~c) == 0
3400 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3403 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3404 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3405 if (BSwap.getNode())
3407 BSwap = MatchBSwapHWordLow(N, N0, N1);
3408 if (BSwap.getNode())
3412 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3415 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3416 // iff (c1 & c2) == 0.
3417 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3418 isa<ConstantSDNode>(N0.getOperand(1))) {
3419 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3420 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3421 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3424 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3425 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3426 N0.getOperand(0), N1), COR);
3429 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3430 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3431 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3432 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3434 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3435 LL.getValueType().isInteger()) {
3436 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3437 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3438 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3439 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3440 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3441 LR.getValueType(), LL, RL);
3442 AddToWorklist(ORNode.getNode());
3443 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3445 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3446 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3447 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3448 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3449 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3450 LR.getValueType(), LL, RL);
3451 AddToWorklist(ANDNode.getNode());
3452 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3455 // canonicalize equivalent to ll == rl
3456 if (LL == RR && LR == RL) {
3457 Op1 = ISD::getSetCCSwappedOperands(Op1);
3460 if (LL == RL && LR == RR) {
3461 bool isInteger = LL.getValueType().isInteger();
3462 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3463 if (Result != ISD::SETCC_INVALID &&
3464 (!LegalOperations ||
3465 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3466 TLI.isOperationLegal(ISD::SETCC,
3467 getSetCCResultType(N0.getValueType())))))
3468 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3473 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3474 if (N0.getOpcode() == N1.getOpcode()) {
3475 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3476 if (Tmp.getNode()) return Tmp;
3479 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3480 if (N0.getOpcode() == ISD::AND &&
3481 N1.getOpcode() == ISD::AND &&
3482 N0.getOperand(1).getOpcode() == ISD::Constant &&
3483 N1.getOperand(1).getOpcode() == ISD::Constant &&
3484 // Don't increase # computations.
3485 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3486 // We can only do this xform if we know that bits from X that are set in C2
3487 // but not in C1 are already zero. Likewise for Y.
3488 const APInt &LHSMask =
3489 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3490 const APInt &RHSMask =
3491 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3493 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3494 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3495 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3496 N0.getOperand(0), N1.getOperand(0));
3497 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3498 DAG.getConstant(LHSMask | RHSMask, VT));
3502 // See if this is some rotate idiom.
3503 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3504 return SDValue(Rot, 0);
3506 // Simplify the operands using demanded-bits information.
3507 if (!VT.isVector() &&
3508 SimplifyDemandedBits(SDValue(N, 0)))
3509 return SDValue(N, 0);
3514 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3515 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3516 if (Op.getOpcode() == ISD::AND) {
3517 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3518 Mask = Op.getOperand(1);
3519 Op = Op.getOperand(0);
3525 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3533 // Return true if we can prove that, whenever Neg and Pos are both in the
3534 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3535 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3537 // (or (shift1 X, Neg), (shift2 X, Pos))
3539 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3540 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3541 // to consider shift amounts with defined behavior.
3542 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3543 // If OpSize is a power of 2 then:
3545 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3546 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3548 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3549 // for the stronger condition:
3551 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3553 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3554 // we can just replace Neg with Neg' for the rest of the function.
3556 // In other cases we check for the even stronger condition:
3558 // Neg == OpSize - Pos [B]
3560 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3561 // behavior if Pos == 0 (and consequently Neg == OpSize).
3563 // We could actually use [A] whenever OpSize is a power of 2, but the
3564 // only extra cases that it would match are those uninteresting ones
3565 // where Neg and Pos are never in range at the same time. E.g. for
3566 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3567 // as well as (sub 32, Pos), but:
3569 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3571 // always invokes undefined behavior for 32-bit X.
3573 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3574 unsigned MaskLoBits = 0;
3575 if (Neg.getOpcode() == ISD::AND &&
3576 isPowerOf2_64(OpSize) &&
3577 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3578 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3579 Neg = Neg.getOperand(0);
3580 MaskLoBits = Log2_64(OpSize);
3583 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3584 if (Neg.getOpcode() != ISD::SUB)
3586 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3589 SDValue NegOp1 = Neg.getOperand(1);
3591 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3592 // Pos'. The truncation is redundant for the purpose of the equality.
3594 Pos.getOpcode() == ISD::AND &&
3595 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3596 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3597 Pos = Pos.getOperand(0);
3599 // The condition we need is now:
3601 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3603 // If NegOp1 == Pos then we need:
3605 // OpSize & Mask == NegC & Mask
3607 // (because "x & Mask" is a truncation and distributes through subtraction).
3610 Width = NegC->getAPIntValue();
3611 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3612 // Then the condition we want to prove becomes:
3614 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3616 // which, again because "x & Mask" is a truncation, becomes:
3618 // NegC & Mask == (OpSize - PosC) & Mask
3619 // OpSize & Mask == (NegC + PosC) & Mask
3620 else if (Pos.getOpcode() == ISD::ADD &&
3621 Pos.getOperand(0) == NegOp1 &&
3622 Pos.getOperand(1).getOpcode() == ISD::Constant)
3623 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3624 NegC->getAPIntValue());
3628 // Now we just need to check that OpSize & Mask == Width & Mask.
3630 // Opsize & Mask is 0 since Mask is Opsize - 1.
3631 return Width.getLoBits(MaskLoBits) == 0;
3632 return Width == OpSize;
3635 // A subroutine of MatchRotate used once we have found an OR of two opposite
3636 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3637 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3638 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3639 // Neg with outer conversions stripped away.
3640 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3641 SDValue Neg, SDValue InnerPos,
3642 SDValue InnerNeg, unsigned PosOpcode,
3643 unsigned NegOpcode, SDLoc DL) {
3644 // fold (or (shl x, (*ext y)),
3645 // (srl x, (*ext (sub 32, y)))) ->
3646 // (rotl x, y) or (rotr x, (sub 32, y))
3648 // fold (or (shl x, (*ext (sub 32, y))),
3649 // (srl x, (*ext y))) ->
3650 // (rotr x, y) or (rotl x, (sub 32, y))
3651 EVT VT = Shifted.getValueType();
3652 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3653 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3654 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3655 HasPos ? Pos : Neg).getNode();
3661 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3662 // idioms for rotate, and if the target supports rotation instructions, generate
3664 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3665 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3666 EVT VT = LHS.getValueType();
3667 if (!TLI.isTypeLegal(VT)) return nullptr;
3669 // The target must have at least one rotate flavor.
3670 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3671 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3672 if (!HasROTL && !HasROTR) return nullptr;
3674 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3675 SDValue LHSShift; // The shift.
3676 SDValue LHSMask; // AND value if any.
3677 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3678 return nullptr; // Not part of a rotate.
3680 SDValue RHSShift; // The shift.
3681 SDValue RHSMask; // AND value if any.
3682 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3683 return nullptr; // Not part of a rotate.
3685 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3686 return nullptr; // Not shifting the same value.
3688 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3689 return nullptr; // Shifts must disagree.
3691 // Canonicalize shl to left side in a shl/srl pair.
3692 if (RHSShift.getOpcode() == ISD::SHL) {
3693 std::swap(LHS, RHS);
3694 std::swap(LHSShift, RHSShift);
3695 std::swap(LHSMask , RHSMask );
3698 unsigned OpSizeInBits = VT.getSizeInBits();
3699 SDValue LHSShiftArg = LHSShift.getOperand(0);
3700 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3701 SDValue RHSShiftArg = RHSShift.getOperand(0);
3702 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3704 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3705 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3706 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3707 RHSShiftAmt.getOpcode() == ISD::Constant) {
3708 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3709 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3710 if ((LShVal + RShVal) != OpSizeInBits)
3713 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3714 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3716 // If there is an AND of either shifted operand, apply it to the result.
3717 if (LHSMask.getNode() || RHSMask.getNode()) {
3718 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3720 if (LHSMask.getNode()) {
3721 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3722 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3724 if (RHSMask.getNode()) {
3725 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3726 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3729 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3732 return Rot.getNode();
3735 // If there is a mask here, and we have a variable shift, we can't be sure
3736 // that we're masking out the right stuff.
3737 if (LHSMask.getNode() || RHSMask.getNode())
3740 // If the shift amount is sign/zext/any-extended just peel it off.
3741 SDValue LExtOp0 = LHSShiftAmt;
3742 SDValue RExtOp0 = RHSShiftAmt;
3743 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3744 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3745 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3746 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3747 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3748 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3749 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3750 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3751 LExtOp0 = LHSShiftAmt.getOperand(0);
3752 RExtOp0 = RHSShiftAmt.getOperand(0);
3755 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3756 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3760 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3761 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3768 SDValue DAGCombiner::visitXOR(SDNode *N) {
3769 SDValue N0 = N->getOperand(0);
3770 SDValue N1 = N->getOperand(1);
3771 SDValue LHS, RHS, CC;
3772 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3773 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3774 EVT VT = N0.getValueType();
3777 if (VT.isVector()) {
3778 SDValue FoldedVOp = SimplifyVBinOp(N);
3779 if (FoldedVOp.getNode()) return FoldedVOp;
3781 // fold (xor x, 0) -> x, vector edition
3782 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3784 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3788 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3789 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3790 return DAG.getConstant(0, VT);
3791 // fold (xor x, undef) -> undef
3792 if (N0.getOpcode() == ISD::UNDEF)
3794 if (N1.getOpcode() == ISD::UNDEF)
3796 // fold (xor c1, c2) -> c1^c2
3798 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3799 // canonicalize constant to RHS
3801 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3802 // fold (xor x, 0) -> x
3803 if (N1C && N1C->isNullValue())
3806 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3810 // fold !(x cc y) -> (x !cc y)
3811 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3812 bool isInt = LHS.getValueType().isInteger();
3813 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3816 if (!LegalOperations ||
3817 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3818 switch (N0.getOpcode()) {
3820 llvm_unreachable("Unhandled SetCC Equivalent!");
3822 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3823 case ISD::SELECT_CC:
3824 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3825 N0.getOperand(3), NotCC);
3830 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3831 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3832 N0.getNode()->hasOneUse() &&
3833 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3834 SDValue V = N0.getOperand(0);
3835 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3836 DAG.getConstant(1, V.getValueType()));
3837 AddToWorklist(V.getNode());
3838 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3841 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3842 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3843 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3844 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3845 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3846 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3847 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3848 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3849 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3850 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3853 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3854 if (N1C && N1C->isAllOnesValue() &&
3855 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3856 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3857 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3858 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3859 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3860 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3861 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3862 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3865 // fold (xor (and x, y), y) -> (and (not x), y)
3866 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3867 N0->getOperand(1) == N1) {
3868 SDValue X = N0->getOperand(0);
3869 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3870 AddToWorklist(NotX.getNode());
3871 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3873 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3874 if (N1C && N0.getOpcode() == ISD::XOR) {
3875 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3876 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3878 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3879 DAG.getConstant(N1C->getAPIntValue() ^
3880 N00C->getAPIntValue(), VT));
3882 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3883 DAG.getConstant(N1C->getAPIntValue() ^
3884 N01C->getAPIntValue(), VT));
3886 // fold (xor x, x) -> 0
3888 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3890 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3891 if (N0.getOpcode() == N1.getOpcode()) {
3892 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3893 if (Tmp.getNode()) return Tmp;
3896 // Simplify the expression using non-local knowledge.
3897 if (!VT.isVector() &&
3898 SimplifyDemandedBits(SDValue(N, 0)))
3899 return SDValue(N, 0);
3904 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3905 /// the shift amount is a constant.
3906 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3907 // We can't and shouldn't fold opaque constants.
3908 if (Amt->isOpaque())
3911 SDNode *LHS = N->getOperand(0).getNode();
3912 if (!LHS->hasOneUse()) return SDValue();
3914 // We want to pull some binops through shifts, so that we have (and (shift))
3915 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3916 // thing happens with address calculations, so it's important to canonicalize
3918 bool HighBitSet = false; // Can we transform this if the high bit is set?
3920 switch (LHS->getOpcode()) {
3921 default: return SDValue();
3924 HighBitSet = false; // We can only transform sra if the high bit is clear.
3927 HighBitSet = true; // We can only transform sra if the high bit is set.
3930 if (N->getOpcode() != ISD::SHL)
3931 return SDValue(); // only shl(add) not sr[al](add).
3932 HighBitSet = false; // We can only transform sra if the high bit is clear.
3936 // We require the RHS of the binop to be a constant and not opaque as well.
3937 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3938 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3940 // FIXME: disable this unless the input to the binop is a shift by a constant.
3941 // If it is not a shift, it pessimizes some common cases like:
3943 // void foo(int *X, int i) { X[i & 1235] = 1; }
3944 // int bar(int *X, int i) { return X[i & 255]; }
3945 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3946 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3947 BinOpLHSVal->getOpcode() != ISD::SRA &&
3948 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3949 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3952 EVT VT = N->getValueType(0);
3954 // If this is a signed shift right, and the high bit is modified by the
3955 // logical operation, do not perform the transformation. The highBitSet
3956 // boolean indicates the value of the high bit of the constant which would
3957 // cause it to be modified for this operation.
3958 if (N->getOpcode() == ISD::SRA) {
3959 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3960 if (BinOpRHSSignSet != HighBitSet)
3964 if (!TLI.isDesirableToCommuteWithShift(LHS))
3967 // Fold the constants, shifting the binop RHS by the shift amount.
3968 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3970 LHS->getOperand(1), N->getOperand(1));
3971 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3973 // Create the new shift.
3974 SDValue NewShift = DAG.getNode(N->getOpcode(),
3975 SDLoc(LHS->getOperand(0)),
3976 VT, LHS->getOperand(0), N->getOperand(1));
3978 // Create the new binop.
3979 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3982 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3983 assert(N->getOpcode() == ISD::TRUNCATE);
3984 assert(N->getOperand(0).getOpcode() == ISD::AND);
3986 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3987 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3988 SDValue N01 = N->getOperand(0).getOperand(1);
3990 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3991 EVT TruncVT = N->getValueType(0);
3992 SDValue N00 = N->getOperand(0).getOperand(0);
3993 APInt TruncC = N01C->getAPIntValue();
3994 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3996 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3997 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3998 DAG.getConstant(TruncC, TruncVT));
4005 SDValue DAGCombiner::visitRotate(SDNode *N) {
4006 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4007 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4008 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4009 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4010 if (NewOp1.getNode())
4011 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4012 N->getOperand(0), NewOp1);
4017 SDValue DAGCombiner::visitSHL(SDNode *N) {
4018 SDValue N0 = N->getOperand(0);
4019 SDValue N1 = N->getOperand(1);
4020 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4021 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4022 EVT VT = N0.getValueType();
4023 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4026 if (VT.isVector()) {
4027 SDValue FoldedVOp = SimplifyVBinOp(N);
4028 if (FoldedVOp.getNode()) return FoldedVOp;
4030 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4031 // If setcc produces all-one true value then:
4032 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4033 if (N1CV && N1CV->isConstant()) {
4034 if (N0.getOpcode() == ISD::AND) {
4035 SDValue N00 = N0->getOperand(0);
4036 SDValue N01 = N0->getOperand(1);
4037 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4039 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4040 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4041 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4042 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4044 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4047 N1C = isConstOrConstSplat(N1);
4052 // fold (shl c1, c2) -> c1<<c2
4054 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4055 // fold (shl 0, x) -> 0
4056 if (N0C && N0C->isNullValue())
4058 // fold (shl x, c >= size(x)) -> undef
4059 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4060 return DAG.getUNDEF(VT);
4061 // fold (shl x, 0) -> x
4062 if (N1C && N1C->isNullValue())
4064 // fold (shl undef, x) -> 0
4065 if (N0.getOpcode() == ISD::UNDEF)
4066 return DAG.getConstant(0, VT);
4067 // if (shl x, c) is known to be zero, return 0
4068 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4069 APInt::getAllOnesValue(OpSizeInBits)))
4070 return DAG.getConstant(0, VT);
4071 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4072 if (N1.getOpcode() == ISD::TRUNCATE &&
4073 N1.getOperand(0).getOpcode() == ISD::AND) {
4074 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4075 if (NewOp1.getNode())
4076 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4079 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4080 return SDValue(N, 0);
4082 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4083 if (N1C && N0.getOpcode() == ISD::SHL) {
4084 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4085 uint64_t c1 = N0C1->getZExtValue();
4086 uint64_t c2 = N1C->getZExtValue();
4087 if (c1 + c2 >= OpSizeInBits)
4088 return DAG.getConstant(0, VT);
4089 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4090 DAG.getConstant(c1 + c2, N1.getValueType()));
4094 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4095 // For this to be valid, the second form must not preserve any of the bits
4096 // that are shifted out by the inner shift in the first form. This means
4097 // the outer shift size must be >= the number of bits added by the ext.
4098 // As a corollary, we don't care what kind of ext it is.
4099 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4100 N0.getOpcode() == ISD::ANY_EXTEND ||
4101 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4102 N0.getOperand(0).getOpcode() == ISD::SHL) {
4103 SDValue N0Op0 = N0.getOperand(0);
4104 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4105 uint64_t c1 = N0Op0C1->getZExtValue();
4106 uint64_t c2 = N1C->getZExtValue();
4107 EVT InnerShiftVT = N0Op0.getValueType();
4108 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4109 if (c2 >= OpSizeInBits - InnerShiftSize) {
4110 if (c1 + c2 >= OpSizeInBits)
4111 return DAG.getConstant(0, VT);
4112 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4113 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4114 N0Op0->getOperand(0)),
4115 DAG.getConstant(c1 + c2, N1.getValueType()));
4120 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4121 // Only fold this if the inner zext has no other uses to avoid increasing
4122 // the total number of instructions.
4123 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4124 N0.getOperand(0).getOpcode() == ISD::SRL) {
4125 SDValue N0Op0 = N0.getOperand(0);
4126 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4127 uint64_t c1 = N0Op0C1->getZExtValue();
4128 if (c1 < VT.getScalarSizeInBits()) {
4129 uint64_t c2 = N1C->getZExtValue();
4131 SDValue NewOp0 = N0.getOperand(0);
4132 EVT CountVT = NewOp0.getOperand(1).getValueType();
4133 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4134 NewOp0, DAG.getConstant(c2, CountVT));
4135 AddToWorklist(NewSHL.getNode());
4136 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4142 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4143 // (and (srl x, (sub c1, c2), MASK)
4144 // Only fold this if the inner shift has no other uses -- if it does, folding
4145 // this will increase the total number of instructions.
4146 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4147 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4148 uint64_t c1 = N0C1->getZExtValue();
4149 if (c1 < OpSizeInBits) {
4150 uint64_t c2 = N1C->getZExtValue();
4151 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4154 Mask = Mask.shl(c2 - c1);
4155 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4156 DAG.getConstant(c2 - c1, N1.getValueType()));
4158 Mask = Mask.lshr(c1 - c2);
4159 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4160 DAG.getConstant(c1 - c2, N1.getValueType()));
4162 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4163 DAG.getConstant(Mask, VT));
4167 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4168 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4169 unsigned BitSize = VT.getScalarSizeInBits();
4170 SDValue HiBitsMask =
4171 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4172 BitSize - N1C->getZExtValue()), VT);
4173 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4178 SDValue NewSHL = visitShiftByConstant(N, N1C);
4179 if (NewSHL.getNode())
4186 SDValue DAGCombiner::visitSRA(SDNode *N) {
4187 SDValue N0 = N->getOperand(0);
4188 SDValue N1 = N->getOperand(1);
4189 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4190 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4191 EVT VT = N0.getValueType();
4192 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4195 if (VT.isVector()) {
4196 SDValue FoldedVOp = SimplifyVBinOp(N);
4197 if (FoldedVOp.getNode()) return FoldedVOp;
4199 N1C = isConstOrConstSplat(N1);
4202 // fold (sra c1, c2) -> (sra c1, c2)
4204 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4205 // fold (sra 0, x) -> 0
4206 if (N0C && N0C->isNullValue())
4208 // fold (sra -1, x) -> -1
4209 if (N0C && N0C->isAllOnesValue())
4211 // fold (sra x, (setge c, size(x))) -> undef
4212 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4213 return DAG.getUNDEF(VT);
4214 // fold (sra x, 0) -> x
4215 if (N1C && N1C->isNullValue())
4217 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4219 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4220 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4221 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4223 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4224 ExtVT, VT.getVectorNumElements());
4225 if ((!LegalOperations ||
4226 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4227 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4228 N0.getOperand(0), DAG.getValueType(ExtVT));
4231 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4232 if (N1C && N0.getOpcode() == ISD::SRA) {
4233 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4234 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4235 if (Sum >= OpSizeInBits)
4236 Sum = OpSizeInBits - 1;
4237 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4238 DAG.getConstant(Sum, N1.getValueType()));
4242 // fold (sra (shl X, m), (sub result_size, n))
4243 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4244 // result_size - n != m.
4245 // If truncate is free for the target sext(shl) is likely to result in better
4247 if (N0.getOpcode() == ISD::SHL && N1C) {
4248 // Get the two constanst of the shifts, CN0 = m, CN = n.
4249 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4251 LLVMContext &Ctx = *DAG.getContext();
4252 // Determine what the truncate's result bitsize and type would be.
4253 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4256 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4258 // Determine the residual right-shift amount.
4259 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4261 // If the shift is not a no-op (in which case this should be just a sign
4262 // extend already), the truncated to type is legal, sign_extend is legal
4263 // on that type, and the truncate to that type is both legal and free,
4264 // perform the transform.
4265 if ((ShiftAmt > 0) &&
4266 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4267 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4268 TLI.isTruncateFree(VT, TruncVT)) {
4270 SDValue Amt = DAG.getConstant(ShiftAmt,
4271 getShiftAmountTy(N0.getOperand(0).getValueType()));
4272 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4273 N0.getOperand(0), Amt);
4274 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4276 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4277 N->getValueType(0), Trunc);
4282 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4283 if (N1.getOpcode() == ISD::TRUNCATE &&
4284 N1.getOperand(0).getOpcode() == ISD::AND) {
4285 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4286 if (NewOp1.getNode())
4287 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4290 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4291 // if c1 is equal to the number of bits the trunc removes
4292 if (N0.getOpcode() == ISD::TRUNCATE &&
4293 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4294 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4295 N0.getOperand(0).hasOneUse() &&
4296 N0.getOperand(0).getOperand(1).hasOneUse() &&
4298 SDValue N0Op0 = N0.getOperand(0);
4299 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4300 unsigned LargeShiftVal = LargeShift->getZExtValue();
4301 EVT LargeVT = N0Op0.getValueType();
4303 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4305 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4306 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4307 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4308 N0Op0.getOperand(0), Amt);
4309 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4314 // Simplify, based on bits shifted out of the LHS.
4315 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4316 return SDValue(N, 0);
4319 // If the sign bit is known to be zero, switch this to a SRL.
4320 if (DAG.SignBitIsZero(N0))
4321 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4324 SDValue NewSRA = visitShiftByConstant(N, N1C);
4325 if (NewSRA.getNode())
4332 SDValue DAGCombiner::visitSRL(SDNode *N) {
4333 SDValue N0 = N->getOperand(0);
4334 SDValue N1 = N->getOperand(1);
4335 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4336 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4337 EVT VT = N0.getValueType();
4338 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4341 if (VT.isVector()) {
4342 SDValue FoldedVOp = SimplifyVBinOp(N);
4343 if (FoldedVOp.getNode()) return FoldedVOp;
4345 N1C = isConstOrConstSplat(N1);
4348 // fold (srl c1, c2) -> c1 >>u c2
4350 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4351 // fold (srl 0, x) -> 0
4352 if (N0C && N0C->isNullValue())
4354 // fold (srl x, c >= size(x)) -> undef
4355 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4356 return DAG.getUNDEF(VT);
4357 // fold (srl x, 0) -> x
4358 if (N1C && N1C->isNullValue())
4360 // if (srl x, c) is known to be zero, return 0
4361 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4362 APInt::getAllOnesValue(OpSizeInBits)))
4363 return DAG.getConstant(0, VT);
4365 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4366 if (N1C && N0.getOpcode() == ISD::SRL) {
4367 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4368 uint64_t c1 = N01C->getZExtValue();
4369 uint64_t c2 = N1C->getZExtValue();
4370 if (c1 + c2 >= OpSizeInBits)
4371 return DAG.getConstant(0, VT);
4372 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4373 DAG.getConstant(c1 + c2, N1.getValueType()));
4377 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4378 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4379 N0.getOperand(0).getOpcode() == ISD::SRL &&
4380 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4382 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4383 uint64_t c2 = N1C->getZExtValue();
4384 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4385 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4386 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4387 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4388 if (c1 + OpSizeInBits == InnerShiftSize) {
4389 if (c1 + c2 >= InnerShiftSize)
4390 return DAG.getConstant(0, VT);
4391 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4392 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4393 N0.getOperand(0)->getOperand(0),
4394 DAG.getConstant(c1 + c2, ShiftCountVT)));
4398 // fold (srl (shl x, c), c) -> (and x, cst2)
4399 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4400 unsigned BitSize = N0.getScalarValueSizeInBits();
4401 if (BitSize <= 64) {
4402 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4403 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4404 DAG.getConstant(~0ULL >> ShAmt, VT));
4408 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4409 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4410 // Shifting in all undef bits?
4411 EVT SmallVT = N0.getOperand(0).getValueType();
4412 unsigned BitSize = SmallVT.getScalarSizeInBits();
4413 if (N1C->getZExtValue() >= BitSize)
4414 return DAG.getUNDEF(VT);
4416 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4417 uint64_t ShiftAmt = N1C->getZExtValue();
4418 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4420 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4421 AddToWorklist(SmallShift.getNode());
4422 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4423 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4424 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4425 DAG.getConstant(Mask, VT));
4429 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4430 // bit, which is unmodified by sra.
4431 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4432 if (N0.getOpcode() == ISD::SRA)
4433 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4436 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4437 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4438 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4439 APInt KnownZero, KnownOne;
4440 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4442 // If any of the input bits are KnownOne, then the input couldn't be all
4443 // zeros, thus the result of the srl will always be zero.
4444 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4446 // If all of the bits input the to ctlz node are known to be zero, then
4447 // the result of the ctlz is "32" and the result of the shift is one.
4448 APInt UnknownBits = ~KnownZero;
4449 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4451 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4452 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4453 // Okay, we know that only that the single bit specified by UnknownBits
4454 // could be set on input to the CTLZ node. If this bit is set, the SRL
4455 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4456 // to an SRL/XOR pair, which is likely to simplify more.
4457 unsigned ShAmt = UnknownBits.countTrailingZeros();
4458 SDValue Op = N0.getOperand(0);
4461 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4462 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4463 AddToWorklist(Op.getNode());
4466 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4467 Op, DAG.getConstant(1, VT));
4471 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4472 if (N1.getOpcode() == ISD::TRUNCATE &&
4473 N1.getOperand(0).getOpcode() == ISD::AND) {
4474 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4475 if (NewOp1.getNode())
4476 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4479 // fold operands of srl based on knowledge that the low bits are not
4481 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4482 return SDValue(N, 0);
4485 SDValue NewSRL = visitShiftByConstant(N, N1C);
4486 if (NewSRL.getNode())
4490 // Attempt to convert a srl of a load into a narrower zero-extending load.
4491 SDValue NarrowLoad = ReduceLoadWidth(N);
4492 if (NarrowLoad.getNode())
4495 // Here is a common situation. We want to optimize:
4498 // %b = and i32 %a, 2
4499 // %c = srl i32 %b, 1
4500 // brcond i32 %c ...
4506 // %c = setcc eq %b, 0
4509 // However when after the source operand of SRL is optimized into AND, the SRL
4510 // itself may not be optimized further. Look for it and add the BRCOND into
4512 if (N->hasOneUse()) {
4513 SDNode *Use = *N->use_begin();
4514 if (Use->getOpcode() == ISD::BRCOND)
4516 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4517 // Also look pass the truncate.
4518 Use = *Use->use_begin();
4519 if (Use->getOpcode() == ISD::BRCOND)
4527 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4528 SDValue N0 = N->getOperand(0);
4529 EVT VT = N->getValueType(0);
4531 // fold (ctlz c1) -> c2
4532 if (isa<ConstantSDNode>(N0))
4533 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4537 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4538 SDValue N0 = N->getOperand(0);
4539 EVT VT = N->getValueType(0);
4541 // fold (ctlz_zero_undef c1) -> c2
4542 if (isa<ConstantSDNode>(N0))
4543 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4547 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4548 SDValue N0 = N->getOperand(0);
4549 EVT VT = N->getValueType(0);
4551 // fold (cttz c1) -> c2
4552 if (isa<ConstantSDNode>(N0))
4553 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4557 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4558 SDValue N0 = N->getOperand(0);
4559 EVT VT = N->getValueType(0);
4561 // fold (cttz_zero_undef c1) -> c2
4562 if (isa<ConstantSDNode>(N0))
4563 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4567 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4568 SDValue N0 = N->getOperand(0);
4569 EVT VT = N->getValueType(0);
4571 // fold (ctpop c1) -> c2
4572 if (isa<ConstantSDNode>(N0))
4573 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4577 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4578 SDValue N0 = N->getOperand(0);
4579 SDValue N1 = N->getOperand(1);
4580 SDValue N2 = N->getOperand(2);
4581 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4582 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4583 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4584 EVT VT = N->getValueType(0);
4585 EVT VT0 = N0.getValueType();
4587 // fold (select C, X, X) -> X
4590 // fold (select true, X, Y) -> X
4591 if (N0C && !N0C->isNullValue())
4593 // fold (select false, X, Y) -> Y
4594 if (N0C && N0C->isNullValue())
4596 // fold (select C, 1, X) -> (or C, X)
4597 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4598 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4599 // fold (select C, 0, 1) -> (xor C, 1)
4600 // We can't do this reliably if integer based booleans have different contents
4601 // to floating point based booleans. This is because we can't tell whether we
4602 // have an integer-based boolean or a floating-point-based boolean unless we
4603 // can find the SETCC that produced it and inspect its operands. This is
4604 // fairly easy if C is the SETCC node, but it can potentially be
4605 // undiscoverable (or not reasonably discoverable). For example, it could be
4606 // in another basic block or it could require searching a complicated
4608 if (VT.isInteger() &&
4609 (VT0 == MVT::i1 || (VT0.isInteger() &&
4610 TLI.getBooleanContents(false, false) ==
4611 TLI.getBooleanContents(false, true) &&
4612 TLI.getBooleanContents(false, false) ==
4613 TargetLowering::ZeroOrOneBooleanContent)) &&
4614 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4617 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4618 N0, DAG.getConstant(1, VT0));
4619 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4620 N0, DAG.getConstant(1, VT0));
4621 AddToWorklist(XORNode.getNode());
4623 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4624 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4626 // fold (select C, 0, X) -> (and (not C), X)
4627 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4628 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4629 AddToWorklist(NOTNode.getNode());
4630 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4632 // fold (select C, X, 1) -> (or (not C), X)
4633 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4634 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4635 AddToWorklist(NOTNode.getNode());
4636 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4638 // fold (select C, X, 0) -> (and C, X)
4639 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4640 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4641 // fold (select X, X, Y) -> (or X, Y)
4642 // fold (select X, 1, Y) -> (or X, Y)
4643 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4644 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4645 // fold (select X, Y, X) -> (and X, Y)
4646 // fold (select X, Y, 0) -> (and X, Y)
4647 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4648 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4650 // If we can fold this based on the true/false value, do so.
4651 if (SimplifySelectOps(N, N1, N2))
4652 return SDValue(N, 0); // Don't revisit N.
4654 // fold selects based on a setcc into other things, such as min/max/abs
4655 if (N0.getOpcode() == ISD::SETCC) {
4656 if ((!LegalOperations &&
4657 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4658 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4659 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4660 N0.getOperand(0), N0.getOperand(1),
4661 N1, N2, N0.getOperand(2));
4662 return SimplifySelect(SDLoc(N), N0, N1, N2);
4669 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4672 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4674 // Split the inputs.
4675 SDValue Lo, Hi, LL, LH, RL, RH;
4676 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4677 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4679 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4680 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4682 return std::make_pair(Lo, Hi);
4685 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4686 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4687 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4689 SDValue Cond = N->getOperand(0);
4690 SDValue LHS = N->getOperand(1);
4691 SDValue RHS = N->getOperand(2);
4692 MVT VT = N->getSimpleValueType(0);
4693 int NumElems = VT.getVectorNumElements();
4694 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4695 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4696 Cond.getOpcode() == ISD::BUILD_VECTOR);
4698 // We're sure we have an even number of elements due to the
4699 // concat_vectors we have as arguments to vselect.
4700 // Skip BV elements until we find one that's not an UNDEF
4701 // After we find an UNDEF element, keep looping until we get to half the
4702 // length of the BV and see if all the non-undef nodes are the same.
4703 ConstantSDNode *BottomHalf = nullptr;
4704 for (int i = 0; i < NumElems / 2; ++i) {
4705 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4708 if (BottomHalf == nullptr)
4709 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4710 else if (Cond->getOperand(i).getNode() != BottomHalf)
4714 // Do the same for the second half of the BuildVector
4715 ConstantSDNode *TopHalf = nullptr;
4716 for (int i = NumElems / 2; i < NumElems; ++i) {
4717 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4720 if (TopHalf == nullptr)
4721 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4722 else if (Cond->getOperand(i).getNode() != TopHalf)
4726 assert(TopHalf && BottomHalf &&
4727 "One half of the selector was all UNDEFs and the other was all the "
4728 "same value. This should have been addressed before this function.");
4730 ISD::CONCAT_VECTORS, dl, VT,
4731 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4732 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4735 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4736 SDValue N0 = N->getOperand(0);
4737 SDValue N1 = N->getOperand(1);
4738 SDValue N2 = N->getOperand(2);
4741 // Canonicalize integer abs.
4742 // vselect (setg[te] X, 0), X, -X ->
4743 // vselect (setgt X, -1), X, -X ->
4744 // vselect (setl[te] X, 0), -X, X ->
4745 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4746 if (N0.getOpcode() == ISD::SETCC) {
4747 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4748 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4750 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4752 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4753 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4754 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4755 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4756 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4757 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4758 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4761 EVT VT = LHS.getValueType();
4762 SDValue Shift = DAG.getNode(
4763 ISD::SRA, DL, VT, LHS,
4764 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4765 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4766 AddToWorklist(Shift.getNode());
4767 AddToWorklist(Add.getNode());
4768 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4772 // If the VSELECT result requires splitting and the mask is provided by a
4773 // SETCC, then split both nodes and its operands before legalization. This
4774 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4775 // and enables future optimizations (e.g. min/max pattern matching on X86).
4776 if (N0.getOpcode() == ISD::SETCC) {
4777 EVT VT = N->getValueType(0);
4779 // Check if any splitting is required.
4780 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4781 TargetLowering::TypeSplitVector)
4784 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4785 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4786 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4787 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4789 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4790 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4792 // Add the new VSELECT nodes to the work list in case they need to be split
4794 AddToWorklist(Lo.getNode());
4795 AddToWorklist(Hi.getNode());
4797 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4800 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4801 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4803 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4804 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4807 // The ConvertSelectToConcatVector function is assuming both the above
4808 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4810 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4811 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4812 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4813 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4821 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4822 SDValue N0 = N->getOperand(0);
4823 SDValue N1 = N->getOperand(1);
4824 SDValue N2 = N->getOperand(2);
4825 SDValue N3 = N->getOperand(3);
4826 SDValue N4 = N->getOperand(4);
4827 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4829 // fold select_cc lhs, rhs, x, x, cc -> x
4833 // Determine if the condition we're dealing with is constant
4834 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4835 N0, N1, CC, SDLoc(N), false);
4836 if (SCC.getNode()) {
4837 AddToWorklist(SCC.getNode());
4839 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4840 if (!SCCC->isNullValue())
4841 return N2; // cond always true -> true val
4843 return N3; // cond always false -> false val
4846 // Fold to a simpler select_cc
4847 if (SCC.getOpcode() == ISD::SETCC)
4848 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4849 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4853 // If we can fold this based on the true/false value, do so.
4854 if (SimplifySelectOps(N, N2, N3))
4855 return SDValue(N, 0); // Don't revisit N.
4857 // fold select_cc into other things, such as min/max/abs
4858 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4861 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4862 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4863 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4867 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4868 // dag node into a ConstantSDNode or a build_vector of constants.
4869 // This function is called by the DAGCombiner when visiting sext/zext/aext
4870 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4871 // Vector extends are not folded if operations are legal; this is to
4872 // avoid introducing illegal build_vector dag nodes.
4873 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4874 SelectionDAG &DAG, bool LegalTypes,
4875 bool LegalOperations) {
4876 unsigned Opcode = N->getOpcode();
4877 SDValue N0 = N->getOperand(0);
4878 EVT VT = N->getValueType(0);
4880 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4881 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4883 // fold (sext c1) -> c1
4884 // fold (zext c1) -> c1
4885 // fold (aext c1) -> c1
4886 if (isa<ConstantSDNode>(N0))
4887 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4889 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4890 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4891 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4892 EVT SVT = VT.getScalarType();
4893 if (!(VT.isVector() &&
4894 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4895 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4898 // We can fold this node into a build_vector.
4899 unsigned VTBits = SVT.getSizeInBits();
4900 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4901 unsigned ShAmt = VTBits - EVTBits;
4902 SmallVector<SDValue, 8> Elts;
4903 unsigned NumElts = N0->getNumOperands();
4906 for (unsigned i=0; i != NumElts; ++i) {
4907 SDValue Op = N0->getOperand(i);
4908 if (Op->getOpcode() == ISD::UNDEF) {
4909 Elts.push_back(DAG.getUNDEF(SVT));
4913 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4914 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4915 if (Opcode == ISD::SIGN_EXTEND)
4916 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4919 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4923 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4926 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4927 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4928 // transformation. Returns true if extension are possible and the above
4929 // mentioned transformation is profitable.
4930 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4932 SmallVectorImpl<SDNode *> &ExtendNodes,
4933 const TargetLowering &TLI) {
4934 bool HasCopyToRegUses = false;
4935 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4936 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4937 UE = N0.getNode()->use_end();
4942 if (UI.getUse().getResNo() != N0.getResNo())
4944 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4945 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4946 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4947 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4948 // Sign bits will be lost after a zext.
4951 for (unsigned i = 0; i != 2; ++i) {
4952 SDValue UseOp = User->getOperand(i);
4955 if (!isa<ConstantSDNode>(UseOp))
4960 ExtendNodes.push_back(User);
4963 // If truncates aren't free and there are users we can't
4964 // extend, it isn't worthwhile.
4967 // Remember if this value is live-out.
4968 if (User->getOpcode() == ISD::CopyToReg)
4969 HasCopyToRegUses = true;
4972 if (HasCopyToRegUses) {
4973 bool BothLiveOut = false;
4974 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4976 SDUse &Use = UI.getUse();
4977 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4983 // Both unextended and extended values are live out. There had better be
4984 // a good reason for the transformation.
4985 return ExtendNodes.size();
4990 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4991 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4992 ISD::NodeType ExtType) {
4993 // Extend SetCC uses if necessary.
4994 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4995 SDNode *SetCC = SetCCs[i];
4996 SmallVector<SDValue, 4> Ops;
4998 for (unsigned j = 0; j != 2; ++j) {
4999 SDValue SOp = SetCC->getOperand(j);
5001 Ops.push_back(ExtLoad);
5003 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5006 Ops.push_back(SetCC->getOperand(2));
5007 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5011 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5012 SDValue N0 = N->getOperand(0);
5013 EVT VT = N->getValueType(0);
5015 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5017 return SDValue(Res, 0);
5019 // fold (sext (sext x)) -> (sext x)
5020 // fold (sext (aext x)) -> (sext x)
5021 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5022 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5025 if (N0.getOpcode() == ISD::TRUNCATE) {
5026 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5027 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5028 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5029 if (NarrowLoad.getNode()) {
5030 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5031 if (NarrowLoad.getNode() != N0.getNode()) {
5032 CombineTo(N0.getNode(), NarrowLoad);
5033 // CombineTo deleted the truncate, if needed, but not what's under it.
5036 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5039 // See if the value being truncated is already sign extended. If so, just
5040 // eliminate the trunc/sext pair.
5041 SDValue Op = N0.getOperand(0);
5042 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5043 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5044 unsigned DestBits = VT.getScalarType().getSizeInBits();
5045 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5047 if (OpBits == DestBits) {
5048 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5049 // bits, it is already ready.
5050 if (NumSignBits > DestBits-MidBits)
5052 } else if (OpBits < DestBits) {
5053 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5054 // bits, just sext from i32.
5055 if (NumSignBits > OpBits-MidBits)
5056 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5058 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5059 // bits, just truncate to i32.
5060 if (NumSignBits > OpBits-MidBits)
5061 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5064 // fold (sext (truncate x)) -> (sextinreg x).
5065 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5066 N0.getValueType())) {
5067 if (OpBits < DestBits)
5068 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5069 else if (OpBits > DestBits)
5070 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5071 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5072 DAG.getValueType(N0.getValueType()));
5076 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5077 // None of the supported targets knows how to perform load and sign extend
5078 // on vectors in one instruction. We only perform this transformation on
5080 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5081 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5082 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5083 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5084 bool DoXform = true;
5085 SmallVector<SDNode*, 4> SetCCs;
5086 if (!N0.hasOneUse())
5087 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5089 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5090 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5092 LN0->getBasePtr(), N0.getValueType(),
5093 LN0->getMemOperand());
5094 CombineTo(N, ExtLoad);
5095 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5096 N0.getValueType(), ExtLoad);
5097 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5098 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5100 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5104 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5105 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5106 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5107 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5108 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5109 EVT MemVT = LN0->getMemoryVT();
5110 if ((!LegalOperations && !LN0->isVolatile()) ||
5111 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5112 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5114 LN0->getBasePtr(), MemVT,
5115 LN0->getMemOperand());
5116 CombineTo(N, ExtLoad);
5117 CombineTo(N0.getNode(),
5118 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5119 N0.getValueType(), ExtLoad),
5120 ExtLoad.getValue(1));
5121 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5125 // fold (sext (and/or/xor (load x), cst)) ->
5126 // (and/or/xor (sextload x), (sext cst))
5127 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5128 N0.getOpcode() == ISD::XOR) &&
5129 isa<LoadSDNode>(N0.getOperand(0)) &&
5130 N0.getOperand(1).getOpcode() == ISD::Constant &&
5131 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5132 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5133 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5134 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5135 bool DoXform = true;
5136 SmallVector<SDNode*, 4> SetCCs;
5137 if (!N0.hasOneUse())
5138 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5141 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5142 LN0->getChain(), LN0->getBasePtr(),
5144 LN0->getMemOperand());
5145 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5146 Mask = Mask.sext(VT.getSizeInBits());
5147 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5148 ExtLoad, DAG.getConstant(Mask, VT));
5149 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5150 SDLoc(N0.getOperand(0)),
5151 N0.getOperand(0).getValueType(), ExtLoad);
5153 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5154 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5156 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5161 if (N0.getOpcode() == ISD::SETCC) {
5162 EVT N0VT = N0.getOperand(0).getValueType();
5163 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5164 // Only do this before legalize for now.
5165 if (VT.isVector() && !LegalOperations &&
5166 TLI.getBooleanContents(N0VT) ==
5167 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5168 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5169 // of the same size as the compared operands. Only optimize sext(setcc())
5170 // if this is the case.
5171 EVT SVT = getSetCCResultType(N0VT);
5173 // We know that the # elements of the results is the same as the
5174 // # elements of the compare (and the # elements of the compare result
5175 // for that matter). Check to see that they are the same size. If so,
5176 // we know that the element size of the sext'd result matches the
5177 // element size of the compare operands.
5178 if (VT.getSizeInBits() == SVT.getSizeInBits())
5179 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5181 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5183 // If the desired elements are smaller or larger than the source
5184 // elements we can use a matching integer vector type and then
5185 // truncate/sign extend
5186 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5187 if (SVT == MatchingVectorType) {
5188 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5189 N0.getOperand(0), N0.getOperand(1),
5190 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5191 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5195 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5196 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5198 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5200 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5201 NegOne, DAG.getConstant(0, VT),
5202 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5203 if (SCC.getNode()) return SCC;
5205 if (!VT.isVector()) {
5206 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5207 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5209 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5210 SDValue SetCC = DAG.getSetCC(DL,
5212 N0.getOperand(0), N0.getOperand(1), CC);
5213 EVT SelectVT = getSetCCResultType(VT);
5214 return DAG.getSelect(DL, VT,
5215 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5216 NegOne, DAG.getConstant(0, VT));
5222 // fold (sext x) -> (zext x) if the sign bit is known zero.
5223 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5224 DAG.SignBitIsZero(N0))
5225 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5230 // isTruncateOf - If N is a truncate of some other value, return true, record
5231 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5232 // This function computes KnownZero to avoid a duplicated call to
5233 // computeKnownBits in the caller.
5234 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5237 if (N->getOpcode() == ISD::TRUNCATE) {
5238 Op = N->getOperand(0);
5239 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5243 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5244 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5247 SDValue Op0 = N->getOperand(0);
5248 SDValue Op1 = N->getOperand(1);
5249 assert(Op0.getValueType() == Op1.getValueType());
5251 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5252 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5253 if (COp0 && COp0->isNullValue())
5255 else if (COp1 && COp1->isNullValue())
5260 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5262 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5268 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5269 SDValue N0 = N->getOperand(0);
5270 EVT VT = N->getValueType(0);
5272 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5274 return SDValue(Res, 0);
5276 // fold (zext (zext x)) -> (zext x)
5277 // fold (zext (aext x)) -> (zext x)
5278 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5279 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5282 // fold (zext (truncate x)) -> (zext x) or
5283 // (zext (truncate x)) -> (truncate x)
5284 // This is valid when the truncated bits of x are already zero.
5285 // FIXME: We should extend this to work for vectors too.
5288 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5289 APInt TruncatedBits =
5290 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5291 APInt(Op.getValueSizeInBits(), 0) :
5292 APInt::getBitsSet(Op.getValueSizeInBits(),
5293 N0.getValueSizeInBits(),
5294 std::min(Op.getValueSizeInBits(),
5295 VT.getSizeInBits()));
5296 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5297 if (VT.bitsGT(Op.getValueType()))
5298 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5299 if (VT.bitsLT(Op.getValueType()))
5300 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5306 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5307 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5308 if (N0.getOpcode() == ISD::TRUNCATE) {
5309 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5310 if (NarrowLoad.getNode()) {
5311 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5312 if (NarrowLoad.getNode() != N0.getNode()) {
5313 CombineTo(N0.getNode(), NarrowLoad);
5314 // CombineTo deleted the truncate, if needed, but not what's under it.
5317 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5321 // fold (zext (truncate x)) -> (and x, mask)
5322 if (N0.getOpcode() == ISD::TRUNCATE &&
5323 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5325 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5326 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5327 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5328 if (NarrowLoad.getNode()) {
5329 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5330 if (NarrowLoad.getNode() != N0.getNode()) {
5331 CombineTo(N0.getNode(), NarrowLoad);
5332 // CombineTo deleted the truncate, if needed, but not what's under it.
5335 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5338 SDValue Op = N0.getOperand(0);
5339 if (Op.getValueType().bitsLT(VT)) {
5340 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5341 AddToWorklist(Op.getNode());
5342 } else if (Op.getValueType().bitsGT(VT)) {
5343 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5344 AddToWorklist(Op.getNode());
5346 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5347 N0.getValueType().getScalarType());
5350 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5351 // if either of the casts is not free.
5352 if (N0.getOpcode() == ISD::AND &&
5353 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5354 N0.getOperand(1).getOpcode() == ISD::Constant &&
5355 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5356 N0.getValueType()) ||
5357 !TLI.isZExtFree(N0.getValueType(), VT))) {
5358 SDValue X = N0.getOperand(0).getOperand(0);
5359 if (X.getValueType().bitsLT(VT)) {
5360 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5361 } else if (X.getValueType().bitsGT(VT)) {
5362 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5364 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5365 Mask = Mask.zext(VT.getSizeInBits());
5366 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5367 X, DAG.getConstant(Mask, VT));
5370 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5371 // None of the supported targets knows how to perform load and vector_zext
5372 // on vectors in one instruction. We only perform this transformation on
5374 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5375 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5376 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5377 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5378 bool DoXform = true;
5379 SmallVector<SDNode*, 4> SetCCs;
5380 if (!N0.hasOneUse())
5381 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5383 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5384 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5386 LN0->getBasePtr(), N0.getValueType(),
5387 LN0->getMemOperand());
5388 CombineTo(N, ExtLoad);
5389 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5390 N0.getValueType(), ExtLoad);
5391 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5393 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5395 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5399 // fold (zext (and/or/xor (load x), cst)) ->
5400 // (and/or/xor (zextload x), (zext cst))
5401 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5402 N0.getOpcode() == ISD::XOR) &&
5403 isa<LoadSDNode>(N0.getOperand(0)) &&
5404 N0.getOperand(1).getOpcode() == ISD::Constant &&
5405 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5406 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5407 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5408 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5409 bool DoXform = true;
5410 SmallVector<SDNode*, 4> SetCCs;
5411 if (!N0.hasOneUse())
5412 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5415 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5416 LN0->getChain(), LN0->getBasePtr(),
5418 LN0->getMemOperand());
5419 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5420 Mask = Mask.zext(VT.getSizeInBits());
5421 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5422 ExtLoad, DAG.getConstant(Mask, VT));
5423 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5424 SDLoc(N0.getOperand(0)),
5425 N0.getOperand(0).getValueType(), ExtLoad);
5427 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5428 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5430 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5435 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5436 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5437 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5438 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5439 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5440 EVT MemVT = LN0->getMemoryVT();
5441 if ((!LegalOperations && !LN0->isVolatile()) ||
5442 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5443 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5445 LN0->getBasePtr(), MemVT,
5446 LN0->getMemOperand());
5447 CombineTo(N, ExtLoad);
5448 CombineTo(N0.getNode(),
5449 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5451 ExtLoad.getValue(1));
5452 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5456 if (N0.getOpcode() == ISD::SETCC) {
5457 if (!LegalOperations && VT.isVector() &&
5458 N0.getValueType().getVectorElementType() == MVT::i1) {
5459 EVT N0VT = N0.getOperand(0).getValueType();
5460 if (getSetCCResultType(N0VT) == N0.getValueType())
5463 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5464 // Only do this before legalize for now.
5465 EVT EltVT = VT.getVectorElementType();
5466 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5467 DAG.getConstant(1, EltVT));
5468 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5469 // We know that the # elements of the results is the same as the
5470 // # elements of the compare (and the # elements of the compare result
5471 // for that matter). Check to see that they are the same size. If so,
5472 // we know that the element size of the sext'd result matches the
5473 // element size of the compare operands.
5474 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5475 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5477 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5478 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5481 // If the desired elements are smaller or larger than the source
5482 // elements we can use a matching integer vector type and then
5483 // truncate/sign extend
5484 EVT MatchingElementType =
5485 EVT::getIntegerVT(*DAG.getContext(),
5486 N0VT.getScalarType().getSizeInBits());
5487 EVT MatchingVectorType =
5488 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5489 N0VT.getVectorNumElements());
5491 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5493 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5494 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5495 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5496 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5499 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5501 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5502 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5503 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5504 if (SCC.getNode()) return SCC;
5507 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5508 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5509 isa<ConstantSDNode>(N0.getOperand(1)) &&
5510 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5512 SDValue ShAmt = N0.getOperand(1);
5513 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5514 if (N0.getOpcode() == ISD::SHL) {
5515 SDValue InnerZExt = N0.getOperand(0);
5516 // If the original shl may be shifting out bits, do not perform this
5518 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5519 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5520 if (ShAmtVal > KnownZeroBits)
5526 // Ensure that the shift amount is wide enough for the shifted value.
5527 if (VT.getSizeInBits() >= 256)
5528 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5530 return DAG.getNode(N0.getOpcode(), DL, VT,
5531 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5538 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5539 SDValue N0 = N->getOperand(0);
5540 EVT VT = N->getValueType(0);
5542 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5544 return SDValue(Res, 0);
5546 // fold (aext (aext x)) -> (aext x)
5547 // fold (aext (zext x)) -> (zext x)
5548 // fold (aext (sext x)) -> (sext x)
5549 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5550 N0.getOpcode() == ISD::ZERO_EXTEND ||
5551 N0.getOpcode() == ISD::SIGN_EXTEND)
5552 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5554 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5555 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5556 if (N0.getOpcode() == ISD::TRUNCATE) {
5557 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5558 if (NarrowLoad.getNode()) {
5559 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5560 if (NarrowLoad.getNode() != N0.getNode()) {
5561 CombineTo(N0.getNode(), NarrowLoad);
5562 // CombineTo deleted the truncate, if needed, but not what's under it.
5565 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5569 // fold (aext (truncate x))
5570 if (N0.getOpcode() == ISD::TRUNCATE) {
5571 SDValue TruncOp = N0.getOperand(0);
5572 if (TruncOp.getValueType() == VT)
5573 return TruncOp; // x iff x size == zext size.
5574 if (TruncOp.getValueType().bitsGT(VT))
5575 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5576 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5579 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5580 // if the trunc is not free.
5581 if (N0.getOpcode() == ISD::AND &&
5582 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5583 N0.getOperand(1).getOpcode() == ISD::Constant &&
5584 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5585 N0.getValueType())) {
5586 SDValue X = N0.getOperand(0).getOperand(0);
5587 if (X.getValueType().bitsLT(VT)) {
5588 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5589 } else if (X.getValueType().bitsGT(VT)) {
5590 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5592 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5593 Mask = Mask.zext(VT.getSizeInBits());
5594 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5595 X, DAG.getConstant(Mask, VT));
5598 // fold (aext (load x)) -> (aext (truncate (extload x)))
5599 // None of the supported targets knows how to perform load and any_ext
5600 // on vectors in one instruction. We only perform this transformation on
5602 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5603 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5604 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5605 bool DoXform = true;
5606 SmallVector<SDNode*, 4> SetCCs;
5607 if (!N0.hasOneUse())
5608 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5610 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5611 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5613 LN0->getBasePtr(), N0.getValueType(),
5614 LN0->getMemOperand());
5615 CombineTo(N, ExtLoad);
5616 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5617 N0.getValueType(), ExtLoad);
5618 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5619 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5621 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5625 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5626 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5627 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5628 if (N0.getOpcode() == ISD::LOAD &&
5629 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5631 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5632 ISD::LoadExtType ExtType = LN0->getExtensionType();
5633 EVT MemVT = LN0->getMemoryVT();
5634 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5635 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5636 VT, LN0->getChain(), LN0->getBasePtr(),
5637 MemVT, LN0->getMemOperand());
5638 CombineTo(N, ExtLoad);
5639 CombineTo(N0.getNode(),
5640 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5641 N0.getValueType(), ExtLoad),
5642 ExtLoad.getValue(1));
5643 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5647 if (N0.getOpcode() == ISD::SETCC) {
5649 // aext(setcc) -> vsetcc
5650 // aext(setcc) -> truncate(vsetcc)
5651 // aext(setcc) -> aext(vsetcc)
5652 // Only do this before legalize for now.
5653 if (VT.isVector() && !LegalOperations) {
5654 EVT N0VT = N0.getOperand(0).getValueType();
5655 // We know that the # elements of the results is the same as the
5656 // # elements of the compare (and the # elements of the compare result
5657 // for that matter). Check to see that they are the same size. If so,
5658 // we know that the element size of the sext'd result matches the
5659 // element size of the compare operands.
5660 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5661 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5663 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5664 // If the desired elements are smaller or larger than the source
5665 // elements we can use a matching integer vector type and then
5666 // truncate/any extend
5668 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5670 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5672 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5673 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5677 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5679 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5680 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5681 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5689 /// GetDemandedBits - See if the specified operand can be simplified with the
5690 /// knowledge that only the bits specified by Mask are used. If so, return the
5691 /// simpler operand, otherwise return a null SDValue.
5692 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5693 switch (V.getOpcode()) {
5695 case ISD::Constant: {
5696 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5697 assert(CV && "Const value should be ConstSDNode.");
5698 const APInt &CVal = CV->getAPIntValue();
5699 APInt NewVal = CVal & Mask;
5701 return DAG.getConstant(NewVal, V.getValueType());
5706 // If the LHS or RHS don't contribute bits to the or, drop them.
5707 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5708 return V.getOperand(1);
5709 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5710 return V.getOperand(0);
5713 // Only look at single-use SRLs.
5714 if (!V.getNode()->hasOneUse())
5716 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5717 // See if we can recursively simplify the LHS.
5718 unsigned Amt = RHSC->getZExtValue();
5720 // Watch out for shift count overflow though.
5721 if (Amt >= Mask.getBitWidth()) break;
5722 APInt NewMask = Mask << Amt;
5723 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5724 if (SimplifyLHS.getNode())
5725 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5726 SimplifyLHS, V.getOperand(1));
5732 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5733 /// bits and then truncated to a narrower type and where N is a multiple
5734 /// of number of bits of the narrower type, transform it to a narrower load
5735 /// from address + N / num of bits of new type. If the result is to be
5736 /// extended, also fold the extension to form a extending load.
5737 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5738 unsigned Opc = N->getOpcode();
5740 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5741 SDValue N0 = N->getOperand(0);
5742 EVT VT = N->getValueType(0);
5745 // This transformation isn't valid for vector loads.
5749 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5751 if (Opc == ISD::SIGN_EXTEND_INREG) {
5752 ExtType = ISD::SEXTLOAD;
5753 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5754 } else if (Opc == ISD::SRL) {
5755 // Another special-case: SRL is basically zero-extending a narrower value.
5756 ExtType = ISD::ZEXTLOAD;
5758 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5759 if (!N01) return SDValue();
5760 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5761 VT.getSizeInBits() - N01->getZExtValue());
5763 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5766 unsigned EVTBits = ExtVT.getSizeInBits();
5768 // Do not generate loads of non-round integer types since these can
5769 // be expensive (and would be wrong if the type is not byte sized).
5770 if (!ExtVT.isRound())
5774 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5775 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5776 ShAmt = N01->getZExtValue();
5777 // Is the shift amount a multiple of size of VT?
5778 if ((ShAmt & (EVTBits-1)) == 0) {
5779 N0 = N0.getOperand(0);
5780 // Is the load width a multiple of size of VT?
5781 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5785 // At this point, we must have a load or else we can't do the transform.
5786 if (!isa<LoadSDNode>(N0)) return SDValue();
5788 // Because a SRL must be assumed to *need* to zero-extend the high bits
5789 // (as opposed to anyext the high bits), we can't combine the zextload
5790 // lowering of SRL and an sextload.
5791 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5794 // If the shift amount is larger than the input type then we're not
5795 // accessing any of the loaded bytes. If the load was a zextload/extload
5796 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5797 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5802 // If the load is shifted left (and the result isn't shifted back right),
5803 // we can fold the truncate through the shift.
5804 unsigned ShLeftAmt = 0;
5805 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5806 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5807 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5808 ShLeftAmt = N01->getZExtValue();
5809 N0 = N0.getOperand(0);
5813 // If we haven't found a load, we can't narrow it. Don't transform one with
5814 // multiple uses, this would require adding a new load.
5815 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5818 // Don't change the width of a volatile load.
5819 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5820 if (LN0->isVolatile())
5823 // Verify that we are actually reducing a load width here.
5824 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5827 // For the transform to be legal, the load must produce only two values
5828 // (the value loaded and the chain). Don't transform a pre-increment
5829 // load, for example, which produces an extra value. Otherwise the
5830 // transformation is not equivalent, and the downstream logic to replace
5831 // uses gets things wrong.
5832 if (LN0->getNumValues() > 2)
5835 // If the load that we're shrinking is an extload and we're not just
5836 // discarding the extension we can't simply shrink the load. Bail.
5837 // TODO: It would be possible to merge the extensions in some cases.
5838 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5839 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5842 EVT PtrType = N0.getOperand(1).getValueType();
5844 if (PtrType == MVT::Untyped || PtrType.isExtended())
5845 // It's not possible to generate a constant of extended or untyped type.
5848 // For big endian targets, we need to adjust the offset to the pointer to
5849 // load the correct bytes.
5850 if (TLI.isBigEndian()) {
5851 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5852 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5853 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5856 uint64_t PtrOff = ShAmt / 8;
5857 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5858 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5859 PtrType, LN0->getBasePtr(),
5860 DAG.getConstant(PtrOff, PtrType));
5861 AddToWorklist(NewPtr.getNode());
5864 if (ExtType == ISD::NON_EXTLOAD)
5865 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5866 LN0->getPointerInfo().getWithOffset(PtrOff),
5867 LN0->isVolatile(), LN0->isNonTemporal(),
5868 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5870 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5871 LN0->getPointerInfo().getWithOffset(PtrOff),
5872 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5873 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5875 // Replace the old load's chain with the new load's chain.
5876 WorklistRemover DeadNodes(*this);
5877 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5879 // Shift the result left, if we've swallowed a left shift.
5880 SDValue Result = Load;
5881 if (ShLeftAmt != 0) {
5882 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5883 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5885 // If the shift amount is as large as the result size (but, presumably,
5886 // no larger than the source) then the useful bits of the result are
5887 // zero; we can't simply return the shortened shift, because the result
5888 // of that operation is undefined.
5889 if (ShLeftAmt >= VT.getSizeInBits())
5890 Result = DAG.getConstant(0, VT);
5892 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5893 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5896 // Return the new loaded value.
5900 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5901 SDValue N0 = N->getOperand(0);
5902 SDValue N1 = N->getOperand(1);
5903 EVT VT = N->getValueType(0);
5904 EVT EVT = cast<VTSDNode>(N1)->getVT();
5905 unsigned VTBits = VT.getScalarType().getSizeInBits();
5906 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5908 // fold (sext_in_reg c1) -> c1
5909 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5910 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5912 // If the input is already sign extended, just drop the extension.
5913 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5916 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5917 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5918 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5919 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5920 N0.getOperand(0), N1);
5922 // fold (sext_in_reg (sext x)) -> (sext x)
5923 // fold (sext_in_reg (aext x)) -> (sext x)
5924 // if x is small enough.
5925 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5926 SDValue N00 = N0.getOperand(0);
5927 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5928 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5929 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5932 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5933 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5934 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5936 // fold operands of sext_in_reg based on knowledge that the top bits are not
5938 if (SimplifyDemandedBits(SDValue(N, 0)))
5939 return SDValue(N, 0);
5941 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5942 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5943 SDValue NarrowLoad = ReduceLoadWidth(N);
5944 if (NarrowLoad.getNode())
5947 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5948 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5949 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5950 if (N0.getOpcode() == ISD::SRL) {
5951 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5952 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5953 // We can turn this into an SRA iff the input to the SRL is already sign
5955 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5956 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5957 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5958 N0.getOperand(0), N0.getOperand(1));
5962 // fold (sext_inreg (extload x)) -> (sextload x)
5963 if (ISD::isEXTLoad(N0.getNode()) &&
5964 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5965 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5966 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5967 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5968 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5969 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5971 LN0->getBasePtr(), EVT,
5972 LN0->getMemOperand());
5973 CombineTo(N, ExtLoad);
5974 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5975 AddToWorklist(ExtLoad.getNode());
5976 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5978 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5979 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5981 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5982 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5983 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5984 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5985 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5987 LN0->getBasePtr(), EVT,
5988 LN0->getMemOperand());
5989 CombineTo(N, ExtLoad);
5990 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5991 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5994 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5995 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5996 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5997 N0.getOperand(1), false);
5998 if (BSwap.getNode())
5999 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6003 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6004 // into a build_vector.
6005 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6006 SmallVector<SDValue, 8> Elts;
6007 unsigned NumElts = N0->getNumOperands();
6008 unsigned ShAmt = VTBits - EVTBits;
6010 for (unsigned i = 0; i != NumElts; ++i) {
6011 SDValue Op = N0->getOperand(i);
6012 if (Op->getOpcode() == ISD::UNDEF) {
6017 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6018 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6019 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6020 Op.getValueType()));
6023 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6029 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6030 SDValue N0 = N->getOperand(0);
6031 EVT VT = N->getValueType(0);
6032 bool isLE = TLI.isLittleEndian();
6035 if (N0.getValueType() == N->getValueType(0))
6037 // fold (truncate c1) -> c1
6038 if (isa<ConstantSDNode>(N0))
6039 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6040 // fold (truncate (truncate x)) -> (truncate x)
6041 if (N0.getOpcode() == ISD::TRUNCATE)
6042 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6043 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6044 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6045 N0.getOpcode() == ISD::SIGN_EXTEND ||
6046 N0.getOpcode() == ISD::ANY_EXTEND) {
6047 if (N0.getOperand(0).getValueType().bitsLT(VT))
6048 // if the source is smaller than the dest, we still need an extend
6049 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6051 if (N0.getOperand(0).getValueType().bitsGT(VT))
6052 // if the source is larger than the dest, than we just need the truncate
6053 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6054 // if the source and dest are the same type, we can drop both the extend
6055 // and the truncate.
6056 return N0.getOperand(0);
6059 // Fold extract-and-trunc into a narrow extract. For example:
6060 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6061 // i32 y = TRUNCATE(i64 x)
6063 // v16i8 b = BITCAST (v2i64 val)
6064 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6066 // Note: We only run this optimization after type legalization (which often
6067 // creates this pattern) and before operation legalization after which
6068 // we need to be more careful about the vector instructions that we generate.
6069 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6070 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6072 EVT VecTy = N0.getOperand(0).getValueType();
6073 EVT ExTy = N0.getValueType();
6074 EVT TrTy = N->getValueType(0);
6076 unsigned NumElem = VecTy.getVectorNumElements();
6077 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6079 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6080 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6082 SDValue EltNo = N0->getOperand(1);
6083 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6084 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6085 EVT IndexTy = TLI.getVectorIdxTy();
6086 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6088 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6089 NVT, N0.getOperand(0));
6091 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6093 DAG.getConstant(Index, IndexTy));
6097 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6098 if (N0.getOpcode() == ISD::SELECT) {
6099 EVT SrcVT = N0.getValueType();
6100 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6101 TLI.isTruncateFree(SrcVT, VT)) {
6103 SDValue Cond = N0.getOperand(0);
6104 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6105 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6106 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6110 // Fold a series of buildvector, bitcast, and truncate if possible.
6112 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6113 // (2xi32 (buildvector x, y)).
6114 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6115 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6116 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6117 N0.getOperand(0).hasOneUse()) {
6119 SDValue BuildVect = N0.getOperand(0);
6120 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6121 EVT TruncVecEltTy = VT.getVectorElementType();
6123 // Check that the element types match.
6124 if (BuildVectEltTy == TruncVecEltTy) {
6125 // Now we only need to compute the offset of the truncated elements.
6126 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6127 unsigned TruncVecNumElts = VT.getVectorNumElements();
6128 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6130 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6131 "Invalid number of elements");
6133 SmallVector<SDValue, 8> Opnds;
6134 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6135 Opnds.push_back(BuildVect.getOperand(i));
6137 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6141 // See if we can simplify the input to this truncate through knowledge that
6142 // only the low bits are being used.
6143 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6144 // Currently we only perform this optimization on scalars because vectors
6145 // may have different active low bits.
6146 if (!VT.isVector()) {
6148 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6149 VT.getSizeInBits()));
6150 if (Shorter.getNode())
6151 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6153 // fold (truncate (load x)) -> (smaller load x)
6154 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6155 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6156 SDValue Reduced = ReduceLoadWidth(N);
6157 if (Reduced.getNode())
6159 // Handle the case where the load remains an extending load even
6160 // after truncation.
6161 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6162 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6163 if (!LN0->isVolatile() &&
6164 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6165 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6166 VT, LN0->getChain(), LN0->getBasePtr(),
6168 LN0->getMemOperand());
6169 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6174 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6175 // where ... are all 'undef'.
6176 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6177 SmallVector<EVT, 8> VTs;
6180 unsigned NumDefs = 0;
6182 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6183 SDValue X = N0.getOperand(i);
6184 if (X.getOpcode() != ISD::UNDEF) {
6189 // Stop if more than one members are non-undef.
6192 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6193 VT.getVectorElementType(),
6194 X.getValueType().getVectorNumElements()));
6198 return DAG.getUNDEF(VT);
6201 assert(V.getNode() && "The single defined operand is empty!");
6202 SmallVector<SDValue, 8> Opnds;
6203 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6205 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6208 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6209 AddToWorklist(NV.getNode());
6210 Opnds.push_back(NV);
6212 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6216 // Simplify the operands using demanded-bits information.
6217 if (!VT.isVector() &&
6218 SimplifyDemandedBits(SDValue(N, 0)))
6219 return SDValue(N, 0);
6224 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6225 SDValue Elt = N->getOperand(i);
6226 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6227 return Elt.getNode();
6228 return Elt.getOperand(Elt.getResNo()).getNode();
6231 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6232 /// if load locations are consecutive.
6233 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6234 assert(N->getOpcode() == ISD::BUILD_PAIR);
6236 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6237 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6238 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6239 LD1->getAddressSpace() != LD2->getAddressSpace())
6241 EVT LD1VT = LD1->getValueType(0);
6243 if (ISD::isNON_EXTLoad(LD2) &&
6245 // If both are volatile this would reduce the number of volatile loads.
6246 // If one is volatile it might be ok, but play conservative and bail out.
6247 !LD1->isVolatile() &&
6248 !LD2->isVolatile() &&
6249 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6250 unsigned Align = LD1->getAlignment();
6251 unsigned NewAlign = TLI.getDataLayout()->
6252 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6254 if (NewAlign <= Align &&
6255 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6256 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6257 LD1->getBasePtr(), LD1->getPointerInfo(),
6258 false, false, false, Align);
6264 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6265 SDValue N0 = N->getOperand(0);
6266 EVT VT = N->getValueType(0);
6268 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6269 // Only do this before legalize, since afterward the target may be depending
6270 // on the bitconvert.
6271 // First check to see if this is all constant.
6273 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6275 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6277 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6278 assert(!DestEltVT.isVector() &&
6279 "Element type of vector ValueType must not be vector!");
6281 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6284 // If the input is a constant, let getNode fold it.
6285 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6286 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6287 if (Res.getNode() != N) {
6288 if (!LegalOperations ||
6289 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6292 // Folding it resulted in an illegal node, and it's too late to
6293 // do that. Clean up the old node and forego the transformation.
6294 // Ideally this won't happen very often, because instcombine
6295 // and the earlier dagcombine runs (where illegal nodes are
6296 // permitted) should have folded most of them already.
6297 deleteAndRecombine(Res.getNode());
6301 // (conv (conv x, t1), t2) -> (conv x, t2)
6302 if (N0.getOpcode() == ISD::BITCAST)
6303 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6306 // fold (conv (load x)) -> (load (conv*)x)
6307 // If the resultant load doesn't need a higher alignment than the original!
6308 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6309 // Do not change the width of a volatile load.
6310 !cast<LoadSDNode>(N0)->isVolatile() &&
6311 // Do not remove the cast if the types differ in endian layout.
6312 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6313 TLI.hasBigEndianPartOrdering(VT) &&
6314 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6315 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6316 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6317 unsigned Align = TLI.getDataLayout()->
6318 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6319 unsigned OrigAlign = LN0->getAlignment();
6321 if (Align <= OrigAlign) {
6322 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6323 LN0->getBasePtr(), LN0->getPointerInfo(),
6324 LN0->isVolatile(), LN0->isNonTemporal(),
6325 LN0->isInvariant(), OrigAlign,
6327 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6332 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6333 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6334 // This often reduces constant pool loads.
6335 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6336 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6337 N0.getNode()->hasOneUse() && VT.isInteger() &&
6338 !VT.isVector() && !N0.getValueType().isVector()) {
6339 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6341 AddToWorklist(NewConv.getNode());
6343 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6344 if (N0.getOpcode() == ISD::FNEG)
6345 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6346 NewConv, DAG.getConstant(SignBit, VT));
6347 assert(N0.getOpcode() == ISD::FABS);
6348 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6349 NewConv, DAG.getConstant(~SignBit, VT));
6352 // fold (bitconvert (fcopysign cst, x)) ->
6353 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6354 // Note that we don't handle (copysign x, cst) because this can always be
6355 // folded to an fneg or fabs.
6356 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6357 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6358 VT.isInteger() && !VT.isVector()) {
6359 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6360 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6361 if (isTypeLegal(IntXVT)) {
6362 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6363 IntXVT, N0.getOperand(1));
6364 AddToWorklist(X.getNode());
6366 // If X has a different width than the result/lhs, sext it or truncate it.
6367 unsigned VTWidth = VT.getSizeInBits();
6368 if (OrigXWidth < VTWidth) {
6369 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6370 AddToWorklist(X.getNode());
6371 } else if (OrigXWidth > VTWidth) {
6372 // To get the sign bit in the right place, we have to shift it right
6373 // before truncating.
6374 X = DAG.getNode(ISD::SRL, SDLoc(X),
6375 X.getValueType(), X,
6376 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6377 AddToWorklist(X.getNode());
6378 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6379 AddToWorklist(X.getNode());
6382 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6383 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6384 X, DAG.getConstant(SignBit, VT));
6385 AddToWorklist(X.getNode());
6387 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6388 VT, N0.getOperand(0));
6389 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6390 Cst, DAG.getConstant(~SignBit, VT));
6391 AddToWorklist(Cst.getNode());
6393 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6397 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6398 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6399 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6400 if (CombineLD.getNode())
6407 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6408 EVT VT = N->getValueType(0);
6409 return CombineConsecutiveLoads(N, VT);
6412 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6413 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6414 /// destination element value type.
6415 SDValue DAGCombiner::
6416 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6417 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6419 // If this is already the right type, we're done.
6420 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6422 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6423 unsigned DstBitSize = DstEltVT.getSizeInBits();
6425 // If this is a conversion of N elements of one type to N elements of another
6426 // type, convert each element. This handles FP<->INT cases.
6427 if (SrcBitSize == DstBitSize) {
6428 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6429 BV->getValueType(0).getVectorNumElements());
6431 // Due to the FP element handling below calling this routine recursively,
6432 // we can end up with a scalar-to-vector node here.
6433 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6434 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6435 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6436 DstEltVT, BV->getOperand(0)));
6438 SmallVector<SDValue, 8> Ops;
6439 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6440 SDValue Op = BV->getOperand(i);
6441 // If the vector element type is not legal, the BUILD_VECTOR operands
6442 // are promoted and implicitly truncated. Make that explicit here.
6443 if (Op.getValueType() != SrcEltVT)
6444 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6445 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6447 AddToWorklist(Ops.back().getNode());
6449 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6452 // Otherwise, we're growing or shrinking the elements. To avoid having to
6453 // handle annoying details of growing/shrinking FP values, we convert them to
6455 if (SrcEltVT.isFloatingPoint()) {
6456 // Convert the input float vector to a int vector where the elements are the
6458 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6459 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6460 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6464 // Now we know the input is an integer vector. If the output is a FP type,
6465 // convert to integer first, then to FP of the right size.
6466 if (DstEltVT.isFloatingPoint()) {
6467 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6468 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6469 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6471 // Next, convert to FP elements of the same size.
6472 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6475 // Okay, we know the src/dst types are both integers of differing types.
6476 // Handling growing first.
6477 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6478 if (SrcBitSize < DstBitSize) {
6479 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6481 SmallVector<SDValue, 8> Ops;
6482 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6483 i += NumInputsPerOutput) {
6484 bool isLE = TLI.isLittleEndian();
6485 APInt NewBits = APInt(DstBitSize, 0);
6486 bool EltIsUndef = true;
6487 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6488 // Shift the previously computed bits over.
6489 NewBits <<= SrcBitSize;
6490 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6491 if (Op.getOpcode() == ISD::UNDEF) continue;
6494 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6495 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6499 Ops.push_back(DAG.getUNDEF(DstEltVT));
6501 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6504 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6505 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6508 // Finally, this must be the case where we are shrinking elements: each input
6509 // turns into multiple outputs.
6510 bool isS2V = ISD::isScalarToVector(BV);
6511 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6512 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6513 NumOutputsPerInput*BV->getNumOperands());
6514 SmallVector<SDValue, 8> Ops;
6516 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6517 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6518 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6519 Ops.push_back(DAG.getUNDEF(DstEltVT));
6523 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6524 getAPIntValue().zextOrTrunc(SrcBitSize);
6526 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6527 APInt ThisVal = OpVal.trunc(DstBitSize);
6528 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6529 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6530 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6531 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6533 OpVal = OpVal.lshr(DstBitSize);
6536 // For big endian targets, swap the order of the pieces of each element.
6537 if (TLI.isBigEndian())
6538 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6541 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6544 SDValue DAGCombiner::visitFADD(SDNode *N) {
6545 SDValue N0 = N->getOperand(0);
6546 SDValue N1 = N->getOperand(1);
6547 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6548 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6549 EVT VT = N->getValueType(0);
6552 if (VT.isVector()) {
6553 SDValue FoldedVOp = SimplifyVBinOp(N);
6554 if (FoldedVOp.getNode()) return FoldedVOp;
6557 // fold (fadd c1, c2) -> c1 + c2
6559 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6560 // canonicalize constant to RHS
6561 if (N0CFP && !N1CFP)
6562 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6563 // fold (fadd A, 0) -> A
6564 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6565 N1CFP->getValueAPF().isZero())
6567 // fold (fadd A, (fneg B)) -> (fsub A, B)
6568 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6569 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6570 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6571 GetNegatedExpression(N1, DAG, LegalOperations));
6572 // fold (fadd (fneg A), B) -> (fsub B, A)
6573 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6574 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6575 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6576 GetNegatedExpression(N0, DAG, LegalOperations));
6578 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6579 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6580 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6581 isa<ConstantFPSDNode>(N0.getOperand(1)))
6582 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6583 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6584 N0.getOperand(1), N1));
6586 // No FP constant should be created after legalization as Instruction
6587 // Selection pass has hard time in dealing with FP constant.
6589 // We don't need test this condition for transformation like following, as
6590 // the DAG being transformed implies it is legal to take FP constant as
6593 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6595 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6597 // If allow, fold (fadd (fneg x), x) -> 0.0
6598 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6599 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6600 return DAG.getConstantFP(0.0, VT);
6602 // If allow, fold (fadd x, (fneg x)) -> 0.0
6603 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6604 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6605 return DAG.getConstantFP(0.0, VT);
6607 // In unsafe math mode, we can fold chains of FADD's of the same value
6608 // into multiplications. This transform is not safe in general because
6609 // we are reducing the number of rounding steps.
6610 if (DAG.getTarget().Options.UnsafeFPMath &&
6611 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6613 if (N0.getOpcode() == ISD::FMUL) {
6614 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6615 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6617 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6618 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6619 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6621 DAG.getConstantFP(1.0, VT));
6622 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6626 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6627 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6628 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6630 DAG.getConstantFP(1.0, VT));
6631 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6635 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6636 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6637 N1.getOperand(0) == N1.getOperand(1) &&
6638 N0.getOperand(1) == N1.getOperand(0)) {
6639 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6641 DAG.getConstantFP(2.0, VT));
6642 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6643 N0.getOperand(1), NewCFP);
6646 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6647 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6648 N1.getOperand(0) == N1.getOperand(1) &&
6649 N0.getOperand(0) == N1.getOperand(0)) {
6650 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6652 DAG.getConstantFP(2.0, VT));
6653 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6654 N0.getOperand(0), NewCFP);
6658 if (N1.getOpcode() == ISD::FMUL) {
6659 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6660 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6662 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6663 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6664 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6666 DAG.getConstantFP(1.0, VT));
6667 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6671 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6672 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6673 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6675 DAG.getConstantFP(1.0, VT));
6676 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6681 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6682 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6683 N0.getOperand(0) == N0.getOperand(1) &&
6684 N1.getOperand(1) == N0.getOperand(0)) {
6685 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6687 DAG.getConstantFP(2.0, VT));
6688 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6689 N1.getOperand(1), NewCFP);
6692 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6693 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6694 N0.getOperand(0) == N0.getOperand(1) &&
6695 N1.getOperand(0) == N0.getOperand(0)) {
6696 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6698 DAG.getConstantFP(2.0, VT));
6699 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6700 N1.getOperand(0), NewCFP);
6704 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6705 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6706 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6707 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6708 (N0.getOperand(0) == N1))
6709 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6710 N1, DAG.getConstantFP(3.0, VT));
6713 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6714 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6715 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6716 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6717 N1.getOperand(0) == N0)
6718 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6719 N0, DAG.getConstantFP(3.0, VT));
6722 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6723 if (AllowNewFpConst &&
6724 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6725 N0.getOperand(0) == N0.getOperand(1) &&
6726 N1.getOperand(0) == N1.getOperand(1) &&
6727 N0.getOperand(0) == N1.getOperand(0))
6728 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6730 DAG.getConstantFP(4.0, VT));
6733 // FADD -> FMA combines:
6734 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6735 DAG.getTarget().Options.UnsafeFPMath) &&
6738 ->getTargetLowering()
6739 ->isFMAFasterThanFMulAndFAdd(VT) &&
6740 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6742 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6743 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6744 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6745 N0.getOperand(0), N0.getOperand(1), N1);
6747 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6748 // Note: Commutes FADD operands.
6749 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6750 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6751 N1.getOperand(0), N1.getOperand(1), N0);
6757 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6758 SDValue N0 = N->getOperand(0);
6759 SDValue N1 = N->getOperand(1);
6760 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6761 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6762 EVT VT = N->getValueType(0);
6766 if (VT.isVector()) {
6767 SDValue FoldedVOp = SimplifyVBinOp(N);
6768 if (FoldedVOp.getNode()) return FoldedVOp;
6771 // fold (fsub c1, c2) -> c1-c2
6773 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6774 // fold (fsub A, 0) -> A
6775 if (DAG.getTarget().Options.UnsafeFPMath &&
6776 N1CFP && N1CFP->getValueAPF().isZero())
6778 // fold (fsub 0, B) -> -B
6779 if (DAG.getTarget().Options.UnsafeFPMath &&
6780 N0CFP && N0CFP->getValueAPF().isZero()) {
6781 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6782 return GetNegatedExpression(N1, DAG, LegalOperations);
6783 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6784 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6786 // fold (fsub A, (fneg B)) -> (fadd A, B)
6787 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6788 return DAG.getNode(ISD::FADD, dl, VT, N0,
6789 GetNegatedExpression(N1, DAG, LegalOperations));
6791 // If 'unsafe math' is enabled, fold
6792 // (fsub x, x) -> 0.0 &
6793 // (fsub x, (fadd x, y)) -> (fneg y) &
6794 // (fsub x, (fadd y, x)) -> (fneg y)
6795 if (DAG.getTarget().Options.UnsafeFPMath) {
6797 return DAG.getConstantFP(0.0f, VT);
6799 if (N1.getOpcode() == ISD::FADD) {
6800 SDValue N10 = N1->getOperand(0);
6801 SDValue N11 = N1->getOperand(1);
6803 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6804 &DAG.getTarget().Options))
6805 return GetNegatedExpression(N11, DAG, LegalOperations);
6807 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6808 &DAG.getTarget().Options))
6809 return GetNegatedExpression(N10, DAG, LegalOperations);
6813 // FSUB -> FMA combines:
6814 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6815 DAG.getTarget().Options.UnsafeFPMath) &&
6818 ->getTargetLowering()
6819 ->isFMAFasterThanFMulAndFAdd(VT) &&
6820 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6822 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6823 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6824 return DAG.getNode(ISD::FMA, dl, VT,
6825 N0.getOperand(0), N0.getOperand(1),
6826 DAG.getNode(ISD::FNEG, dl, VT, N1));
6828 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6829 // Note: Commutes FSUB operands.
6830 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6831 return DAG.getNode(ISD::FMA, dl, VT,
6832 DAG.getNode(ISD::FNEG, dl, VT,
6834 N1.getOperand(1), N0);
6836 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6837 if (N0.getOpcode() == ISD::FNEG &&
6838 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6839 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6840 SDValue N00 = N0.getOperand(0).getOperand(0);
6841 SDValue N01 = N0.getOperand(0).getOperand(1);
6842 return DAG.getNode(ISD::FMA, dl, VT,
6843 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6844 DAG.getNode(ISD::FNEG, dl, VT, N1));
6851 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6852 SDValue N0 = N->getOperand(0);
6853 SDValue N1 = N->getOperand(1);
6854 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6855 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6856 EVT VT = N->getValueType(0);
6857 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6860 if (VT.isVector()) {
6861 SDValue FoldedVOp = SimplifyVBinOp(N);
6862 if (FoldedVOp.getNode()) return FoldedVOp;
6865 // fold (fmul c1, c2) -> c1*c2
6867 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6868 // canonicalize constant to RHS
6869 if (N0CFP && !N1CFP)
6870 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6871 // fold (fmul A, 0) -> 0
6872 if (DAG.getTarget().Options.UnsafeFPMath &&
6873 N1CFP && N1CFP->getValueAPF().isZero())
6875 // fold (fmul A, 1.0) -> A
6876 if (N1CFP && N1CFP->isExactlyValue(1.0))
6879 // fold (fmul X, 2.0) -> (fadd X, X)
6880 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6881 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6882 // fold (fmul X, -1.0) -> (fneg X)
6883 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6884 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6885 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6887 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6888 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6889 &DAG.getTarget().Options)) {
6890 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6891 &DAG.getTarget().Options)) {
6892 // Both can be negated for free, check to see if at least one is cheaper
6894 if (LHSNeg == 2 || RHSNeg == 2)
6895 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6896 GetNegatedExpression(N0, DAG, LegalOperations),
6897 GetNegatedExpression(N1, DAG, LegalOperations));
6901 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6902 if (DAG.getTarget().Options.UnsafeFPMath &&
6903 N1CFP && N0.getOpcode() == ISD::FMUL &&
6904 N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
6905 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6906 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6907 N0.getOperand(1), N1));
6913 SDValue DAGCombiner::visitFMA(SDNode *N) {
6914 SDValue N0 = N->getOperand(0);
6915 SDValue N1 = N->getOperand(1);
6916 SDValue N2 = N->getOperand(2);
6917 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6918 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6919 EVT VT = N->getValueType(0);
6923 // Constant fold FMA.
6924 if (isa<ConstantFPSDNode>(N0) &&
6925 isa<ConstantFPSDNode>(N1) &&
6926 isa<ConstantFPSDNode>(N2)) {
6927 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6930 if (DAG.getTarget().Options.UnsafeFPMath) {
6931 if (N0CFP && N0CFP->isZero())
6933 if (N1CFP && N1CFP->isZero())
6936 if (N0CFP && N0CFP->isExactlyValue(1.0))
6937 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6938 if (N1CFP && N1CFP->isExactlyValue(1.0))
6939 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6941 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6942 if (N0CFP && !N1CFP)
6943 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6945 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6946 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6947 N2.getOpcode() == ISD::FMUL &&
6948 N0 == N2.getOperand(0) &&
6949 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6950 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6951 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6955 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6956 if (DAG.getTarget().Options.UnsafeFPMath &&
6957 N0.getOpcode() == ISD::FMUL && N1CFP &&
6958 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6959 return DAG.getNode(ISD::FMA, dl, VT,
6961 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6965 // (fma x, 1, y) -> (fadd x, y)
6966 // (fma x, -1, y) -> (fadd (fneg x), y)
6968 if (N1CFP->isExactlyValue(1.0))
6969 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6971 if (N1CFP->isExactlyValue(-1.0) &&
6972 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6973 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6974 AddToWorklist(RHSNeg.getNode());
6975 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6979 // (fma x, c, x) -> (fmul x, (c+1))
6980 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6981 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6982 DAG.getNode(ISD::FADD, dl, VT,
6983 N1, DAG.getConstantFP(1.0, VT)));
6985 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6986 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6987 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6988 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6989 DAG.getNode(ISD::FADD, dl, VT,
6990 N1, DAG.getConstantFP(-1.0, VT)));
6996 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6997 SDValue N0 = N->getOperand(0);
6998 SDValue N1 = N->getOperand(1);
6999 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7000 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7001 EVT VT = N->getValueType(0);
7002 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7005 if (VT.isVector()) {
7006 SDValue FoldedVOp = SimplifyVBinOp(N);
7007 if (FoldedVOp.getNode()) return FoldedVOp;
7010 // fold (fdiv c1, c2) -> c1/c2
7012 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7014 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7015 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
7016 // Compute the reciprocal 1.0 / c2.
7017 APFloat N1APF = N1CFP->getValueAPF();
7018 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7019 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7020 // Only do the transform if the reciprocal is a legal fp immediate that
7021 // isn't too nasty (eg NaN, denormal, ...).
7022 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7023 (!LegalOperations ||
7024 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7025 // backend)... we should handle this gracefully after Legalize.
7026 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7027 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7028 TLI.isFPImmLegal(Recip, VT)))
7029 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7030 DAG.getConstantFP(Recip, VT));
7033 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7034 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
7035 &DAG.getTarget().Options)) {
7036 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
7037 &DAG.getTarget().Options)) {
7038 // Both can be negated for free, check to see if at least one is cheaper
7040 if (LHSNeg == 2 || RHSNeg == 2)
7041 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7042 GetNegatedExpression(N0, DAG, LegalOperations),
7043 GetNegatedExpression(N1, DAG, LegalOperations));
7050 SDValue DAGCombiner::visitFREM(SDNode *N) {
7051 SDValue N0 = N->getOperand(0);
7052 SDValue N1 = N->getOperand(1);
7053 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7054 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7055 EVT VT = N->getValueType(0);
7057 // fold (frem c1, c2) -> fmod(c1,c2)
7059 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7064 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7065 SDValue N0 = N->getOperand(0);
7066 SDValue N1 = N->getOperand(1);
7067 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7068 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7069 EVT VT = N->getValueType(0);
7071 if (N0CFP && N1CFP) // Constant fold
7072 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7075 const APFloat& V = N1CFP->getValueAPF();
7076 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7077 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7078 if (!V.isNegative()) {
7079 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7080 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7082 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7083 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7084 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7088 // copysign(fabs(x), y) -> copysign(x, y)
7089 // copysign(fneg(x), y) -> copysign(x, y)
7090 // copysign(copysign(x,z), y) -> copysign(x, y)
7091 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7092 N0.getOpcode() == ISD::FCOPYSIGN)
7093 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7094 N0.getOperand(0), N1);
7096 // copysign(x, abs(y)) -> abs(x)
7097 if (N1.getOpcode() == ISD::FABS)
7098 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7100 // copysign(x, copysign(y,z)) -> copysign(x, z)
7101 if (N1.getOpcode() == ISD::FCOPYSIGN)
7102 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7103 N0, N1.getOperand(1));
7105 // copysign(x, fp_extend(y)) -> copysign(x, y)
7106 // copysign(x, fp_round(y)) -> copysign(x, y)
7107 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7108 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7109 N0, N1.getOperand(0));
7114 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7115 SDValue N0 = N->getOperand(0);
7116 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7117 EVT VT = N->getValueType(0);
7118 EVT OpVT = N0.getValueType();
7120 // fold (sint_to_fp c1) -> c1fp
7122 // ...but only if the target supports immediate floating-point values
7123 (!LegalOperations ||
7124 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7125 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7127 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7128 // but UINT_TO_FP is legal on this target, try to convert.
7129 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7130 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7131 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7132 if (DAG.SignBitIsZero(N0))
7133 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7136 // The next optimizations are desirable only if SELECT_CC can be lowered.
7137 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7138 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7139 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7141 (!LegalOperations ||
7142 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7144 { N0.getOperand(0), N0.getOperand(1),
7145 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7147 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7150 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7151 // (select_cc x, y, 1.0, 0.0,, cc)
7152 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7153 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7154 (!LegalOperations ||
7155 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7157 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7158 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7159 N0.getOperand(0).getOperand(2) };
7160 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7167 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7168 SDValue N0 = N->getOperand(0);
7169 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7170 EVT VT = N->getValueType(0);
7171 EVT OpVT = N0.getValueType();
7173 // fold (uint_to_fp c1) -> c1fp
7175 // ...but only if the target supports immediate floating-point values
7176 (!LegalOperations ||
7177 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7178 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7180 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7181 // but SINT_TO_FP is legal on this target, try to convert.
7182 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7183 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7184 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7185 if (DAG.SignBitIsZero(N0))
7186 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7189 // The next optimizations are desirable only if SELECT_CC can be lowered.
7190 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7191 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7193 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7194 (!LegalOperations ||
7195 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7197 { N0.getOperand(0), N0.getOperand(1),
7198 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7200 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7207 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7208 SDValue N0 = N->getOperand(0);
7209 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7210 EVT VT = N->getValueType(0);
7212 // fold (fp_to_sint c1fp) -> c1
7214 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7219 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7220 SDValue N0 = N->getOperand(0);
7221 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7222 EVT VT = N->getValueType(0);
7224 // fold (fp_to_uint c1fp) -> c1
7226 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7231 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7232 SDValue N0 = N->getOperand(0);
7233 SDValue N1 = N->getOperand(1);
7234 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7235 EVT VT = N->getValueType(0);
7237 // fold (fp_round c1fp) -> c1fp
7239 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7241 // fold (fp_round (fp_extend x)) -> x
7242 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7243 return N0.getOperand(0);
7245 // fold (fp_round (fp_round x)) -> (fp_round x)
7246 if (N0.getOpcode() == ISD::FP_ROUND) {
7247 // This is a value preserving truncation if both round's are.
7248 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7249 N0.getNode()->getConstantOperandVal(1) == 1;
7250 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7251 DAG.getIntPtrConstant(IsTrunc));
7254 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7255 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7256 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7257 N0.getOperand(0), N1);
7258 AddToWorklist(Tmp.getNode());
7259 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7260 Tmp, N0.getOperand(1));
7266 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7267 SDValue N0 = N->getOperand(0);
7268 EVT VT = N->getValueType(0);
7269 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7270 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7272 // fold (fp_round_inreg c1fp) -> c1fp
7273 if (N0CFP && isTypeLegal(EVT)) {
7274 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7275 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7281 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7282 SDValue N0 = N->getOperand(0);
7283 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7284 EVT VT = N->getValueType(0);
7286 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7287 if (N->hasOneUse() &&
7288 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7291 // fold (fp_extend c1fp) -> c1fp
7293 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7295 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7297 if (N0.getOpcode() == ISD::FP_ROUND
7298 && N0.getNode()->getConstantOperandVal(1) == 1) {
7299 SDValue In = N0.getOperand(0);
7300 if (In.getValueType() == VT) return In;
7301 if (VT.bitsLT(In.getValueType()))
7302 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7303 In, N0.getOperand(1));
7304 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7307 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7308 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7309 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7310 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7311 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7313 LN0->getBasePtr(), N0.getValueType(),
7314 LN0->getMemOperand());
7315 CombineTo(N, ExtLoad);
7316 CombineTo(N0.getNode(),
7317 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7318 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7319 ExtLoad.getValue(1));
7320 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7326 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7327 SDValue N0 = N->getOperand(0);
7328 EVT VT = N->getValueType(0);
7330 // Constant fold FNEG.
7331 if (isa<ConstantFPSDNode>(N0))
7332 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7334 if (VT.isVector()) {
7335 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7336 if (FoldedVOp.getNode()) return FoldedVOp;
7339 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7340 &DAG.getTarget().Options))
7341 return GetNegatedExpression(N0, DAG, LegalOperations);
7343 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7344 // constant pool values.
7345 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7346 N0.getNode()->hasOneUse()) {
7347 SDValue Int = N0.getOperand(0);
7348 EVT IntVT = Int.getValueType();
7349 if (IntVT.isInteger() && !IntVT.isVector()) {
7351 if (N0.getValueType().isVector()) {
7352 // For a vector, get a mask such as 0x80... per scalar element
7354 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7355 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7357 // For a scalar, just generate 0x80...
7358 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7360 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7361 DAG.getConstant(SignMask, IntVT));
7362 AddToWorklist(Int.getNode());
7363 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7367 // (fneg (fmul c, x)) -> (fmul -c, x)
7368 if (N0.getOpcode() == ISD::FMUL) {
7369 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7371 APFloat CVal = CFP1->getValueAPF();
7373 if (Level >= AfterLegalizeDAG &&
7374 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7375 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7377 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7378 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7385 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7386 SDValue N0 = N->getOperand(0);
7387 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7388 EVT VT = N->getValueType(0);
7390 // fold (fceil c1) -> fceil(c1)
7392 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7397 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7398 SDValue N0 = N->getOperand(0);
7399 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7400 EVT VT = N->getValueType(0);
7402 // fold (ftrunc c1) -> ftrunc(c1)
7404 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7409 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7410 SDValue N0 = N->getOperand(0);
7411 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7412 EVT VT = N->getValueType(0);
7414 // fold (ffloor c1) -> ffloor(c1)
7416 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7421 SDValue DAGCombiner::visitFABS(SDNode *N) {
7422 SDValue N0 = N->getOperand(0);
7423 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7424 EVT VT = N->getValueType(0);
7426 if (VT.isVector()) {
7427 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7428 if (FoldedVOp.getNode()) return FoldedVOp;
7431 // fold (fabs c1) -> fabs(c1)
7433 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7434 // fold (fabs (fabs x)) -> (fabs x)
7435 if (N0.getOpcode() == ISD::FABS)
7436 return N->getOperand(0);
7437 // fold (fabs (fneg x)) -> (fabs x)
7438 // fold (fabs (fcopysign x, y)) -> (fabs x)
7439 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7440 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7442 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7443 // constant pool values.
7444 if (!TLI.isFAbsFree(VT) &&
7445 N0.getOpcode() == ISD::BITCAST &&
7446 N0.getNode()->hasOneUse()) {
7447 SDValue Int = N0.getOperand(0);
7448 EVT IntVT = Int.getValueType();
7449 if (IntVT.isInteger() && !IntVT.isVector()) {
7451 if (N0.getValueType().isVector()) {
7452 // For a vector, get a mask such as 0x7f... per scalar element
7454 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7455 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7457 // For a scalar, just generate 0x7f...
7458 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7460 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7461 DAG.getConstant(SignMask, IntVT));
7462 AddToWorklist(Int.getNode());
7463 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7470 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7471 SDValue Chain = N->getOperand(0);
7472 SDValue N1 = N->getOperand(1);
7473 SDValue N2 = N->getOperand(2);
7475 // If N is a constant we could fold this into a fallthrough or unconditional
7476 // branch. However that doesn't happen very often in normal code, because
7477 // Instcombine/SimplifyCFG should have handled the available opportunities.
7478 // If we did this folding here, it would be necessary to update the
7479 // MachineBasicBlock CFG, which is awkward.
7481 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7483 if (N1.getOpcode() == ISD::SETCC &&
7484 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7485 N1.getOperand(0).getValueType())) {
7486 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7487 Chain, N1.getOperand(2),
7488 N1.getOperand(0), N1.getOperand(1), N2);
7491 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7492 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7493 (N1.getOperand(0).hasOneUse() &&
7494 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7495 SDNode *Trunc = nullptr;
7496 if (N1.getOpcode() == ISD::TRUNCATE) {
7497 // Look pass the truncate.
7498 Trunc = N1.getNode();
7499 N1 = N1.getOperand(0);
7502 // Match this pattern so that we can generate simpler code:
7505 // %b = and i32 %a, 2
7506 // %c = srl i32 %b, 1
7507 // brcond i32 %c ...
7512 // %b = and i32 %a, 2
7513 // %c = setcc eq %b, 0
7516 // This applies only when the AND constant value has one bit set and the
7517 // SRL constant is equal to the log2 of the AND constant. The back-end is
7518 // smart enough to convert the result into a TEST/JMP sequence.
7519 SDValue Op0 = N1.getOperand(0);
7520 SDValue Op1 = N1.getOperand(1);
7522 if (Op0.getOpcode() == ISD::AND &&
7523 Op1.getOpcode() == ISD::Constant) {
7524 SDValue AndOp1 = Op0.getOperand(1);
7526 if (AndOp1.getOpcode() == ISD::Constant) {
7527 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7529 if (AndConst.isPowerOf2() &&
7530 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7532 DAG.getSetCC(SDLoc(N),
7533 getSetCCResultType(Op0.getValueType()),
7534 Op0, DAG.getConstant(0, Op0.getValueType()),
7537 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7538 MVT::Other, Chain, SetCC, N2);
7539 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7540 // will convert it back to (X & C1) >> C2.
7541 CombineTo(N, NewBRCond, false);
7542 // Truncate is dead.
7544 deleteAndRecombine(Trunc);
7545 // Replace the uses of SRL with SETCC
7546 WorklistRemover DeadNodes(*this);
7547 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7548 deleteAndRecombine(N1.getNode());
7549 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7555 // Restore N1 if the above transformation doesn't match.
7556 N1 = N->getOperand(1);
7559 // Transform br(xor(x, y)) -> br(x != y)
7560 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7561 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7562 SDNode *TheXor = N1.getNode();
7563 SDValue Op0 = TheXor->getOperand(0);
7564 SDValue Op1 = TheXor->getOperand(1);
7565 if (Op0.getOpcode() == Op1.getOpcode()) {
7566 // Avoid missing important xor optimizations.
7567 SDValue Tmp = visitXOR(TheXor);
7568 if (Tmp.getNode()) {
7569 if (Tmp.getNode() != TheXor) {
7570 DEBUG(dbgs() << "\nReplacing.8 ";
7572 dbgs() << "\nWith: ";
7573 Tmp.getNode()->dump(&DAG);
7575 WorklistRemover DeadNodes(*this);
7576 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7577 deleteAndRecombine(TheXor);
7578 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7579 MVT::Other, Chain, Tmp, N2);
7582 // visitXOR has changed XOR's operands or replaced the XOR completely,
7584 return SDValue(N, 0);
7588 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7590 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7591 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7592 Op0.getOpcode() == ISD::XOR) {
7593 TheXor = Op0.getNode();
7597 EVT SetCCVT = N1.getValueType();
7599 SetCCVT = getSetCCResultType(SetCCVT);
7600 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7603 Equal ? ISD::SETEQ : ISD::SETNE);
7604 // Replace the uses of XOR with SETCC
7605 WorklistRemover DeadNodes(*this);
7606 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7607 deleteAndRecombine(N1.getNode());
7608 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7609 MVT::Other, Chain, SetCC, N2);
7616 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7618 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7619 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7620 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7622 // If N is a constant we could fold this into a fallthrough or unconditional
7623 // branch. However that doesn't happen very often in normal code, because
7624 // Instcombine/SimplifyCFG should have handled the available opportunities.
7625 // If we did this folding here, it would be necessary to update the
7626 // MachineBasicBlock CFG, which is awkward.
7628 // Use SimplifySetCC to simplify SETCC's.
7629 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7630 CondLHS, CondRHS, CC->get(), SDLoc(N),
7632 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7634 // fold to a simpler setcc
7635 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7636 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7637 N->getOperand(0), Simp.getOperand(2),
7638 Simp.getOperand(0), Simp.getOperand(1),
7644 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7645 /// uses N as its base pointer and that N may be folded in the load / store
7646 /// addressing mode.
7647 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7649 const TargetLowering &TLI) {
7651 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7652 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7654 VT = Use->getValueType(0);
7655 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7656 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7658 VT = ST->getValue().getValueType();
7662 TargetLowering::AddrMode AM;
7663 if (N->getOpcode() == ISD::ADD) {
7664 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7667 AM.BaseOffs = Offset->getSExtValue();
7671 } else if (N->getOpcode() == ISD::SUB) {
7672 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7675 AM.BaseOffs = -Offset->getSExtValue();
7682 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7685 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7686 /// pre-indexed load / store when the base pointer is an add or subtract
7687 /// and it has other uses besides the load / store. After the
7688 /// transformation, the new indexed load / store has effectively folded
7689 /// the add / subtract in and all of its other uses are redirected to the
7690 /// new load / store.
7691 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7692 if (Level < AfterLegalizeDAG)
7698 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7699 if (LD->isIndexed())
7701 VT = LD->getMemoryVT();
7702 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7703 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7705 Ptr = LD->getBasePtr();
7706 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7707 if (ST->isIndexed())
7709 VT = ST->getMemoryVT();
7710 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7711 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7713 Ptr = ST->getBasePtr();
7719 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7720 // out. There is no reason to make this a preinc/predec.
7721 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7722 Ptr.getNode()->hasOneUse())
7725 // Ask the target to do addressing mode selection.
7728 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7729 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7732 // Backends without true r+i pre-indexed forms may need to pass a
7733 // constant base with a variable offset so that constant coercion
7734 // will work with the patterns in canonical form.
7735 bool Swapped = false;
7736 if (isa<ConstantSDNode>(BasePtr)) {
7737 std::swap(BasePtr, Offset);
7741 // Don't create a indexed load / store with zero offset.
7742 if (isa<ConstantSDNode>(Offset) &&
7743 cast<ConstantSDNode>(Offset)->isNullValue())
7746 // Try turning it into a pre-indexed load / store except when:
7747 // 1) The new base ptr is a frame index.
7748 // 2) If N is a store and the new base ptr is either the same as or is a
7749 // predecessor of the value being stored.
7750 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7751 // that would create a cycle.
7752 // 4) All uses are load / store ops that use it as old base ptr.
7754 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7755 // (plus the implicit offset) to a register to preinc anyway.
7756 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7761 SDValue Val = cast<StoreSDNode>(N)->getValue();
7762 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7766 // If the offset is a constant, there may be other adds of constants that
7767 // can be folded with this one. We should do this to avoid having to keep
7768 // a copy of the original base pointer.
7769 SmallVector<SDNode *, 16> OtherUses;
7770 if (isa<ConstantSDNode>(Offset))
7771 for (SDNode *Use : BasePtr.getNode()->uses()) {
7772 if (Use == Ptr.getNode())
7775 if (Use->isPredecessorOf(N))
7778 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7783 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7784 if (Op1.getNode() == BasePtr.getNode())
7785 std::swap(Op0, Op1);
7786 assert(Op0.getNode() == BasePtr.getNode() &&
7787 "Use of ADD/SUB but not an operand");
7789 if (!isa<ConstantSDNode>(Op1)) {
7794 // FIXME: In some cases, we can be smarter about this.
7795 if (Op1.getValueType() != Offset.getValueType()) {
7800 OtherUses.push_back(Use);
7804 std::swap(BasePtr, Offset);
7806 // Now check for #3 and #4.
7807 bool RealUse = false;
7809 // Caches for hasPredecessorHelper
7810 SmallPtrSet<const SDNode *, 32> Visited;
7811 SmallVector<const SDNode *, 16> Worklist;
7813 for (SDNode *Use : Ptr.getNode()->uses()) {
7816 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7819 // If Ptr may be folded in addressing mode of other use, then it's
7820 // not profitable to do this transformation.
7821 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7830 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7831 BasePtr, Offset, AM);
7833 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7834 BasePtr, Offset, AM);
7837 DEBUG(dbgs() << "\nReplacing.4 ";
7839 dbgs() << "\nWith: ";
7840 Result.getNode()->dump(&DAG);
7842 WorklistRemover DeadNodes(*this);
7844 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7845 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7847 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7850 // Finally, since the node is now dead, remove it from the graph.
7851 deleteAndRecombine(N);
7854 std::swap(BasePtr, Offset);
7856 // Replace other uses of BasePtr that can be updated to use Ptr
7857 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7858 unsigned OffsetIdx = 1;
7859 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7861 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7862 BasePtr.getNode() && "Expected BasePtr operand");
7864 // We need to replace ptr0 in the following expression:
7865 // x0 * offset0 + y0 * ptr0 = t0
7867 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7869 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7870 // indexed load/store and the expresion that needs to be re-written.
7872 // Therefore, we have:
7873 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7875 ConstantSDNode *CN =
7876 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7878 APInt Offset0 = CN->getAPIntValue();
7879 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7881 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7882 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7883 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7884 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7886 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7888 APInt CNV = Offset0;
7889 if (X0 < 0) CNV = -CNV;
7890 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7891 else CNV = CNV - Offset1;
7893 // We can now generate the new expression.
7894 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7895 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7897 SDValue NewUse = DAG.getNode(Opcode,
7898 SDLoc(OtherUses[i]),
7899 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7900 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7901 deleteAndRecombine(OtherUses[i]);
7904 // Replace the uses of Ptr with uses of the updated base value.
7905 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7906 deleteAndRecombine(Ptr.getNode());
7911 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7912 /// add / sub of the base pointer node into a post-indexed load / store.
7913 /// The transformation folded the add / subtract into the new indexed
7914 /// load / store effectively and all of its uses are redirected to the
7915 /// new load / store.
7916 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7917 if (Level < AfterLegalizeDAG)
7923 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7924 if (LD->isIndexed())
7926 VT = LD->getMemoryVT();
7927 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7928 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7930 Ptr = LD->getBasePtr();
7931 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7932 if (ST->isIndexed())
7934 VT = ST->getMemoryVT();
7935 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7936 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7938 Ptr = ST->getBasePtr();
7944 if (Ptr.getNode()->hasOneUse())
7947 for (SDNode *Op : Ptr.getNode()->uses()) {
7949 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7954 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7955 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7956 // Don't create a indexed load / store with zero offset.
7957 if (isa<ConstantSDNode>(Offset) &&
7958 cast<ConstantSDNode>(Offset)->isNullValue())
7961 // Try turning it into a post-indexed load / store except when
7962 // 1) All uses are load / store ops that use it as base ptr (and
7963 // it may be folded as addressing mmode).
7964 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7965 // nor a successor of N. Otherwise, if Op is folded that would
7968 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7972 bool TryNext = false;
7973 for (SDNode *Use : BasePtr.getNode()->uses()) {
7974 if (Use == Ptr.getNode())
7977 // If all the uses are load / store addresses, then don't do the
7979 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7980 bool RealUse = false;
7981 for (SDNode *UseUse : Use->uses()) {
7982 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7997 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7998 SDValue Result = isLoad
7999 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8000 BasePtr, Offset, AM)
8001 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8002 BasePtr, Offset, AM);
8005 DEBUG(dbgs() << "\nReplacing.5 ";
8007 dbgs() << "\nWith: ";
8008 Result.getNode()->dump(&DAG);
8010 WorklistRemover DeadNodes(*this);
8012 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8013 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8015 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8018 // Finally, since the node is now dead, remove it from the graph.
8019 deleteAndRecombine(N);
8021 // Replace the uses of Use with uses of the updated base value.
8022 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8023 Result.getValue(isLoad ? 1 : 0));
8024 deleteAndRecombine(Op);
8033 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8034 LoadSDNode *LD = cast<LoadSDNode>(N);
8035 SDValue Chain = LD->getChain();
8036 SDValue Ptr = LD->getBasePtr();
8038 // If load is not volatile and there are no uses of the loaded value (and
8039 // the updated indexed value in case of indexed loads), change uses of the
8040 // chain value into uses of the chain input (i.e. delete the dead load).
8041 if (!LD->isVolatile()) {
8042 if (N->getValueType(1) == MVT::Other) {
8044 if (!N->hasAnyUseOfValue(0)) {
8045 // It's not safe to use the two value CombineTo variant here. e.g.
8046 // v1, chain2 = load chain1, loc
8047 // v2, chain3 = load chain2, loc
8049 // Now we replace use of chain2 with chain1. This makes the second load
8050 // isomorphic to the one we are deleting, and thus makes this load live.
8051 DEBUG(dbgs() << "\nReplacing.6 ";
8053 dbgs() << "\nWith chain: ";
8054 Chain.getNode()->dump(&DAG);
8056 WorklistRemover DeadNodes(*this);
8057 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8060 deleteAndRecombine(N);
8062 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8066 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8067 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8068 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8069 DEBUG(dbgs() << "\nReplacing.7 ";
8071 dbgs() << "\nWith: ";
8072 Undef.getNode()->dump(&DAG);
8073 dbgs() << " and 2 other values\n");
8074 WorklistRemover DeadNodes(*this);
8075 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8076 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8077 DAG.getUNDEF(N->getValueType(1)));
8078 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8079 deleteAndRecombine(N);
8080 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8085 // If this load is directly stored, replace the load value with the stored
8087 // TODO: Handle store large -> read small portion.
8088 // TODO: Handle TRUNCSTORE/LOADEXT
8089 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8090 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8091 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8092 if (PrevST->getBasePtr() == Ptr &&
8093 PrevST->getValue().getValueType() == N->getValueType(0))
8094 return CombineTo(N, Chain.getOperand(1), Chain);
8098 // Try to infer better alignment information than the load already has.
8099 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8100 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8101 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8103 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8104 LD->getValueType(0),
8105 Chain, Ptr, LD->getPointerInfo(),
8107 LD->isVolatile(), LD->isNonTemporal(),
8108 LD->isInvariant(), Align, LD->getAAInfo());
8109 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8114 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8115 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8117 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8118 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8121 if (UseAA && LD->isUnindexed()) {
8122 // Walk up chain skipping non-aliasing memory nodes.
8123 SDValue BetterChain = FindBetterChain(N, Chain);
8125 // If there is a better chain.
8126 if (Chain != BetterChain) {
8129 // Replace the chain to void dependency.
8130 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8131 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8132 BetterChain, Ptr, LD->getMemOperand());
8134 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8135 LD->getValueType(0),
8136 BetterChain, Ptr, LD->getMemoryVT(),
8137 LD->getMemOperand());
8140 // Create token factor to keep old chain connected.
8141 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8142 MVT::Other, Chain, ReplLoad.getValue(1));
8144 // Make sure the new and old chains are cleaned up.
8145 AddToWorklist(Token.getNode());
8147 // Replace uses with load result and token factor. Don't add users
8149 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8153 // Try transforming N to an indexed load.
8154 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8155 return SDValue(N, 0);
8157 // Try to slice up N to more direct loads if the slices are mapped to
8158 // different register banks or pairing can take place.
8160 return SDValue(N, 0);
8166 /// \brief Helper structure used to slice a load in smaller loads.
8167 /// Basically a slice is obtained from the following sequence:
8168 /// Origin = load Ty1, Base
8169 /// Shift = srl Ty1 Origin, CstTy Amount
8170 /// Inst = trunc Shift to Ty2
8172 /// Then, it will be rewriten into:
8173 /// Slice = load SliceTy, Base + SliceOffset
8174 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8176 /// SliceTy is deduced from the number of bits that are actually used to
8178 struct LoadedSlice {
8179 /// \brief Helper structure used to compute the cost of a slice.
8181 /// Are we optimizing for code size.
8186 unsigned CrossRegisterBanksCopies;
8190 Cost(bool ForCodeSize = false)
8191 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8192 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8194 /// \brief Get the cost of one isolated slice.
8195 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8196 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8197 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8198 EVT TruncType = LS.Inst->getValueType(0);
8199 EVT LoadedType = LS.getLoadedType();
8200 if (TruncType != LoadedType &&
8201 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8205 /// \brief Account for slicing gain in the current cost.
8206 /// Slicing provide a few gains like removing a shift or a
8207 /// truncate. This method allows to grow the cost of the original
8208 /// load with the gain from this slice.
8209 void addSliceGain(const LoadedSlice &LS) {
8210 // Each slice saves a truncate.
8211 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8212 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8213 LS.Inst->getOperand(0).getValueType()))
8215 // If there is a shift amount, this slice gets rid of it.
8218 // If this slice can merge a cross register bank copy, account for it.
8219 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8220 ++CrossRegisterBanksCopies;
8223 Cost &operator+=(const Cost &RHS) {
8225 Truncates += RHS.Truncates;
8226 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8232 bool operator==(const Cost &RHS) const {
8233 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8234 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8235 ZExts == RHS.ZExts && Shift == RHS.Shift;
8238 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8240 bool operator<(const Cost &RHS) const {
8241 // Assume cross register banks copies are as expensive as loads.
8242 // FIXME: Do we want some more target hooks?
8243 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8244 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8245 // Unless we are optimizing for code size, consider the
8246 // expensive operation first.
8247 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8248 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8249 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8250 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8253 bool operator>(const Cost &RHS) const { return RHS < *this; }
8255 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8257 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8259 // The last instruction that represent the slice. This should be a
8260 // truncate instruction.
8262 // The original load instruction.
8264 // The right shift amount in bits from the original load.
8266 // The DAG from which Origin came from.
8267 // This is used to get some contextual information about legal types, etc.
8270 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8271 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8272 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8274 LoadedSlice(const LoadedSlice &LS)
8275 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8277 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8278 /// \return Result is \p BitWidth and has used bits set to 1 and
8279 /// not used bits set to 0.
8280 APInt getUsedBits() const {
8281 // Reproduce the trunc(lshr) sequence:
8282 // - Start from the truncated value.
8283 // - Zero extend to the desired bit width.
8285 assert(Origin && "No original load to compare against.");
8286 unsigned BitWidth = Origin->getValueSizeInBits(0);
8287 assert(Inst && "This slice is not bound to an instruction");
8288 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8289 "Extracted slice is bigger than the whole type!");
8290 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8291 UsedBits.setAllBits();
8292 UsedBits = UsedBits.zext(BitWidth);
8297 /// \brief Get the size of the slice to be loaded in bytes.
8298 unsigned getLoadedSize() const {
8299 unsigned SliceSize = getUsedBits().countPopulation();
8300 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8301 return SliceSize / 8;
8304 /// \brief Get the type that will be loaded for this slice.
8305 /// Note: This may not be the final type for the slice.
8306 EVT getLoadedType() const {
8307 assert(DAG && "Missing context");
8308 LLVMContext &Ctxt = *DAG->getContext();
8309 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8312 /// \brief Get the alignment of the load used for this slice.
8313 unsigned getAlignment() const {
8314 unsigned Alignment = Origin->getAlignment();
8315 unsigned Offset = getOffsetFromBase();
8317 Alignment = MinAlign(Alignment, Alignment + Offset);
8321 /// \brief Check if this slice can be rewritten with legal operations.
8322 bool isLegal() const {
8323 // An invalid slice is not legal.
8324 if (!Origin || !Inst || !DAG)
8327 // Offsets are for indexed load only, we do not handle that.
8328 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8331 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8333 // Check that the type is legal.
8334 EVT SliceType = getLoadedType();
8335 if (!TLI.isTypeLegal(SliceType))
8338 // Check that the load is legal for this type.
8339 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8342 // Check that the offset can be computed.
8343 // 1. Check its type.
8344 EVT PtrType = Origin->getBasePtr().getValueType();
8345 if (PtrType == MVT::Untyped || PtrType.isExtended())
8348 // 2. Check that it fits in the immediate.
8349 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8352 // 3. Check that the computation is legal.
8353 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8356 // Check that the zext is legal if it needs one.
8357 EVT TruncateType = Inst->getValueType(0);
8358 if (TruncateType != SliceType &&
8359 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8365 /// \brief Get the offset in bytes of this slice in the original chunk of
8367 /// \pre DAG != nullptr.
8368 uint64_t getOffsetFromBase() const {
8369 assert(DAG && "Missing context.");
8371 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8372 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8373 uint64_t Offset = Shift / 8;
8374 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8375 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8376 "The size of the original loaded type is not a multiple of a"
8378 // If Offset is bigger than TySizeInBytes, it means we are loading all
8379 // zeros. This should have been optimized before in the process.
8380 assert(TySizeInBytes > Offset &&
8381 "Invalid shift amount for given loaded size");
8383 Offset = TySizeInBytes - Offset - getLoadedSize();
8387 /// \brief Generate the sequence of instructions to load the slice
8388 /// represented by this object and redirect the uses of this slice to
8389 /// this new sequence of instructions.
8390 /// \pre this->Inst && this->Origin are valid Instructions and this
8391 /// object passed the legal check: LoadedSlice::isLegal returned true.
8392 /// \return The last instruction of the sequence used to load the slice.
8393 SDValue loadSlice() const {
8394 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8395 const SDValue &OldBaseAddr = Origin->getBasePtr();
8396 SDValue BaseAddr = OldBaseAddr;
8397 // Get the offset in that chunk of bytes w.r.t. the endianess.
8398 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8399 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8401 // BaseAddr = BaseAddr + Offset.
8402 EVT ArithType = BaseAddr.getValueType();
8403 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8404 DAG->getConstant(Offset, ArithType));
8407 // Create the type of the loaded slice according to its size.
8408 EVT SliceType = getLoadedType();
8410 // Create the load for the slice.
8411 SDValue LastInst = DAG->getLoad(
8412 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8413 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8414 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8415 // If the final type is not the same as the loaded type, this means that
8416 // we have to pad with zero. Create a zero extend for that.
8417 EVT FinalType = Inst->getValueType(0);
8418 if (SliceType != FinalType)
8420 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8424 /// \brief Check if this slice can be merged with an expensive cross register
8425 /// bank copy. E.g.,
8427 /// f = bitcast i32 i to float
8428 bool canMergeExpensiveCrossRegisterBankCopy() const {
8429 if (!Inst || !Inst->hasOneUse())
8431 SDNode *Use = *Inst->use_begin();
8432 if (Use->getOpcode() != ISD::BITCAST)
8434 assert(DAG && "Missing context");
8435 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8436 EVT ResVT = Use->getValueType(0);
8437 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8438 const TargetRegisterClass *ArgRC =
8439 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8440 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8443 // At this point, we know that we perform a cross-register-bank copy.
8444 // Check if it is expensive.
8445 const TargetRegisterInfo *TRI =
8446 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8447 // Assume bitcasts are cheap, unless both register classes do not
8448 // explicitly share a common sub class.
8449 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8452 // Check if it will be merged with the load.
8453 // 1. Check the alignment constraint.
8454 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8455 ResVT.getTypeForEVT(*DAG->getContext()));
8457 if (RequiredAlignment > getAlignment())
8460 // 2. Check that the load is a legal operation for that type.
8461 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8464 // 3. Check that we do not have a zext in the way.
8465 if (Inst->getValueType(0) != getLoadedType())
8473 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8474 /// \p UsedBits looks like 0..0 1..1 0..0.
8475 static bool areUsedBitsDense(const APInt &UsedBits) {
8476 // If all the bits are one, this is dense!
8477 if (UsedBits.isAllOnesValue())
8480 // Get rid of the unused bits on the right.
8481 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8482 // Get rid of the unused bits on the left.
8483 if (NarrowedUsedBits.countLeadingZeros())
8484 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8485 // Check that the chunk of bits is completely used.
8486 return NarrowedUsedBits.isAllOnesValue();
8489 /// \brief Check whether or not \p First and \p Second are next to each other
8490 /// in memory. This means that there is no hole between the bits loaded
8491 /// by \p First and the bits loaded by \p Second.
8492 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8493 const LoadedSlice &Second) {
8494 assert(First.Origin == Second.Origin && First.Origin &&
8495 "Unable to match different memory origins.");
8496 APInt UsedBits = First.getUsedBits();
8497 assert((UsedBits & Second.getUsedBits()) == 0 &&
8498 "Slices are not supposed to overlap.");
8499 UsedBits |= Second.getUsedBits();
8500 return areUsedBitsDense(UsedBits);
8503 /// \brief Adjust the \p GlobalLSCost according to the target
8504 /// paring capabilities and the layout of the slices.
8505 /// \pre \p GlobalLSCost should account for at least as many loads as
8506 /// there is in the slices in \p LoadedSlices.
8507 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8508 LoadedSlice::Cost &GlobalLSCost) {
8509 unsigned NumberOfSlices = LoadedSlices.size();
8510 // If there is less than 2 elements, no pairing is possible.
8511 if (NumberOfSlices < 2)
8514 // Sort the slices so that elements that are likely to be next to each
8515 // other in memory are next to each other in the list.
8516 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8517 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8518 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8519 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8521 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8522 // First (resp. Second) is the first (resp. Second) potentially candidate
8523 // to be placed in a paired load.
8524 const LoadedSlice *First = nullptr;
8525 const LoadedSlice *Second = nullptr;
8526 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8527 // Set the beginning of the pair.
8530 Second = &LoadedSlices[CurrSlice];
8532 // If First is NULL, it means we start a new pair.
8533 // Get to the next slice.
8537 EVT LoadedType = First->getLoadedType();
8539 // If the types of the slices are different, we cannot pair them.
8540 if (LoadedType != Second->getLoadedType())
8543 // Check if the target supplies paired loads for this type.
8544 unsigned RequiredAlignment = 0;
8545 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8546 // move to the next pair, this type is hopeless.
8550 // Check if we meet the alignment requirement.
8551 if (RequiredAlignment > First->getAlignment())
8554 // Check that both loads are next to each other in memory.
8555 if (!areSlicesNextToEachOther(*First, *Second))
8558 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8559 --GlobalLSCost.Loads;
8560 // Move to the next pair.
8565 /// \brief Check the profitability of all involved LoadedSlice.
8566 /// Currently, it is considered profitable if there is exactly two
8567 /// involved slices (1) which are (2) next to each other in memory, and
8568 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8570 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8571 /// the elements themselves.
8573 /// FIXME: When the cost model will be mature enough, we can relax
8574 /// constraints (1) and (2).
8575 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8576 const APInt &UsedBits, bool ForCodeSize) {
8577 unsigned NumberOfSlices = LoadedSlices.size();
8578 if (StressLoadSlicing)
8579 return NumberOfSlices > 1;
8582 if (NumberOfSlices != 2)
8586 if (!areUsedBitsDense(UsedBits))
8590 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8591 // The original code has one big load.
8593 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8594 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8595 // Accumulate the cost of all the slices.
8596 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8597 GlobalSlicingCost += SliceCost;
8599 // Account as cost in the original configuration the gain obtained
8600 // with the current slices.
8601 OrigCost.addSliceGain(LS);
8604 // If the target supports paired load, adjust the cost accordingly.
8605 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8606 return OrigCost > GlobalSlicingCost;
8609 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8610 /// operations, split it in the various pieces being extracted.
8612 /// This sort of thing is introduced by SROA.
8613 /// This slicing takes care not to insert overlapping loads.
8614 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8615 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8616 if (Level < AfterLegalizeDAG)
8619 LoadSDNode *LD = cast<LoadSDNode>(N);
8620 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8621 !LD->getValueType(0).isInteger())
8624 // Keep track of already used bits to detect overlapping values.
8625 // In that case, we will just abort the transformation.
8626 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8628 SmallVector<LoadedSlice, 4> LoadedSlices;
8630 // Check if this load is used as several smaller chunks of bits.
8631 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8632 // of computation for each trunc.
8633 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8634 UI != UIEnd; ++UI) {
8635 // Skip the uses of the chain.
8636 if (UI.getUse().getResNo() != 0)
8642 // Check if this is a trunc(lshr).
8643 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8644 isa<ConstantSDNode>(User->getOperand(1))) {
8645 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8646 User = *User->use_begin();
8649 // At this point, User is a Truncate, iff we encountered, trunc or
8651 if (User->getOpcode() != ISD::TRUNCATE)
8654 // The width of the type must be a power of 2 and greater than 8-bits.
8655 // Otherwise the load cannot be represented in LLVM IR.
8656 // Moreover, if we shifted with a non-8-bits multiple, the slice
8657 // will be across several bytes. We do not support that.
8658 unsigned Width = User->getValueSizeInBits(0);
8659 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8662 // Build the slice for this chain of computations.
8663 LoadedSlice LS(User, LD, Shift, &DAG);
8664 APInt CurrentUsedBits = LS.getUsedBits();
8666 // Check if this slice overlaps with another.
8667 if ((CurrentUsedBits & UsedBits) != 0)
8669 // Update the bits used globally.
8670 UsedBits |= CurrentUsedBits;
8672 // Check if the new slice would be legal.
8676 // Record the slice.
8677 LoadedSlices.push_back(LS);
8680 // Abort slicing if it does not seem to be profitable.
8681 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8686 // Rewrite each chain to use an independent load.
8687 // By construction, each chain can be represented by a unique load.
8689 // Prepare the argument for the new token factor for all the slices.
8690 SmallVector<SDValue, 8> ArgChains;
8691 for (SmallVectorImpl<LoadedSlice>::const_iterator
8692 LSIt = LoadedSlices.begin(),
8693 LSItEnd = LoadedSlices.end();
8694 LSIt != LSItEnd; ++LSIt) {
8695 SDValue SliceInst = LSIt->loadSlice();
8696 CombineTo(LSIt->Inst, SliceInst, true);
8697 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8698 SliceInst = SliceInst.getOperand(0);
8699 assert(SliceInst->getOpcode() == ISD::LOAD &&
8700 "It takes more than a zext to get to the loaded slice!!");
8701 ArgChains.push_back(SliceInst.getValue(1));
8704 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8706 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8710 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8711 /// load is having specific bytes cleared out. If so, return the byte size
8712 /// being masked out and the shift amount.
8713 static std::pair<unsigned, unsigned>
8714 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8715 std::pair<unsigned, unsigned> Result(0, 0);
8717 // Check for the structure we're looking for.
8718 if (V->getOpcode() != ISD::AND ||
8719 !isa<ConstantSDNode>(V->getOperand(1)) ||
8720 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8723 // Check the chain and pointer.
8724 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8725 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8727 // The store should be chained directly to the load or be an operand of a
8729 if (LD == Chain.getNode())
8731 else if (Chain->getOpcode() != ISD::TokenFactor)
8732 return Result; // Fail.
8735 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8736 if (Chain->getOperand(i).getNode() == LD) {
8740 if (!isOk) return Result;
8743 // This only handles simple types.
8744 if (V.getValueType() != MVT::i16 &&
8745 V.getValueType() != MVT::i32 &&
8746 V.getValueType() != MVT::i64)
8749 // Check the constant mask. Invert it so that the bits being masked out are
8750 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8751 // follow the sign bit for uniformity.
8752 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8753 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8754 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8755 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8756 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8757 if (NotMaskLZ == 64) return Result; // All zero mask.
8759 // See if we have a continuous run of bits. If so, we have 0*1+0*
8760 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8763 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8764 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8765 NotMaskLZ -= 64-V.getValueSizeInBits();
8767 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8768 switch (MaskedBytes) {
8772 default: return Result; // All one mask, or 5-byte mask.
8775 // Verify that the first bit starts at a multiple of mask so that the access
8776 // is aligned the same as the access width.
8777 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8779 Result.first = MaskedBytes;
8780 Result.second = NotMaskTZ/8;
8785 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8786 /// provides a value as specified by MaskInfo. If so, replace the specified
8787 /// store with a narrower store of truncated IVal.
8789 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8790 SDValue IVal, StoreSDNode *St,
8792 unsigned NumBytes = MaskInfo.first;
8793 unsigned ByteShift = MaskInfo.second;
8794 SelectionDAG &DAG = DC->getDAG();
8796 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8797 // that uses this. If not, this is not a replacement.
8798 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8799 ByteShift*8, (ByteShift+NumBytes)*8);
8800 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8802 // Check that it is legal on the target to do this. It is legal if the new
8803 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8805 MVT VT = MVT::getIntegerVT(NumBytes*8);
8806 if (!DC->isTypeLegal(VT))
8809 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8810 // shifted by ByteShift and truncated down to NumBytes.
8812 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8813 DAG.getConstant(ByteShift*8,
8814 DC->getShiftAmountTy(IVal.getValueType())));
8816 // Figure out the offset for the store and the alignment of the access.
8818 unsigned NewAlign = St->getAlignment();
8820 if (DAG.getTargetLoweringInfo().isLittleEndian())
8821 StOffset = ByteShift;
8823 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8825 SDValue Ptr = St->getBasePtr();
8827 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8828 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8829 NewAlign = MinAlign(NewAlign, StOffset);
8832 // Truncate down to the new size.
8833 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8836 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8837 St->getPointerInfo().getWithOffset(StOffset),
8838 false, false, NewAlign).getNode();
8842 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8843 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8844 /// of the loaded bits, try narrowing the load and store if it would end up
8845 /// being a win for performance or code size.
8846 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8847 StoreSDNode *ST = cast<StoreSDNode>(N);
8848 if (ST->isVolatile())
8851 SDValue Chain = ST->getChain();
8852 SDValue Value = ST->getValue();
8853 SDValue Ptr = ST->getBasePtr();
8854 EVT VT = Value.getValueType();
8856 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8859 unsigned Opc = Value.getOpcode();
8861 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8862 // is a byte mask indicating a consecutive number of bytes, check to see if
8863 // Y is known to provide just those bytes. If so, we try to replace the
8864 // load + replace + store sequence with a single (narrower) store, which makes
8866 if (Opc == ISD::OR) {
8867 std::pair<unsigned, unsigned> MaskedLoad;
8868 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8869 if (MaskedLoad.first)
8870 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8871 Value.getOperand(1), ST,this))
8872 return SDValue(NewST, 0);
8874 // Or is commutative, so try swapping X and Y.
8875 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8876 if (MaskedLoad.first)
8877 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8878 Value.getOperand(0), ST,this))
8879 return SDValue(NewST, 0);
8882 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8883 Value.getOperand(1).getOpcode() != ISD::Constant)
8886 SDValue N0 = Value.getOperand(0);
8887 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8888 Chain == SDValue(N0.getNode(), 1)) {
8889 LoadSDNode *LD = cast<LoadSDNode>(N0);
8890 if (LD->getBasePtr() != Ptr ||
8891 LD->getPointerInfo().getAddrSpace() !=
8892 ST->getPointerInfo().getAddrSpace())
8895 // Find the type to narrow it the load / op / store to.
8896 SDValue N1 = Value.getOperand(1);
8897 unsigned BitWidth = N1.getValueSizeInBits();
8898 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8899 if (Opc == ISD::AND)
8900 Imm ^= APInt::getAllOnesValue(BitWidth);
8901 if (Imm == 0 || Imm.isAllOnesValue())
8903 unsigned ShAmt = Imm.countTrailingZeros();
8904 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8905 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8906 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8907 while (NewBW < BitWidth &&
8908 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8909 TLI.isNarrowingProfitable(VT, NewVT))) {
8910 NewBW = NextPowerOf2(NewBW);
8911 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8913 if (NewBW >= BitWidth)
8916 // If the lsb changed does not start at the type bitwidth boundary,
8917 // start at the previous one.
8919 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8920 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8921 std::min(BitWidth, ShAmt + NewBW));
8922 if ((Imm & Mask) == Imm) {
8923 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8924 if (Opc == ISD::AND)
8925 NewImm ^= APInt::getAllOnesValue(NewBW);
8926 uint64_t PtrOff = ShAmt / 8;
8927 // For big endian targets, we need to adjust the offset to the pointer to
8928 // load the correct bytes.
8929 if (TLI.isBigEndian())
8930 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8932 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8933 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8934 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8937 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8938 Ptr.getValueType(), Ptr,
8939 DAG.getConstant(PtrOff, Ptr.getValueType()));
8940 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8941 LD->getChain(), NewPtr,
8942 LD->getPointerInfo().getWithOffset(PtrOff),
8943 LD->isVolatile(), LD->isNonTemporal(),
8944 LD->isInvariant(), NewAlign,
8946 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8947 DAG.getConstant(NewImm, NewVT));
8948 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8950 ST->getPointerInfo().getWithOffset(PtrOff),
8951 false, false, NewAlign);
8953 AddToWorklist(NewPtr.getNode());
8954 AddToWorklist(NewLD.getNode());
8955 AddToWorklist(NewVal.getNode());
8956 WorklistRemover DeadNodes(*this);
8957 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8966 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8967 /// if the load value isn't used by any other operations, then consider
8968 /// transforming the pair to integer load / store operations if the target
8969 /// deems the transformation profitable.
8970 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8971 StoreSDNode *ST = cast<StoreSDNode>(N);
8972 SDValue Chain = ST->getChain();
8973 SDValue Value = ST->getValue();
8974 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8975 Value.hasOneUse() &&
8976 Chain == SDValue(Value.getNode(), 1)) {
8977 LoadSDNode *LD = cast<LoadSDNode>(Value);
8978 EVT VT = LD->getMemoryVT();
8979 if (!VT.isFloatingPoint() ||
8980 VT != ST->getMemoryVT() ||
8981 LD->isNonTemporal() ||
8982 ST->isNonTemporal() ||
8983 LD->getPointerInfo().getAddrSpace() != 0 ||
8984 ST->getPointerInfo().getAddrSpace() != 0)
8987 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8988 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8989 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8990 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8991 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8994 unsigned LDAlign = LD->getAlignment();
8995 unsigned STAlign = ST->getAlignment();
8996 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8997 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8998 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9001 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9002 LD->getChain(), LD->getBasePtr(),
9003 LD->getPointerInfo(),
9004 false, false, false, LDAlign);
9006 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9007 NewLD, ST->getBasePtr(),
9008 ST->getPointerInfo(),
9009 false, false, STAlign);
9011 AddToWorklist(NewLD.getNode());
9012 AddToWorklist(NewST.getNode());
9013 WorklistRemover DeadNodes(*this);
9014 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9022 /// Helper struct to parse and store a memory address as base + index + offset.
9023 /// We ignore sign extensions when it is safe to do so.
9024 /// The following two expressions are not equivalent. To differentiate we need
9025 /// to store whether there was a sign extension involved in the index
9027 /// (load (i64 add (i64 copyfromreg %c)
9028 /// (i64 signextend (add (i8 load %index)
9032 /// (load (i64 add (i64 copyfromreg %c)
9033 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9035 struct BaseIndexOffset {
9039 bool IsIndexSignExt;
9041 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9043 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9044 bool IsIndexSignExt) :
9045 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9047 bool equalBaseIndex(const BaseIndexOffset &Other) {
9048 return Other.Base == Base && Other.Index == Index &&
9049 Other.IsIndexSignExt == IsIndexSignExt;
9052 /// Parses tree in Ptr for base, index, offset addresses.
9053 static BaseIndexOffset match(SDValue Ptr) {
9054 bool IsIndexSignExt = false;
9056 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9057 // instruction, then it could be just the BASE or everything else we don't
9058 // know how to handle. Just use Ptr as BASE and give up.
9059 if (Ptr->getOpcode() != ISD::ADD)
9060 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9062 // We know that we have at least an ADD instruction. Try to pattern match
9063 // the simple case of BASE + OFFSET.
9064 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9065 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9066 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9070 // Inside a loop the current BASE pointer is calculated using an ADD and a
9071 // MUL instruction. In this case Ptr is the actual BASE pointer.
9072 // (i64 add (i64 %array_ptr)
9073 // (i64 mul (i64 %induction_var)
9074 // (i64 %element_size)))
9075 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9076 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9078 // Look at Base + Index + Offset cases.
9079 SDValue Base = Ptr->getOperand(0);
9080 SDValue IndexOffset = Ptr->getOperand(1);
9082 // Skip signextends.
9083 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9084 IndexOffset = IndexOffset->getOperand(0);
9085 IsIndexSignExt = true;
9088 // Either the case of Base + Index (no offset) or something else.
9089 if (IndexOffset->getOpcode() != ISD::ADD)
9090 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9092 // Now we have the case of Base + Index + offset.
9093 SDValue Index = IndexOffset->getOperand(0);
9094 SDValue Offset = IndexOffset->getOperand(1);
9096 if (!isa<ConstantSDNode>(Offset))
9097 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9099 // Ignore signextends.
9100 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9101 Index = Index->getOperand(0);
9102 IsIndexSignExt = true;
9103 } else IsIndexSignExt = false;
9105 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9106 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9110 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9111 /// is located in a sequence of memory operations connected by a chain.
9113 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9114 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9115 // Ptr to the mem node.
9116 LSBaseSDNode *MemNode;
9117 // Offset from the base ptr.
9118 int64_t OffsetFromBase;
9119 // What is the sequence number of this mem node.
9120 // Lowest mem operand in the DAG starts at zero.
9121 unsigned SequenceNum;
9124 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9125 EVT MemVT = St->getMemoryVT();
9126 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9127 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9128 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9130 // Don't merge vectors into wider inputs.
9131 if (MemVT.isVector() || !MemVT.isSimple())
9134 // Perform an early exit check. Do not bother looking at stored values that
9135 // are not constants or loads.
9136 SDValue StoredVal = St->getValue();
9137 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9138 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9142 // Only look at ends of store sequences.
9143 SDValue Chain = SDValue(St, 0);
9144 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9147 // This holds the base pointer, index, and the offset in bytes from the base
9149 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9151 // We must have a base and an offset.
9152 if (!BasePtr.Base.getNode())
9155 // Do not handle stores to undef base pointers.
9156 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9159 // Save the LoadSDNodes that we find in the chain.
9160 // We need to make sure that these nodes do not interfere with
9161 // any of the store nodes.
9162 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9164 // Save the StoreSDNodes that we find in the chain.
9165 SmallVector<MemOpLink, 8> StoreNodes;
9167 // Walk up the chain and look for nodes with offsets from the same
9168 // base pointer. Stop when reaching an instruction with a different kind
9169 // or instruction which has a different base pointer.
9171 StoreSDNode *Index = St;
9173 // If the chain has more than one use, then we can't reorder the mem ops.
9174 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9177 // Find the base pointer and offset for this memory node.
9178 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9180 // Check that the base pointer is the same as the original one.
9181 if (!Ptr.equalBaseIndex(BasePtr))
9184 // Check that the alignment is the same.
9185 if (Index->getAlignment() != St->getAlignment())
9188 // The memory operands must not be volatile.
9189 if (Index->isVolatile() || Index->isIndexed())
9193 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9194 if (St->isTruncatingStore())
9197 // The stored memory type must be the same.
9198 if (Index->getMemoryVT() != MemVT)
9201 // We do not allow unaligned stores because we want to prevent overriding
9203 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9206 // We found a potential memory operand to merge.
9207 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9209 // Find the next memory operand in the chain. If the next operand in the
9210 // chain is a store then move up and continue the scan with the next
9211 // memory operand. If the next operand is a load save it and use alias
9212 // information to check if it interferes with anything.
9213 SDNode *NextInChain = Index->getChain().getNode();
9215 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9216 // We found a store node. Use it for the next iteration.
9219 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9220 if (Ldn->isVolatile()) {
9225 // Save the load node for later. Continue the scan.
9226 AliasLoadNodes.push_back(Ldn);
9227 NextInChain = Ldn->getChain().getNode();
9236 // Check if there is anything to merge.
9237 if (StoreNodes.size() < 2)
9240 // Sort the memory operands according to their distance from the base pointer.
9241 std::sort(StoreNodes.begin(), StoreNodes.end(),
9242 [](MemOpLink LHS, MemOpLink RHS) {
9243 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9244 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9245 LHS.SequenceNum > RHS.SequenceNum);
9248 // Scan the memory operations on the chain and find the first non-consecutive
9249 // store memory address.
9250 unsigned LastConsecutiveStore = 0;
9251 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9252 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9254 // Check that the addresses are consecutive starting from the second
9255 // element in the list of stores.
9257 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9258 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9263 // Check if this store interferes with any of the loads that we found.
9264 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9265 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9269 // We found a load that alias with this store. Stop the sequence.
9273 // Mark this node as useful.
9274 LastConsecutiveStore = i;
9277 // The node with the lowest store address.
9278 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9280 // Store the constants into memory as one consecutive store.
9282 unsigned LastLegalType = 0;
9283 unsigned LastLegalVectorType = 0;
9284 bool NonZero = false;
9285 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9286 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9287 SDValue StoredVal = St->getValue();
9289 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9290 NonZero |= !C->isNullValue();
9291 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9292 NonZero |= !C->getConstantFPValue()->isNullValue();
9298 // Find a legal type for the constant store.
9299 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9300 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9301 if (TLI.isTypeLegal(StoreTy))
9302 LastLegalType = i+1;
9303 // Or check whether a truncstore is legal.
9304 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9305 TargetLowering::TypePromoteInteger) {
9306 EVT LegalizedStoredValueTy =
9307 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9308 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9309 LastLegalType = i+1;
9312 // Find a legal type for the vector store.
9313 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9314 if (TLI.isTypeLegal(Ty))
9315 LastLegalVectorType = i + 1;
9318 // We only use vectors if the constant is known to be zero and the
9319 // function is not marked with the noimplicitfloat attribute.
9320 if (NonZero || NoVectors)
9321 LastLegalVectorType = 0;
9323 // Check if we found a legal integer type to store.
9324 if (LastLegalType == 0 && LastLegalVectorType == 0)
9327 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9328 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9330 // Make sure we have something to merge.
9334 unsigned EarliestNodeUsed = 0;
9335 for (unsigned i=0; i < NumElem; ++i) {
9336 // Find a chain for the new wide-store operand. Notice that some
9337 // of the store nodes that we found may not be selected for inclusion
9338 // in the wide store. The chain we use needs to be the chain of the
9339 // earliest store node which is *used* and replaced by the wide store.
9340 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9341 EarliestNodeUsed = i;
9344 // The earliest Node in the DAG.
9345 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9346 SDLoc DL(StoreNodes[0].MemNode);
9350 // Find a legal type for the vector store.
9351 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9352 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9353 StoredVal = DAG.getConstant(0, Ty);
9355 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9356 APInt StoreInt(StoreBW, 0);
9358 // Construct a single integer constant which is made of the smaller
9360 bool IsLE = TLI.isLittleEndian();
9361 for (unsigned i = 0; i < NumElem ; ++i) {
9362 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9363 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9364 SDValue Val = St->getValue();
9365 StoreInt<<=ElementSizeBytes*8;
9366 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9367 StoreInt|=C->getAPIntValue().zext(StoreBW);
9368 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9369 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9371 assert(false && "Invalid constant element type");
9375 // Create the new Load and Store operations.
9376 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9377 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9380 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9381 FirstInChain->getBasePtr(),
9382 FirstInChain->getPointerInfo(),
9384 FirstInChain->getAlignment());
9386 // Replace the first store with the new store
9387 CombineTo(EarliestOp, NewStore);
9388 // Erase all other stores.
9389 for (unsigned i = 0; i < NumElem ; ++i) {
9390 if (StoreNodes[i].MemNode == EarliestOp)
9392 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9393 // ReplaceAllUsesWith will replace all uses that existed when it was
9394 // called, but graph optimizations may cause new ones to appear. For
9395 // example, the case in pr14333 looks like
9397 // St's chain -> St -> another store -> X
9399 // And the only difference from St to the other store is the chain.
9400 // When we change it's chain to be St's chain they become identical,
9401 // get CSEed and the net result is that X is now a use of St.
9402 // Since we know that St is redundant, just iterate.
9403 while (!St->use_empty())
9404 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9405 deleteAndRecombine(St);
9411 // Below we handle the case of multiple consecutive stores that
9412 // come from multiple consecutive loads. We merge them into a single
9413 // wide load and a single wide store.
9415 // Look for load nodes which are used by the stored values.
9416 SmallVector<MemOpLink, 8> LoadNodes;
9418 // Find acceptable loads. Loads need to have the same chain (token factor),
9419 // must not be zext, volatile, indexed, and they must be consecutive.
9420 BaseIndexOffset LdBasePtr;
9421 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9422 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9423 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9426 // Loads must only have one use.
9427 if (!Ld->hasNUsesOfValue(1, 0))
9430 // Check that the alignment is the same as the stores.
9431 if (Ld->getAlignment() != St->getAlignment())
9434 // The memory operands must not be volatile.
9435 if (Ld->isVolatile() || Ld->isIndexed())
9438 // We do not accept ext loads.
9439 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9442 // The stored memory type must be the same.
9443 if (Ld->getMemoryVT() != MemVT)
9446 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9447 // If this is not the first ptr that we check.
9448 if (LdBasePtr.Base.getNode()) {
9449 // The base ptr must be the same.
9450 if (!LdPtr.equalBaseIndex(LdBasePtr))
9453 // Check that all other base pointers are the same as this one.
9457 // We found a potential memory operand to merge.
9458 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9461 if (LoadNodes.size() < 2)
9464 // If we have load/store pair instructions and we only have two values,
9466 unsigned RequiredAlignment;
9467 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9468 St->getAlignment() >= RequiredAlignment)
9471 // Scan the memory operations on the chain and find the first non-consecutive
9472 // load memory address. These variables hold the index in the store node
9474 unsigned LastConsecutiveLoad = 0;
9475 // This variable refers to the size and not index in the array.
9476 unsigned LastLegalVectorType = 0;
9477 unsigned LastLegalIntegerType = 0;
9478 StartAddress = LoadNodes[0].OffsetFromBase;
9479 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9480 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9481 // All loads much share the same chain.
9482 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9485 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9486 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9488 LastConsecutiveLoad = i;
9490 // Find a legal type for the vector store.
9491 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9492 if (TLI.isTypeLegal(StoreTy))
9493 LastLegalVectorType = i + 1;
9495 // Find a legal type for the integer store.
9496 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9497 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9498 if (TLI.isTypeLegal(StoreTy))
9499 LastLegalIntegerType = i + 1;
9500 // Or check whether a truncstore and extload is legal.
9501 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9502 TargetLowering::TypePromoteInteger) {
9503 EVT LegalizedStoredValueTy =
9504 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9505 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9506 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9507 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9508 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9509 LastLegalIntegerType = i+1;
9513 // Only use vector types if the vector type is larger than the integer type.
9514 // If they are the same, use integers.
9515 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9516 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9518 // We add +1 here because the LastXXX variables refer to location while
9519 // the NumElem refers to array/index size.
9520 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9521 NumElem = std::min(LastLegalType, NumElem);
9526 // The earliest Node in the DAG.
9527 unsigned EarliestNodeUsed = 0;
9528 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9529 for (unsigned i=1; i<NumElem; ++i) {
9530 // Find a chain for the new wide-store operand. Notice that some
9531 // of the store nodes that we found may not be selected for inclusion
9532 // in the wide store. The chain we use needs to be the chain of the
9533 // earliest store node which is *used* and replaced by the wide store.
9534 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9535 EarliestNodeUsed = i;
9538 // Find if it is better to use vectors or integers to load and store
9542 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9544 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9545 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9548 SDLoc LoadDL(LoadNodes[0].MemNode);
9549 SDLoc StoreDL(StoreNodes[0].MemNode);
9551 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9552 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9553 FirstLoad->getChain(),
9554 FirstLoad->getBasePtr(),
9555 FirstLoad->getPointerInfo(),
9556 false, false, false,
9557 FirstLoad->getAlignment());
9559 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9560 FirstInChain->getBasePtr(),
9561 FirstInChain->getPointerInfo(), false, false,
9562 FirstInChain->getAlignment());
9564 // Replace one of the loads with the new load.
9565 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9566 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9567 SDValue(NewLoad.getNode(), 1));
9569 // Remove the rest of the load chains.
9570 for (unsigned i = 1; i < NumElem ; ++i) {
9571 // Replace all chain users of the old load nodes with the chain of the new
9573 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9574 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9577 // Replace the first store with the new store.
9578 CombineTo(EarliestOp, NewStore);
9579 // Erase all other stores.
9580 for (unsigned i = 0; i < NumElem ; ++i) {
9581 // Remove all Store nodes.
9582 if (StoreNodes[i].MemNode == EarliestOp)
9584 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9585 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9586 deleteAndRecombine(St);
9592 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9593 StoreSDNode *ST = cast<StoreSDNode>(N);
9594 SDValue Chain = ST->getChain();
9595 SDValue Value = ST->getValue();
9596 SDValue Ptr = ST->getBasePtr();
9598 // If this is a store of a bit convert, store the input value if the
9599 // resultant store does not need a higher alignment than the original.
9600 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9601 ST->isUnindexed()) {
9602 unsigned OrigAlign = ST->getAlignment();
9603 EVT SVT = Value.getOperand(0).getValueType();
9604 unsigned Align = TLI.getDataLayout()->
9605 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9606 if (Align <= OrigAlign &&
9607 ((!LegalOperations && !ST->isVolatile()) ||
9608 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9609 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9610 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9611 ST->isNonTemporal(), OrigAlign,
9615 // Turn 'store undef, Ptr' -> nothing.
9616 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9619 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9620 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9621 // NOTE: If the original store is volatile, this transform must not increase
9622 // the number of stores. For example, on x86-32 an f64 can be stored in one
9623 // processor operation but an i64 (which is not legal) requires two. So the
9624 // transform should not be done in this case.
9625 if (Value.getOpcode() != ISD::TargetConstantFP) {
9627 switch (CFP->getSimpleValueType(0).SimpleTy) {
9628 default: llvm_unreachable("Unknown FP type");
9629 case MVT::f16: // We don't do this for these yet.
9635 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9636 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9637 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9638 bitcastToAPInt().getZExtValue(), MVT::i32);
9639 return DAG.getStore(Chain, SDLoc(N), Tmp,
9640 Ptr, ST->getMemOperand());
9644 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9645 !ST->isVolatile()) ||
9646 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9647 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9648 getZExtValue(), MVT::i64);
9649 return DAG.getStore(Chain, SDLoc(N), Tmp,
9650 Ptr, ST->getMemOperand());
9653 if (!ST->isVolatile() &&
9654 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9655 // Many FP stores are not made apparent until after legalize, e.g. for
9656 // argument passing. Since this is so common, custom legalize the
9657 // 64-bit integer store into two 32-bit stores.
9658 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9659 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9660 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9661 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9663 unsigned Alignment = ST->getAlignment();
9664 bool isVolatile = ST->isVolatile();
9665 bool isNonTemporal = ST->isNonTemporal();
9666 AAMDNodes AAInfo = ST->getAAInfo();
9668 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9669 Ptr, ST->getPointerInfo(),
9670 isVolatile, isNonTemporal,
9671 ST->getAlignment(), AAInfo);
9672 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9673 DAG.getConstant(4, Ptr.getValueType()));
9674 Alignment = MinAlign(Alignment, 4U);
9675 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9676 Ptr, ST->getPointerInfo().getWithOffset(4),
9677 isVolatile, isNonTemporal,
9679 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9688 // Try to infer better alignment information than the store already has.
9689 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9690 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9691 if (Align > ST->getAlignment())
9692 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9693 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9694 ST->isVolatile(), ST->isNonTemporal(), Align,
9699 // Try transforming a pair floating point load / store ops to integer
9700 // load / store ops.
9701 SDValue NewST = TransformFPLoadStorePair(N);
9702 if (NewST.getNode())
9705 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9706 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9708 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9709 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9712 if (UseAA && ST->isUnindexed()) {
9713 // Walk up chain skipping non-aliasing memory nodes.
9714 SDValue BetterChain = FindBetterChain(N, Chain);
9716 // If there is a better chain.
9717 if (Chain != BetterChain) {
9720 // Replace the chain to avoid dependency.
9721 if (ST->isTruncatingStore()) {
9722 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9723 ST->getMemoryVT(), ST->getMemOperand());
9725 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9726 ST->getMemOperand());
9729 // Create token to keep both nodes around.
9730 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9731 MVT::Other, Chain, ReplStore);
9733 // Make sure the new and old chains are cleaned up.
9734 AddToWorklist(Token.getNode());
9736 // Don't add users to work list.
9737 return CombineTo(N, Token, false);
9741 // Try transforming N to an indexed store.
9742 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9743 return SDValue(N, 0);
9745 // FIXME: is there such a thing as a truncating indexed store?
9746 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9747 Value.getValueType().isInteger()) {
9748 // See if we can simplify the input to this truncstore with knowledge that
9749 // only the low bits are being used. For example:
9750 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9752 GetDemandedBits(Value,
9753 APInt::getLowBitsSet(
9754 Value.getValueType().getScalarType().getSizeInBits(),
9755 ST->getMemoryVT().getScalarType().getSizeInBits()));
9756 AddToWorklist(Value.getNode());
9757 if (Shorter.getNode())
9758 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9759 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9761 // Otherwise, see if we can simplify the operation with
9762 // SimplifyDemandedBits, which only works if the value has a single use.
9763 if (SimplifyDemandedBits(Value,
9764 APInt::getLowBitsSet(
9765 Value.getValueType().getScalarType().getSizeInBits(),
9766 ST->getMemoryVT().getScalarType().getSizeInBits())))
9767 return SDValue(N, 0);
9770 // If this is a load followed by a store to the same location, then the store
9772 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9773 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9774 ST->isUnindexed() && !ST->isVolatile() &&
9775 // There can't be any side effects between the load and store, such as
9777 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9778 // The store is dead, remove it.
9783 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9784 // truncating store. We can do this even if this is already a truncstore.
9785 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9786 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9787 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9788 ST->getMemoryVT())) {
9789 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9790 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9793 // Only perform this optimization before the types are legal, because we
9794 // don't want to perform this optimization on every DAGCombine invocation.
9796 bool EverChanged = false;
9799 // There can be multiple store sequences on the same chain.
9800 // Keep trying to merge store sequences until we are unable to do so
9801 // or until we merge the last store on the chain.
9802 bool Changed = MergeConsecutiveStores(ST);
9803 EverChanged |= Changed;
9804 if (!Changed) break;
9805 } while (ST->getOpcode() != ISD::DELETED_NODE);
9808 return SDValue(N, 0);
9811 return ReduceLoadOpStoreWidth(N);
9814 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9815 SDValue InVec = N->getOperand(0);
9816 SDValue InVal = N->getOperand(1);
9817 SDValue EltNo = N->getOperand(2);
9820 // If the inserted element is an UNDEF, just use the input vector.
9821 if (InVal.getOpcode() == ISD::UNDEF)
9824 EVT VT = InVec.getValueType();
9826 // If we can't generate a legal BUILD_VECTOR, exit
9827 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9830 // Check that we know which element is being inserted
9831 if (!isa<ConstantSDNode>(EltNo))
9833 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9835 // Canonicalize insert_vector_elt dag nodes.
9837 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9838 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9840 // Do this only if the child insert_vector node has one use; also
9841 // do this only if indices are both constants and Idx1 < Idx0.
9842 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9843 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9845 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9846 if (Elt < OtherElt) {
9848 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9849 InVec.getOperand(0), InVal, EltNo);
9850 AddToWorklist(NewOp.getNode());
9851 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9852 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9856 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9857 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9859 SmallVector<SDValue, 8> Ops;
9860 // Do not combine these two vectors if the output vector will not replace
9861 // the input vector.
9862 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9863 Ops.append(InVec.getNode()->op_begin(),
9864 InVec.getNode()->op_end());
9865 } else if (InVec.getOpcode() == ISD::UNDEF) {
9866 unsigned NElts = VT.getVectorNumElements();
9867 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9872 // Insert the element
9873 if (Elt < Ops.size()) {
9874 // All the operands of BUILD_VECTOR must have the same type;
9875 // we enforce that here.
9876 EVT OpVT = Ops[0].getValueType();
9877 if (InVal.getValueType() != OpVT)
9878 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9879 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9880 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9884 // Return the new vector
9885 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9888 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9889 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9890 EVT ResultVT = EVE->getValueType(0);
9891 EVT VecEltVT = InVecVT.getVectorElementType();
9892 unsigned Align = OriginalLoad->getAlignment();
9893 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9894 VecEltVT.getTypeForEVT(*DAG.getContext()));
9896 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9901 SDValue NewPtr = OriginalLoad->getBasePtr();
9903 EVT PtrType = NewPtr.getValueType();
9904 MachinePointerInfo MPI;
9905 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9906 int Elt = ConstEltNo->getZExtValue();
9907 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9908 if (TLI.isBigEndian())
9909 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9910 Offset = DAG.getConstant(PtrOff, PtrType);
9911 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9913 Offset = DAG.getNode(
9914 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9915 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9916 if (TLI.isBigEndian())
9917 Offset = DAG.getNode(
9918 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9919 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9920 MPI = OriginalLoad->getPointerInfo();
9922 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9924 // The replacement we need to do here is a little tricky: we need to
9925 // replace an extractelement of a load with a load.
9926 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9927 // Note that this replacement assumes that the extractvalue is the only
9928 // use of the load; that's okay because we don't want to perform this
9929 // transformation in other cases anyway.
9932 if (ResultVT.bitsGT(VecEltVT)) {
9933 // If the result type of vextract is wider than the load, then issue an
9934 // extending load instead.
9935 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9938 Load = DAG.getExtLoad(
9939 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9940 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9941 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9942 Chain = Load.getValue(1);
9945 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9946 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9947 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9948 Chain = Load.getValue(1);
9949 if (ResultVT.bitsLT(VecEltVT))
9950 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9952 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9954 WorklistRemover DeadNodes(*this);
9955 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9956 SDValue To[] = { Load, Chain };
9957 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9958 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9959 // worklist explicitly as well.
9960 AddToWorklist(Load.getNode());
9961 AddUsersToWorklist(Load.getNode()); // Add users too
9962 // Make sure to revisit this node to clean it up; it will usually be dead.
9965 return SDValue(EVE, 0);
9968 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9969 // (vextract (scalar_to_vector val, 0) -> val
9970 SDValue InVec = N->getOperand(0);
9971 EVT VT = InVec.getValueType();
9972 EVT NVT = N->getValueType(0);
9974 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9975 // Check if the result type doesn't match the inserted element type. A
9976 // SCALAR_TO_VECTOR may truncate the inserted element and the
9977 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9978 SDValue InOp = InVec.getOperand(0);
9979 if (InOp.getValueType() != NVT) {
9980 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9981 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9986 SDValue EltNo = N->getOperand(1);
9987 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9989 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9990 // We only perform this optimization before the op legalization phase because
9991 // we may introduce new vector instructions which are not backed by TD
9992 // patterns. For example on AVX, extracting elements from a wide vector
9993 // without using extract_subvector. However, if we can find an underlying
9994 // scalar value, then we can always use that.
9995 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9997 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9998 int NumElem = VT.getVectorNumElements();
9999 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10000 // Find the new index to extract from.
10001 int OrigElt = SVOp->getMaskElt(Elt);
10003 // Extracting an undef index is undef.
10005 return DAG.getUNDEF(NVT);
10007 // Select the right vector half to extract from.
10009 if (OrigElt < NumElem) {
10010 SVInVec = InVec->getOperand(0);
10012 SVInVec = InVec->getOperand(1);
10013 OrigElt -= NumElem;
10016 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10017 SDValue InOp = SVInVec.getOperand(OrigElt);
10018 if (InOp.getValueType() != NVT) {
10019 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10020 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10026 // FIXME: We should handle recursing on other vector shuffles and
10027 // scalar_to_vector here as well.
10029 if (!LegalOperations) {
10030 EVT IndexTy = TLI.getVectorIdxTy();
10031 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10032 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10036 bool BCNumEltsChanged = false;
10037 EVT ExtVT = VT.getVectorElementType();
10040 // If the result of load has to be truncated, then it's not necessarily
10042 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10045 if (InVec.getOpcode() == ISD::BITCAST) {
10046 // Don't duplicate a load with other uses.
10047 if (!InVec.hasOneUse())
10050 EVT BCVT = InVec.getOperand(0).getValueType();
10051 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10053 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10054 BCNumEltsChanged = true;
10055 InVec = InVec.getOperand(0);
10056 ExtVT = BCVT.getVectorElementType();
10059 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10060 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10061 ISD::isNormalLoad(InVec.getNode()) &&
10062 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10063 SDValue Index = N->getOperand(1);
10064 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10065 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10069 // Perform only after legalization to ensure build_vector / vector_shuffle
10070 // optimizations have already been done.
10071 if (!LegalOperations) return SDValue();
10073 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10074 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10075 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10078 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10080 LoadSDNode *LN0 = nullptr;
10081 const ShuffleVectorSDNode *SVN = nullptr;
10082 if (ISD::isNormalLoad(InVec.getNode())) {
10083 LN0 = cast<LoadSDNode>(InVec);
10084 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10085 InVec.getOperand(0).getValueType() == ExtVT &&
10086 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10087 // Don't duplicate a load with other uses.
10088 if (!InVec.hasOneUse())
10091 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10092 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10093 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10095 // (load $addr+1*size)
10097 // Don't duplicate a load with other uses.
10098 if (!InVec.hasOneUse())
10101 // If the bit convert changed the number of elements, it is unsafe
10102 // to examine the mask.
10103 if (BCNumEltsChanged)
10106 // Select the input vector, guarding against out of range extract vector.
10107 unsigned NumElems = VT.getVectorNumElements();
10108 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10109 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10111 if (InVec.getOpcode() == ISD::BITCAST) {
10112 // Don't duplicate a load with other uses.
10113 if (!InVec.hasOneUse())
10116 InVec = InVec.getOperand(0);
10118 if (ISD::isNormalLoad(InVec.getNode())) {
10119 LN0 = cast<LoadSDNode>(InVec);
10120 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10121 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10125 // Make sure we found a non-volatile load and the extractelement is
10127 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10130 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10132 return DAG.getUNDEF(LVT);
10134 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10140 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10141 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10142 // We perform this optimization post type-legalization because
10143 // the type-legalizer often scalarizes integer-promoted vectors.
10144 // Performing this optimization before may create bit-casts which
10145 // will be type-legalized to complex code sequences.
10146 // We perform this optimization only before the operation legalizer because we
10147 // may introduce illegal operations.
10148 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10151 unsigned NumInScalars = N->getNumOperands();
10153 EVT VT = N->getValueType(0);
10155 // Check to see if this is a BUILD_VECTOR of a bunch of values
10156 // which come from any_extend or zero_extend nodes. If so, we can create
10157 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10158 // optimizations. We do not handle sign-extend because we can't fill the sign
10160 EVT SourceType = MVT::Other;
10161 bool AllAnyExt = true;
10163 for (unsigned i = 0; i != NumInScalars; ++i) {
10164 SDValue In = N->getOperand(i);
10165 // Ignore undef inputs.
10166 if (In.getOpcode() == ISD::UNDEF) continue;
10168 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10169 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10171 // Abort if the element is not an extension.
10172 if (!ZeroExt && !AnyExt) {
10173 SourceType = MVT::Other;
10177 // The input is a ZeroExt or AnyExt. Check the original type.
10178 EVT InTy = In.getOperand(0).getValueType();
10180 // Check that all of the widened source types are the same.
10181 if (SourceType == MVT::Other)
10184 else if (InTy != SourceType) {
10185 // Multiple income types. Abort.
10186 SourceType = MVT::Other;
10190 // Check if all of the extends are ANY_EXTENDs.
10191 AllAnyExt &= AnyExt;
10194 // In order to have valid types, all of the inputs must be extended from the
10195 // same source type and all of the inputs must be any or zero extend.
10196 // Scalar sizes must be a power of two.
10197 EVT OutScalarTy = VT.getScalarType();
10198 bool ValidTypes = SourceType != MVT::Other &&
10199 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10200 isPowerOf2_32(SourceType.getSizeInBits());
10202 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10203 // turn into a single shuffle instruction.
10207 bool isLE = TLI.isLittleEndian();
10208 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10209 assert(ElemRatio > 1 && "Invalid element size ratio");
10210 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10211 DAG.getConstant(0, SourceType);
10213 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10214 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10216 // Populate the new build_vector
10217 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10218 SDValue Cast = N->getOperand(i);
10219 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10220 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10221 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10223 if (Cast.getOpcode() == ISD::UNDEF)
10224 In = DAG.getUNDEF(SourceType);
10226 In = Cast->getOperand(0);
10227 unsigned Index = isLE ? (i * ElemRatio) :
10228 (i * ElemRatio + (ElemRatio - 1));
10230 assert(Index < Ops.size() && "Invalid index");
10234 // The type of the new BUILD_VECTOR node.
10235 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10236 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10237 "Invalid vector size");
10238 // Check if the new vector type is legal.
10239 if (!isTypeLegal(VecVT)) return SDValue();
10241 // Make the new BUILD_VECTOR.
10242 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10244 // The new BUILD_VECTOR node has the potential to be further optimized.
10245 AddToWorklist(BV.getNode());
10246 // Bitcast to the desired type.
10247 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10250 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10251 EVT VT = N->getValueType(0);
10253 unsigned NumInScalars = N->getNumOperands();
10256 EVT SrcVT = MVT::Other;
10257 unsigned Opcode = ISD::DELETED_NODE;
10258 unsigned NumDefs = 0;
10260 for (unsigned i = 0; i != NumInScalars; ++i) {
10261 SDValue In = N->getOperand(i);
10262 unsigned Opc = In.getOpcode();
10264 if (Opc == ISD::UNDEF)
10267 // If all scalar values are floats and converted from integers.
10268 if (Opcode == ISD::DELETED_NODE &&
10269 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10276 EVT InVT = In.getOperand(0).getValueType();
10278 // If all scalar values are typed differently, bail out. It's chosen to
10279 // simplify BUILD_VECTOR of integer types.
10280 if (SrcVT == MVT::Other)
10287 // If the vector has just one element defined, it's not worth to fold it into
10288 // a vectorized one.
10292 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10293 && "Should only handle conversion from integer to float.");
10294 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10296 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10298 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10301 SmallVector<SDValue, 8> Opnds;
10302 for (unsigned i = 0; i != NumInScalars; ++i) {
10303 SDValue In = N->getOperand(i);
10305 if (In.getOpcode() == ISD::UNDEF)
10306 Opnds.push_back(DAG.getUNDEF(SrcVT));
10308 Opnds.push_back(In.getOperand(0));
10310 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10311 AddToWorklist(BV.getNode());
10313 return DAG.getNode(Opcode, dl, VT, BV);
10316 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10317 unsigned NumInScalars = N->getNumOperands();
10319 EVT VT = N->getValueType(0);
10321 // A vector built entirely of undefs is undef.
10322 if (ISD::allOperandsUndef(N))
10323 return DAG.getUNDEF(VT);
10325 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10329 V = reduceBuildVecConvertToConvertBuildVec(N);
10333 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10334 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10335 // at most two distinct vectors, turn this into a shuffle node.
10337 // May only combine to shuffle after legalize if shuffle is legal.
10338 if (LegalOperations &&
10339 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10342 SDValue VecIn1, VecIn2;
10343 for (unsigned i = 0; i != NumInScalars; ++i) {
10344 // Ignore undef inputs.
10345 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10347 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10348 // constant index, bail out.
10349 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10350 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10351 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10355 // We allow up to two distinct input vectors.
10356 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10357 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10360 if (!VecIn1.getNode()) {
10361 VecIn1 = ExtractedFromVec;
10362 } else if (!VecIn2.getNode()) {
10363 VecIn2 = ExtractedFromVec;
10365 // Too many inputs.
10366 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10371 // If everything is good, we can make a shuffle operation.
10372 if (VecIn1.getNode()) {
10373 SmallVector<int, 8> Mask;
10374 for (unsigned i = 0; i != NumInScalars; ++i) {
10375 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10376 Mask.push_back(-1);
10380 // If extracting from the first vector, just use the index directly.
10381 SDValue Extract = N->getOperand(i);
10382 SDValue ExtVal = Extract.getOperand(1);
10383 if (Extract.getOperand(0) == VecIn1) {
10384 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10385 if (ExtIndex > VT.getVectorNumElements())
10388 Mask.push_back(ExtIndex);
10392 // Otherwise, use InIdx + VecSize
10393 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10394 Mask.push_back(Idx+NumInScalars);
10397 // We can't generate a shuffle node with mismatched input and output types.
10398 // Attempt to transform a single input vector to the correct type.
10399 if ((VT != VecIn1.getValueType())) {
10400 // We don't support shuffeling between TWO values of different types.
10401 if (VecIn2.getNode())
10404 // We only support widening of vectors which are half the size of the
10405 // output registers. For example XMM->YMM widening on X86 with AVX.
10406 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10409 // If the input vector type has a different base type to the output
10410 // vector type, bail out.
10411 if (VecIn1.getValueType().getVectorElementType() !=
10412 VT.getVectorElementType())
10415 // Widen the input vector by adding undef values.
10416 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10417 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10420 // If VecIn2 is unused then change it to undef.
10421 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10423 // Check that we were able to transform all incoming values to the same
10425 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10426 VecIn1.getValueType() != VT)
10429 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10430 if (!isTypeLegal(VT))
10433 // Return the new VECTOR_SHUFFLE node.
10437 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10443 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10444 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10445 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10446 // inputs come from at most two distinct vectors, turn this into a shuffle
10449 // If we only have one input vector, we don't need to do any concatenation.
10450 if (N->getNumOperands() == 1)
10451 return N->getOperand(0);
10453 // Check if all of the operands are undefs.
10454 EVT VT = N->getValueType(0);
10455 if (ISD::allOperandsUndef(N))
10456 return DAG.getUNDEF(VT);
10458 // Optimize concat_vectors where one of the vectors is undef.
10459 if (N->getNumOperands() == 2 &&
10460 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10461 SDValue In = N->getOperand(0);
10462 assert(In.getValueType().isVector() && "Must concat vectors");
10464 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10465 if (In->getOpcode() == ISD::BITCAST &&
10466 !In->getOperand(0)->getValueType(0).isVector()) {
10467 SDValue Scalar = In->getOperand(0);
10468 EVT SclTy = Scalar->getValueType(0);
10470 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10473 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10474 VT.getSizeInBits() / SclTy.getSizeInBits());
10475 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10478 SDLoc dl = SDLoc(N);
10479 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10480 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10484 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10485 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10486 if (N->getNumOperands() == 2 &&
10487 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10488 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10489 EVT VT = N->getValueType(0);
10490 SDValue N0 = N->getOperand(0);
10491 SDValue N1 = N->getOperand(1);
10492 SmallVector<SDValue, 8> Opnds;
10493 unsigned BuildVecNumElts = N0.getNumOperands();
10495 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10496 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10497 if (SclTy0.isFloatingPoint()) {
10498 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10499 Opnds.push_back(N0.getOperand(i));
10500 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10501 Opnds.push_back(N1.getOperand(i));
10503 // If BUILD_VECTOR are from built from integer, they may have different
10504 // operand types. Get the smaller type and truncate all operands to it.
10505 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10506 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10507 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10508 N0.getOperand(i)));
10509 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10510 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10511 N1.getOperand(i)));
10514 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10517 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10518 // nodes often generate nop CONCAT_VECTOR nodes.
10519 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10520 // place the incoming vectors at the exact same location.
10521 SDValue SingleSource = SDValue();
10522 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10524 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10525 SDValue Op = N->getOperand(i);
10527 if (Op.getOpcode() == ISD::UNDEF)
10530 // Check if this is the identity extract:
10531 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10534 // Find the single incoming vector for the extract_subvector.
10535 if (SingleSource.getNode()) {
10536 if (Op.getOperand(0) != SingleSource)
10539 SingleSource = Op.getOperand(0);
10541 // Check the source type is the same as the type of the result.
10542 // If not, this concat may extend the vector, so we can not
10543 // optimize it away.
10544 if (SingleSource.getValueType() != N->getValueType(0))
10548 unsigned IdentityIndex = i * PartNumElem;
10549 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10550 // The extract index must be constant.
10554 // Check that we are reading from the identity index.
10555 if (CS->getZExtValue() != IdentityIndex)
10559 if (SingleSource.getNode())
10560 return SingleSource;
10565 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10566 EVT NVT = N->getValueType(0);
10567 SDValue V = N->getOperand(0);
10569 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10571 // (extract_subvec (concat V1, V2, ...), i)
10574 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10576 if (V->getOperand(0).getValueType() != NVT)
10578 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10579 unsigned NumElems = NVT.getVectorNumElements();
10580 assert((Idx % NumElems) == 0 &&
10581 "IDX in concat is not a multiple of the result vector length.");
10582 return V->getOperand(Idx / NumElems);
10586 if (V->getOpcode() == ISD::BITCAST)
10587 V = V.getOperand(0);
10589 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10591 // Handle only simple case where vector being inserted and vector
10592 // being extracted are of same type, and are half size of larger vectors.
10593 EVT BigVT = V->getOperand(0).getValueType();
10594 EVT SmallVT = V->getOperand(1).getValueType();
10595 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10598 // Only handle cases where both indexes are constants with the same type.
10599 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10600 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10602 if (InsIdx && ExtIdx &&
10603 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10604 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10606 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10608 // indices are equal or bit offsets are equal => V1
10609 // otherwise => (extract_subvec V1, ExtIdx)
10610 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10611 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10612 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10613 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10614 DAG.getNode(ISD::BITCAST, dl,
10615 N->getOperand(0).getValueType(),
10616 V->getOperand(0)), N->getOperand(1));
10623 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10624 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10625 EVT VT = N->getValueType(0);
10626 unsigned NumElts = VT.getVectorNumElements();
10628 SDValue N0 = N->getOperand(0);
10629 SDValue N1 = N->getOperand(1);
10630 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10632 SmallVector<SDValue, 4> Ops;
10633 EVT ConcatVT = N0.getOperand(0).getValueType();
10634 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10635 unsigned NumConcats = NumElts / NumElemsPerConcat;
10637 // Look at every vector that's inserted. We're looking for exact
10638 // subvector-sized copies from a concatenated vector
10639 for (unsigned I = 0; I != NumConcats; ++I) {
10640 // Make sure we're dealing with a copy.
10641 unsigned Begin = I * NumElemsPerConcat;
10642 bool AllUndef = true, NoUndef = true;
10643 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10644 if (SVN->getMaskElt(J) >= 0)
10651 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10654 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10655 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10658 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10659 if (FirstElt < N0.getNumOperands())
10660 Ops.push_back(N0.getOperand(FirstElt));
10662 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10664 } else if (AllUndef) {
10665 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10666 } else { // Mixed with general masks and undefs, can't do optimization.
10671 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10674 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10675 EVT VT = N->getValueType(0);
10676 unsigned NumElts = VT.getVectorNumElements();
10678 SDValue N0 = N->getOperand(0);
10679 SDValue N1 = N->getOperand(1);
10681 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10683 // Canonicalize shuffle undef, undef -> undef
10684 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10685 return DAG.getUNDEF(VT);
10687 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10689 // Canonicalize shuffle v, v -> v, undef
10691 SmallVector<int, 8> NewMask;
10692 for (unsigned i = 0; i != NumElts; ++i) {
10693 int Idx = SVN->getMaskElt(i);
10694 if (Idx >= (int)NumElts) Idx -= NumElts;
10695 NewMask.push_back(Idx);
10697 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10701 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10702 if (N0.getOpcode() == ISD::UNDEF) {
10703 SmallVector<int, 8> NewMask;
10704 for (unsigned i = 0; i != NumElts; ++i) {
10705 int Idx = SVN->getMaskElt(i);
10707 if (Idx >= (int)NumElts)
10710 Idx = -1; // remove reference to lhs
10712 NewMask.push_back(Idx);
10714 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10718 // Remove references to rhs if it is undef
10719 if (N1.getOpcode() == ISD::UNDEF) {
10720 bool Changed = false;
10721 SmallVector<int, 8> NewMask;
10722 for (unsigned i = 0; i != NumElts; ++i) {
10723 int Idx = SVN->getMaskElt(i);
10724 if (Idx >= (int)NumElts) {
10728 NewMask.push_back(Idx);
10731 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10734 // If it is a splat, check if the argument vector is another splat or a
10735 // build_vector with all scalar elements the same.
10736 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10737 SDNode *V = N0.getNode();
10739 // If this is a bit convert that changes the element type of the vector but
10740 // not the number of vector elements, look through it. Be careful not to
10741 // look though conversions that change things like v4f32 to v2f64.
10742 if (V->getOpcode() == ISD::BITCAST) {
10743 SDValue ConvInput = V->getOperand(0);
10744 if (ConvInput.getValueType().isVector() &&
10745 ConvInput.getValueType().getVectorNumElements() == NumElts)
10746 V = ConvInput.getNode();
10749 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10750 assert(V->getNumOperands() == NumElts &&
10751 "BUILD_VECTOR has wrong number of operands");
10753 bool AllSame = true;
10754 for (unsigned i = 0; i != NumElts; ++i) {
10755 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10756 Base = V->getOperand(i);
10760 // Splat of <u, u, u, u>, return <u, u, u, u>
10761 if (!Base.getNode())
10763 for (unsigned i = 0; i != NumElts; ++i) {
10764 if (V->getOperand(i) != Base) {
10769 // Splat of <x, x, x, x>, return <x, x, x, x>
10775 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10776 Level < AfterLegalizeVectorOps &&
10777 (N1.getOpcode() == ISD::UNDEF ||
10778 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10779 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10780 SDValue V = partitionShuffleOfConcats(N, DAG);
10786 // If this shuffle node is simply a swizzle of another shuffle node,
10787 // then try to simplify it.
10788 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10789 N1.getOpcode() == ISD::UNDEF) {
10791 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10793 // The incoming shuffle must be of the same type as the result of the
10794 // current shuffle.
10795 assert(OtherSV->getOperand(0).getValueType() == VT &&
10796 "Shuffle types don't match");
10798 SmallVector<int, 4> Mask;
10799 // Compute the combined shuffle mask.
10800 for (unsigned i = 0; i != NumElts; ++i) {
10801 int Idx = SVN->getMaskElt(i);
10802 assert(Idx < (int)NumElts && "Index references undef operand");
10803 // Next, this index comes from the first value, which is the incoming
10804 // shuffle. Adopt the incoming index.
10806 Idx = OtherSV->getMaskElt(Idx);
10807 Mask.push_back(Idx);
10810 // Check if all indices in Mask are Undef. In case, propagate Undef.
10811 bool isUndefMask = true;
10812 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10813 isUndefMask &= Mask[i] < 0;
10816 return DAG.getUNDEF(VT);
10818 bool CommuteOperands = false;
10819 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10820 // To be valid, the combine shuffle mask should only reference elements
10821 // from one of the two vectors in input to the inner shufflevector.
10822 bool IsValidMask = true;
10823 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10824 // See if the combined mask only reference undefs or elements coming
10825 // from the first shufflevector operand.
10826 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10828 if (!IsValidMask) {
10829 IsValidMask = true;
10830 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10831 // Check that all the elements come from the second shuffle operand.
10832 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10833 CommuteOperands = IsValidMask;
10836 // Early exit if the combined shuffle mask is not valid.
10841 // See if this pair of shuffles can be safely folded according to either
10842 // of the following rules:
10843 // shuffle(shuffle(x, y), undef) -> x
10844 // shuffle(shuffle(x, undef), undef) -> x
10845 // shuffle(shuffle(x, y), undef) -> y
10846 bool IsIdentityMask = true;
10847 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10848 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10853 // The combined shuffle must map each index to itself.
10854 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10857 if (IsIdentityMask) {
10858 if (CommuteOperands)
10859 // optimize shuffle(shuffle(x, y), undef) -> y.
10860 return OtherSV->getOperand(1);
10862 // optimize shuffle(shuffle(x, undef), undef) -> x
10863 // optimize shuffle(shuffle(x, y), undef) -> x
10864 return OtherSV->getOperand(0);
10867 // It may still be beneficial to combine the two shuffles if the
10868 // resulting shuffle is legal.
10869 if (TLI.isTypeLegal(VT)) {
10870 if (!CommuteOperands) {
10871 if (TLI.isShuffleMaskLegal(Mask, VT))
10872 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10873 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10874 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10877 // Compute the commuted shuffle mask.
10878 for (unsigned i = 0; i != NumElts; ++i) {
10882 else if (idx < (int)NumElts)
10883 Mask[i] = idx + NumElts;
10885 Mask[i] = idx - NumElts;
10888 if (TLI.isShuffleMaskLegal(Mask, VT))
10889 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10890 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10896 // Canonicalize shuffles according to rules:
10897 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10898 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10899 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10900 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10901 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10902 TLI.isTypeLegal(VT)) {
10903 // The incoming shuffle must be of the same type as the result of the
10904 // current shuffle.
10905 assert(N1->getOperand(0).getValueType() == VT &&
10906 "Shuffle types don't match");
10908 SDValue SV0 = N1->getOperand(0);
10909 SDValue SV1 = N1->getOperand(1);
10910 bool HasSameOp0 = N0 == SV0;
10911 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10912 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10913 // Commute the operands of this shuffle so that next rule
10915 return DAG.getCommutedVectorShuffle(*SVN);
10918 // Try to fold according to rules:
10919 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10920 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10921 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10922 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10923 // Don't try to fold shuffles with illegal type.
10924 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10925 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10926 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10928 // The incoming shuffle must be of the same type as the result of the
10929 // current shuffle.
10930 assert(OtherSV->getOperand(0).getValueType() == VT &&
10931 "Shuffle types don't match");
10933 SDValue SV0 = OtherSV->getOperand(0);
10934 SDValue SV1 = OtherSV->getOperand(1);
10935 bool HasSameOp0 = N1 == SV0;
10936 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10937 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10941 SmallVector<int, 4> Mask;
10942 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10943 // operand, and SV1 as the second operand.
10944 for (unsigned i = 0; i != NumElts; ++i) {
10945 int Idx = SVN->getMaskElt(i);
10947 // Propagate Undef.
10948 Mask.push_back(Idx);
10952 if (Idx < (int)NumElts) {
10953 Idx = OtherSV->getMaskElt(Idx);
10954 if (IsSV1Undef && Idx >= (int) NumElts)
10955 Idx = -1; // Propagate Undef.
10957 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10959 Mask.push_back(Idx);
10962 // Check if all indices in Mask are Undef. In case, propagate Undef.
10963 bool isUndefMask = true;
10964 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10965 isUndefMask &= Mask[i] < 0;
10968 return DAG.getUNDEF(VT);
10970 // Avoid introducing shuffles with illegal mask.
10971 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10973 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10974 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10975 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10976 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10983 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10984 SDValue N0 = N->getOperand(0);
10985 SDValue N2 = N->getOperand(2);
10987 // If the input vector is a concatenation, and the insert replaces
10988 // one of the halves, we can optimize into a single concat_vectors.
10989 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10990 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10991 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10992 EVT VT = N->getValueType(0);
10994 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10995 // (concat_vectors Z, Y)
10997 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10998 N->getOperand(1), N0.getOperand(1));
11000 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11001 // (concat_vectors X, Z)
11002 if (InsIdx == VT.getVectorNumElements()/2)
11003 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11004 N0.getOperand(0), N->getOperand(1));
11010 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
11011 /// an AND to a vector_shuffle with the destination vector and a zero vector.
11012 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11013 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11014 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11015 EVT VT = N->getValueType(0);
11017 SDValue LHS = N->getOperand(0);
11018 SDValue RHS = N->getOperand(1);
11019 if (N->getOpcode() == ISD::AND) {
11020 if (RHS.getOpcode() == ISD::BITCAST)
11021 RHS = RHS.getOperand(0);
11022 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11023 SmallVector<int, 8> Indices;
11024 unsigned NumElts = RHS.getNumOperands();
11025 for (unsigned i = 0; i != NumElts; ++i) {
11026 SDValue Elt = RHS.getOperand(i);
11027 if (!isa<ConstantSDNode>(Elt))
11030 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11031 Indices.push_back(i);
11032 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11033 Indices.push_back(NumElts);
11038 // Let's see if the target supports this vector_shuffle.
11039 EVT RVT = RHS.getValueType();
11040 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11043 // Return the new VECTOR_SHUFFLE node.
11044 EVT EltVT = RVT.getVectorElementType();
11045 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11046 DAG.getConstant(0, EltVT));
11047 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11048 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11049 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11050 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11057 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
11058 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11059 assert(N->getValueType(0).isVector() &&
11060 "SimplifyVBinOp only works on vectors!");
11062 SDValue LHS = N->getOperand(0);
11063 SDValue RHS = N->getOperand(1);
11064 SDValue Shuffle = XformToShuffleWithZero(N);
11065 if (Shuffle.getNode()) return Shuffle;
11067 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11069 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11070 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11071 // Check if both vectors are constants. If not bail out.
11072 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11073 cast<BuildVectorSDNode>(RHS)->isConstant()))
11076 SmallVector<SDValue, 8> Ops;
11077 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11078 SDValue LHSOp = LHS.getOperand(i);
11079 SDValue RHSOp = RHS.getOperand(i);
11081 // Can't fold divide by zero.
11082 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11083 N->getOpcode() == ISD::FDIV) {
11084 if ((RHSOp.getOpcode() == ISD::Constant &&
11085 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11086 (RHSOp.getOpcode() == ISD::ConstantFP &&
11087 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11091 EVT VT = LHSOp.getValueType();
11092 EVT RVT = RHSOp.getValueType();
11094 // Integer BUILD_VECTOR operands may have types larger than the element
11095 // size (e.g., when the element type is not legal). Prior to type
11096 // legalization, the types may not match between the two BUILD_VECTORS.
11097 // Truncate one of the operands to make them match.
11098 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11099 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11101 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11105 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11107 if (FoldOp.getOpcode() != ISD::UNDEF &&
11108 FoldOp.getOpcode() != ISD::Constant &&
11109 FoldOp.getOpcode() != ISD::ConstantFP)
11111 Ops.push_back(FoldOp);
11112 AddToWorklist(FoldOp.getNode());
11115 if (Ops.size() == LHS.getNumOperands())
11116 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11119 // Type legalization might introduce new shuffles in the DAG.
11120 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11121 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11122 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11123 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11124 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11125 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11126 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11127 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11129 if (SVN0->getMask().equals(SVN1->getMask())) {
11130 EVT VT = N->getValueType(0);
11131 SDValue UndefVector = LHS.getOperand(1);
11132 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11133 LHS.getOperand(0), RHS.getOperand(0));
11134 AddUsersToWorklist(N);
11135 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11136 &SVN0->getMask()[0]);
11143 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11144 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11145 assert(N->getValueType(0).isVector() &&
11146 "SimplifyVUnaryOp only works on vectors!");
11148 SDValue N0 = N->getOperand(0);
11150 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11153 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11154 SmallVector<SDValue, 8> Ops;
11155 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11156 SDValue Op = N0.getOperand(i);
11157 if (Op.getOpcode() != ISD::UNDEF &&
11158 Op.getOpcode() != ISD::ConstantFP)
11160 EVT EltVT = Op.getValueType();
11161 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11162 if (FoldOp.getOpcode() != ISD::UNDEF &&
11163 FoldOp.getOpcode() != ISD::ConstantFP)
11165 Ops.push_back(FoldOp);
11166 AddToWorklist(FoldOp.getNode());
11169 if (Ops.size() != N0.getNumOperands())
11172 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11175 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11176 SDValue N1, SDValue N2){
11177 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11179 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11180 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11182 // If we got a simplified select_cc node back from SimplifySelectCC, then
11183 // break it down into a new SETCC node, and a new SELECT node, and then return
11184 // the SELECT node, since we were called with a SELECT node.
11185 if (SCC.getNode()) {
11186 // Check to see if we got a select_cc back (to turn into setcc/select).
11187 // Otherwise, just return whatever node we got back, like fabs.
11188 if (SCC.getOpcode() == ISD::SELECT_CC) {
11189 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11191 SCC.getOperand(0), SCC.getOperand(1),
11192 SCC.getOperand(4));
11193 AddToWorklist(SETCC.getNode());
11194 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11195 SCC.getOperand(2), SCC.getOperand(3));
11203 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11204 /// are the two values being selected between, see if we can simplify the
11205 /// select. Callers of this should assume that TheSelect is deleted if this
11206 /// returns true. As such, they should return the appropriate thing (e.g. the
11207 /// node) back to the top-level of the DAG combiner loop to avoid it being
11209 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11212 // Cannot simplify select with vector condition
11213 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11215 // If this is a select from two identical things, try to pull the operation
11216 // through the select.
11217 if (LHS.getOpcode() != RHS.getOpcode() ||
11218 !LHS.hasOneUse() || !RHS.hasOneUse())
11221 // If this is a load and the token chain is identical, replace the select
11222 // of two loads with a load through a select of the address to load from.
11223 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11224 // constants have been dropped into the constant pool.
11225 if (LHS.getOpcode() == ISD::LOAD) {
11226 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11227 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11229 // Token chains must be identical.
11230 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11231 // Do not let this transformation reduce the number of volatile loads.
11232 LLD->isVolatile() || RLD->isVolatile() ||
11233 // If this is an EXTLOAD, the VT's must match.
11234 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11235 // If this is an EXTLOAD, the kind of extension must match.
11236 (LLD->getExtensionType() != RLD->getExtensionType() &&
11237 // The only exception is if one of the extensions is anyext.
11238 LLD->getExtensionType() != ISD::EXTLOAD &&
11239 RLD->getExtensionType() != ISD::EXTLOAD) ||
11240 // FIXME: this discards src value information. This is
11241 // over-conservative. It would be beneficial to be able to remember
11242 // both potential memory locations. Since we are discarding
11243 // src value info, don't do the transformation if the memory
11244 // locations are not in the default address space.
11245 LLD->getPointerInfo().getAddrSpace() != 0 ||
11246 RLD->getPointerInfo().getAddrSpace() != 0 ||
11247 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11248 LLD->getBasePtr().getValueType()))
11251 // Check that the select condition doesn't reach either load. If so,
11252 // folding this will induce a cycle into the DAG. If not, this is safe to
11253 // xform, so create a select of the addresses.
11255 if (TheSelect->getOpcode() == ISD::SELECT) {
11256 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11257 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11258 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11260 // The loads must not depend on one another.
11261 if (LLD->isPredecessorOf(RLD) ||
11262 RLD->isPredecessorOf(LLD))
11264 Addr = DAG.getSelect(SDLoc(TheSelect),
11265 LLD->getBasePtr().getValueType(),
11266 TheSelect->getOperand(0), LLD->getBasePtr(),
11267 RLD->getBasePtr());
11268 } else { // Otherwise SELECT_CC
11269 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11270 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11272 if ((LLD->hasAnyUseOfValue(1) &&
11273 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11274 (RLD->hasAnyUseOfValue(1) &&
11275 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11278 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11279 LLD->getBasePtr().getValueType(),
11280 TheSelect->getOperand(0),
11281 TheSelect->getOperand(1),
11282 LLD->getBasePtr(), RLD->getBasePtr(),
11283 TheSelect->getOperand(4));
11287 // It is safe to replace the two loads if they have different alignments,
11288 // but the new load must be the minimum (most restrictive) alignment of the
11290 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11291 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11292 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11293 Load = DAG.getLoad(TheSelect->getValueType(0),
11295 // FIXME: Discards pointer and AA info.
11296 LLD->getChain(), Addr, MachinePointerInfo(),
11297 LLD->isVolatile(), LLD->isNonTemporal(),
11298 isInvariant, Alignment);
11300 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11301 RLD->getExtensionType() : LLD->getExtensionType(),
11303 TheSelect->getValueType(0),
11304 // FIXME: Discards pointer and AA info.
11305 LLD->getChain(), Addr, MachinePointerInfo(),
11306 LLD->getMemoryVT(), LLD->isVolatile(),
11307 LLD->isNonTemporal(), isInvariant, Alignment);
11310 // Users of the select now use the result of the load.
11311 CombineTo(TheSelect, Load);
11313 // Users of the old loads now use the new load's chain. We know the
11314 // old-load value is dead now.
11315 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11316 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11323 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11324 /// where 'cond' is the comparison specified by CC.
11325 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11326 SDValue N2, SDValue N3,
11327 ISD::CondCode CC, bool NotExtCompare) {
11328 // (x ? y : y) -> y.
11329 if (N2 == N3) return N2;
11331 EVT VT = N2.getValueType();
11332 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11333 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11334 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11336 // Determine if the condition we're dealing with is constant
11337 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11338 N0, N1, CC, DL, false);
11339 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11340 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11342 // fold select_cc true, x, y -> x
11343 if (SCCC && !SCCC->isNullValue())
11345 // fold select_cc false, x, y -> y
11346 if (SCCC && SCCC->isNullValue())
11349 // Check to see if we can simplify the select into an fabs node
11350 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11351 // Allow either -0.0 or 0.0
11352 if (CFP->getValueAPF().isZero()) {
11353 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11354 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11355 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11356 N2 == N3.getOperand(0))
11357 return DAG.getNode(ISD::FABS, DL, VT, N0);
11359 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11360 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11361 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11362 N2.getOperand(0) == N3)
11363 return DAG.getNode(ISD::FABS, DL, VT, N3);
11367 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11368 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11369 // in it. This is a win when the constant is not otherwise available because
11370 // it replaces two constant pool loads with one. We only do this if the FP
11371 // type is known to be legal, because if it isn't, then we are before legalize
11372 // types an we want the other legalization to happen first (e.g. to avoid
11373 // messing with soft float) and if the ConstantFP is not legal, because if
11374 // it is legal, we may not need to store the FP constant in a constant pool.
11375 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11376 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11377 if (TLI.isTypeLegal(N2.getValueType()) &&
11378 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11379 TargetLowering::Legal &&
11380 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11381 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11382 // If both constants have multiple uses, then we won't need to do an
11383 // extra load, they are likely around in registers for other users.
11384 (TV->hasOneUse() || FV->hasOneUse())) {
11385 Constant *Elts[] = {
11386 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11387 const_cast<ConstantFP*>(TV->getConstantFPValue())
11389 Type *FPTy = Elts[0]->getType();
11390 const DataLayout &TD = *TLI.getDataLayout();
11392 // Create a ConstantArray of the two constants.
11393 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11394 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11395 TD.getPrefTypeAlignment(FPTy));
11396 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11398 // Get the offsets to the 0 and 1 element of the array so that we can
11399 // select between them.
11400 SDValue Zero = DAG.getIntPtrConstant(0);
11401 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11402 SDValue One = DAG.getIntPtrConstant(EltSize);
11404 SDValue Cond = DAG.getSetCC(DL,
11405 getSetCCResultType(N0.getValueType()),
11407 AddToWorklist(Cond.getNode());
11408 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11410 AddToWorklist(CstOffset.getNode());
11411 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11413 AddToWorklist(CPIdx.getNode());
11414 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11415 MachinePointerInfo::getConstantPool(), false,
11416 false, false, Alignment);
11421 // Check to see if we can perform the "gzip trick", transforming
11422 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11423 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11424 (N1C->isNullValue() || // (a < 0) ? b : 0
11425 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11426 EVT XType = N0.getValueType();
11427 EVT AType = N2.getValueType();
11428 if (XType.bitsGE(AType)) {
11429 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11430 // single-bit constant.
11431 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11432 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11433 ShCtV = XType.getSizeInBits()-ShCtV-1;
11434 SDValue ShCt = DAG.getConstant(ShCtV,
11435 getShiftAmountTy(N0.getValueType()));
11436 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11438 AddToWorklist(Shift.getNode());
11440 if (XType.bitsGT(AType)) {
11441 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11442 AddToWorklist(Shift.getNode());
11445 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11448 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11450 DAG.getConstant(XType.getSizeInBits()-1,
11451 getShiftAmountTy(N0.getValueType())));
11452 AddToWorklist(Shift.getNode());
11454 if (XType.bitsGT(AType)) {
11455 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11456 AddToWorklist(Shift.getNode());
11459 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11463 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11464 // where y is has a single bit set.
11465 // A plaintext description would be, we can turn the SELECT_CC into an AND
11466 // when the condition can be materialized as an all-ones register. Any
11467 // single bit-test can be materialized as an all-ones register with
11468 // shift-left and shift-right-arith.
11469 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11470 N0->getValueType(0) == VT &&
11471 N1C && N1C->isNullValue() &&
11472 N2C && N2C->isNullValue()) {
11473 SDValue AndLHS = N0->getOperand(0);
11474 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11475 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11476 // Shift the tested bit over the sign bit.
11477 APInt AndMask = ConstAndRHS->getAPIntValue();
11479 DAG.getConstant(AndMask.countLeadingZeros(),
11480 getShiftAmountTy(AndLHS.getValueType()));
11481 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11483 // Now arithmetic right shift it all the way over, so the result is either
11484 // all-ones, or zero.
11486 DAG.getConstant(AndMask.getBitWidth()-1,
11487 getShiftAmountTy(Shl.getValueType()));
11488 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11490 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11494 // fold select C, 16, 0 -> shl C, 4
11495 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11496 TLI.getBooleanContents(N0.getValueType()) ==
11497 TargetLowering::ZeroOrOneBooleanContent) {
11499 // If the caller doesn't want us to simplify this into a zext of a compare,
11501 if (NotExtCompare && N2C->getAPIntValue() == 1)
11504 // Get a SetCC of the condition
11505 // NOTE: Don't create a SETCC if it's not legal on this target.
11506 if (!LegalOperations ||
11507 TLI.isOperationLegal(ISD::SETCC,
11508 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11510 // cast from setcc result type to select result type
11512 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11514 if (N2.getValueType().bitsLT(SCC.getValueType()))
11515 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11516 N2.getValueType());
11518 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11519 N2.getValueType(), SCC);
11521 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11522 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11523 N2.getValueType(), SCC);
11526 AddToWorklist(SCC.getNode());
11527 AddToWorklist(Temp.getNode());
11529 if (N2C->getAPIntValue() == 1)
11532 // shl setcc result by log2 n2c
11533 return DAG.getNode(
11534 ISD::SHL, DL, N2.getValueType(), Temp,
11535 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11536 getShiftAmountTy(Temp.getValueType())));
11540 // Check to see if this is the equivalent of setcc
11541 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11542 // otherwise, go ahead with the folds.
11543 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11544 EVT XType = N0.getValueType();
11545 if (!LegalOperations ||
11546 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11547 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11548 if (Res.getValueType() != VT)
11549 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11553 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11554 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11555 (!LegalOperations ||
11556 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11557 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11558 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11559 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11560 getShiftAmountTy(Ctlz.getValueType())));
11562 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11563 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11564 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11565 XType, DAG.getConstant(0, XType), N0);
11566 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11567 return DAG.getNode(ISD::SRL, DL, XType,
11568 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11569 DAG.getConstant(XType.getSizeInBits()-1,
11570 getShiftAmountTy(XType)));
11572 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11573 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11574 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11575 DAG.getConstant(XType.getSizeInBits()-1,
11576 getShiftAmountTy(N0.getValueType())));
11577 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11581 // Check to see if this is an integer abs.
11582 // select_cc setg[te] X, 0, X, -X ->
11583 // select_cc setgt X, -1, X, -X ->
11584 // select_cc setl[te] X, 0, -X, X ->
11585 // select_cc setlt X, 1, -X, X ->
11586 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11588 ConstantSDNode *SubC = nullptr;
11589 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11590 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11591 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11592 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11593 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11594 (N1C->isOne() && CC == ISD::SETLT)) &&
11595 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11596 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11598 EVT XType = N0.getValueType();
11599 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11600 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11602 DAG.getConstant(XType.getSizeInBits()-1,
11603 getShiftAmountTy(N0.getValueType())));
11604 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11606 AddToWorklist(Shift.getNode());
11607 AddToWorklist(Add.getNode());
11608 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11615 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11616 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11617 SDValue N1, ISD::CondCode Cond,
11618 SDLoc DL, bool foldBooleans) {
11619 TargetLowering::DAGCombinerInfo
11620 DagCombineInfo(DAG, Level, false, this);
11621 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11624 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11625 /// a DAG expression to select that will generate the same value by multiplying
11626 /// by a magic number. See:
11627 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11628 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11629 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11633 // Avoid division by zero.
11634 if (!C->getAPIntValue())
11637 std::vector<SDNode*> Built;
11639 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11641 for (SDNode *N : Built)
11646 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11647 /// power of 2, return a DAG expression to select that will generate the same
11648 /// value by right shifting.
11649 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11650 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11654 // Avoid division by zero.
11655 if (!C->getAPIntValue())
11658 std::vector<SDNode *> Built;
11659 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11661 for (SDNode *N : Built)
11666 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11667 /// return a DAG expression to select that will generate the same value by
11668 /// multiplying by a magic number. See:
11669 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11670 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11671 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11675 // Avoid division by zero.
11676 if (!C->getAPIntValue())
11679 std::vector<SDNode*> Built;
11681 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11683 for (SDNode *N : Built)
11688 /// FindBaseOffset - Return true if base is a frame index, which is known not
11689 // to alias with anything but itself. Provides base object and offset as
11691 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11692 const GlobalValue *&GV, const void *&CV) {
11693 // Assume it is a primitive operation.
11694 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11696 // If it's an adding a simple constant then integrate the offset.
11697 if (Base.getOpcode() == ISD::ADD) {
11698 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11699 Base = Base.getOperand(0);
11700 Offset += C->getZExtValue();
11704 // Return the underlying GlobalValue, and update the Offset. Return false
11705 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11706 // by multiple nodes with different offsets.
11707 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11708 GV = G->getGlobal();
11709 Offset += G->getOffset();
11713 // Return the underlying Constant value, and update the Offset. Return false
11714 // for ConstantSDNodes since the same constant pool entry may be represented
11715 // by multiple nodes with different offsets.
11716 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11717 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11718 : (const void *)C->getConstVal();
11719 Offset += C->getOffset();
11722 // If it's any of the following then it can't alias with anything but itself.
11723 return isa<FrameIndexSDNode>(Base);
11726 /// isAlias - Return true if there is any possibility that the two addresses
11728 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11729 // If they are the same then they must be aliases.
11730 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11732 // If they are both volatile then they cannot be reordered.
11733 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11735 // Gather base node and offset information.
11736 SDValue Base1, Base2;
11737 int64_t Offset1, Offset2;
11738 const GlobalValue *GV1, *GV2;
11739 const void *CV1, *CV2;
11740 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11741 Base1, Offset1, GV1, CV1);
11742 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11743 Base2, Offset2, GV2, CV2);
11745 // If they have a same base address then check to see if they overlap.
11746 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11747 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11748 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11750 // It is possible for different frame indices to alias each other, mostly
11751 // when tail call optimization reuses return address slots for arguments.
11752 // To catch this case, look up the actual index of frame indices to compute
11753 // the real alias relationship.
11754 if (isFrameIndex1 && isFrameIndex2) {
11755 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11756 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11757 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11758 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11759 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11762 // Otherwise, if we know what the bases are, and they aren't identical, then
11763 // we know they cannot alias.
11764 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11767 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11768 // compared to the size and offset of the access, we may be able to prove they
11769 // do not alias. This check is conservative for now to catch cases created by
11770 // splitting vector types.
11771 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11772 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11773 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11774 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11775 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11776 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11777 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11779 // There is no overlap between these relatively aligned accesses of similar
11780 // size, return no alias.
11781 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11782 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11786 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11787 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11789 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11790 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11794 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11795 // Use alias analysis information.
11796 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11797 Op1->getSrcValueOffset());
11798 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11799 Op0->getSrcValueOffset() - MinOffset;
11800 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11801 Op1->getSrcValueOffset() - MinOffset;
11802 AliasAnalysis::AliasResult AAResult =
11803 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11805 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11806 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11808 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11809 if (AAResult == AliasAnalysis::NoAlias)
11813 // Otherwise we have to assume they alias.
11817 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11818 /// looking for aliasing nodes and adding them to the Aliases vector.
11819 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11820 SmallVectorImpl<SDValue> &Aliases) {
11821 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11822 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11824 // Get alias information for node.
11825 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11828 Chains.push_back(OriginalChain);
11829 unsigned Depth = 0;
11831 // Look at each chain and determine if it is an alias. If so, add it to the
11832 // aliases list. If not, then continue up the chain looking for the next
11834 while (!Chains.empty()) {
11835 SDValue Chain = Chains.back();
11838 // For TokenFactor nodes, look at each operand and only continue up the
11839 // chain until we find two aliases. If we've seen two aliases, assume we'll
11840 // find more and revert to original chain since the xform is unlikely to be
11843 // FIXME: The depth check could be made to return the last non-aliasing
11844 // chain we found before we hit a tokenfactor rather than the original
11846 if (Depth > 6 || Aliases.size() == 2) {
11848 Aliases.push_back(OriginalChain);
11852 // Don't bother if we've been before.
11853 if (!Visited.insert(Chain.getNode()))
11856 switch (Chain.getOpcode()) {
11857 case ISD::EntryToken:
11858 // Entry token is ideal chain operand, but handled in FindBetterChain.
11863 // Get alias information for Chain.
11864 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11865 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11867 // If chain is alias then stop here.
11868 if (!(IsLoad && IsOpLoad) &&
11869 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11870 Aliases.push_back(Chain);
11872 // Look further up the chain.
11873 Chains.push_back(Chain.getOperand(0));
11879 case ISD::TokenFactor:
11880 // We have to check each of the operands of the token factor for "small"
11881 // token factors, so we queue them up. Adding the operands to the queue
11882 // (stack) in reverse order maintains the original order and increases the
11883 // likelihood that getNode will find a matching token factor (CSE.)
11884 if (Chain.getNumOperands() > 16) {
11885 Aliases.push_back(Chain);
11888 for (unsigned n = Chain.getNumOperands(); n;)
11889 Chains.push_back(Chain.getOperand(--n));
11894 // For all other instructions we will just have to take what we can get.
11895 Aliases.push_back(Chain);
11900 // We need to be careful here to also search for aliases through the
11901 // value operand of a store, etc. Consider the following situation:
11903 // L1 = load Token1, %52
11904 // S1 = store Token1, L1, %51
11905 // L2 = load Token1, %52+8
11906 // S2 = store Token1, L2, %51+8
11907 // Token2 = Token(S1, S2)
11908 // L3 = load Token2, %53
11909 // S3 = store Token2, L3, %52
11910 // L4 = load Token2, %53+8
11911 // S4 = store Token2, L4, %52+8
11912 // If we search for aliases of S3 (which loads address %52), and we look
11913 // only through the chain, then we'll miss the trivial dependence on L1
11914 // (which also loads from %52). We then might change all loads and
11915 // stores to use Token1 as their chain operand, which could result in
11916 // copying %53 into %52 before copying %52 into %51 (which should
11919 // The problem is, however, that searching for such data dependencies
11920 // can become expensive, and the cost is not directly related to the
11921 // chain depth. Instead, we'll rule out such configurations here by
11922 // insisting that we've visited all chain users (except for users
11923 // of the original chain, which is not necessary). When doing this,
11924 // we need to look through nodes we don't care about (otherwise, things
11925 // like register copies will interfere with trivial cases).
11927 SmallVector<const SDNode *, 16> Worklist;
11928 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11929 IE = Visited.end(); I != IE; ++I)
11930 if (*I != OriginalChain.getNode())
11931 Worklist.push_back(*I);
11933 while (!Worklist.empty()) {
11934 const SDNode *M = Worklist.pop_back_val();
11936 // We have already visited M, and want to make sure we've visited any uses
11937 // of M that we care about. For uses that we've not visisted, and don't
11938 // care about, queue them to the worklist.
11940 for (SDNode::use_iterator UI = M->use_begin(),
11941 UIE = M->use_end(); UI != UIE; ++UI)
11942 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11943 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11944 // We've not visited this use, and we care about it (it could have an
11945 // ordering dependency with the original node).
11947 Aliases.push_back(OriginalChain);
11951 // We've not visited this use, but we don't care about it. Mark it as
11952 // visited and enqueue it to the worklist.
11953 Worklist.push_back(*UI);
11958 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11959 /// for a better chain (aliasing node.)
11960 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11961 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11963 // Accumulate all the aliases to this node.
11964 GatherAllAliases(N, OldChain, Aliases);
11966 // If no operands then chain to entry token.
11967 if (Aliases.size() == 0)
11968 return DAG.getEntryNode();
11970 // If a single operand then chain to it. We don't need to revisit it.
11971 if (Aliases.size() == 1)
11974 // Construct a custom tailored token factor.
11975 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11978 // SelectionDAG::Combine - This is the entry point for the file.
11980 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11981 CodeGenOpt::Level OptLevel) {
11982 /// run - This is the main entry point to this class.
11984 DAGCombiner(*this, AA, OptLevel).Run(Level);