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 bool recursivelyDeleteUnusedNodes(SDNode *N);
158 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
161 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
162 return CombineTo(N, &Res, 1, AddTo);
165 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167 SDValue To[] = { Res0, Res1 };
168 return CombineTo(N, To, 2, AddTo);
171 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
175 /// SimplifyDemandedBits - Check the specified integer node value to see if
176 /// it can be simplified or if things it uses can be simplified by bit
177 /// propagation. If so, return true.
178 bool SimplifyDemandedBits(SDValue Op) {
179 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
180 APInt Demanded = APInt::getAllOnesValue(BitWidth);
181 return SimplifyDemandedBits(Op, Demanded);
184 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186 bool CombineToPreIndexedLoadStore(SDNode *N);
187 bool CombineToPostIndexedLoadStore(SDNode *N);
188 bool SliceUpLoad(SDNode *N);
190 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
191 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
192 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
193 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
194 SDValue PromoteIntBinOp(SDValue Op);
195 SDValue PromoteIntShiftOp(SDValue Op);
196 SDValue PromoteExtend(SDValue Op);
197 bool PromoteLoad(SDValue Op);
199 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
200 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
201 ISD::NodeType ExtType);
203 /// combine - call the node-specific routine that knows how to fold each
204 /// particular type of node. If that doesn't do anything, try the
205 /// target-specific DAG combines.
206 SDValue combine(SDNode *N);
208 // Visitation implementation - Implement dag node combining for different
209 // node types. The semantics are as follows:
211 // SDValue.getNode() == 0 - No change was made
212 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
213 // otherwise - N should be replaced by the returned Operand.
215 SDValue visitTokenFactor(SDNode *N);
216 SDValue visitMERGE_VALUES(SDNode *N);
217 SDValue visitADD(SDNode *N);
218 SDValue visitSUB(SDNode *N);
219 SDValue visitADDC(SDNode *N);
220 SDValue visitSUBC(SDNode *N);
221 SDValue visitADDE(SDNode *N);
222 SDValue visitSUBE(SDNode *N);
223 SDValue visitMUL(SDNode *N);
224 SDValue visitSDIV(SDNode *N);
225 SDValue visitUDIV(SDNode *N);
226 SDValue visitSREM(SDNode *N);
227 SDValue visitUREM(SDNode *N);
228 SDValue visitMULHU(SDNode *N);
229 SDValue visitMULHS(SDNode *N);
230 SDValue visitSMUL_LOHI(SDNode *N);
231 SDValue visitUMUL_LOHI(SDNode *N);
232 SDValue visitSMULO(SDNode *N);
233 SDValue visitUMULO(SDNode *N);
234 SDValue visitSDIVREM(SDNode *N);
235 SDValue visitUDIVREM(SDNode *N);
236 SDValue visitAND(SDNode *N);
237 SDValue visitOR(SDNode *N);
238 SDValue visitXOR(SDNode *N);
239 SDValue SimplifyVBinOp(SDNode *N);
240 SDValue SimplifyVUnaryOp(SDNode *N);
241 SDValue visitSHL(SDNode *N);
242 SDValue visitSRA(SDNode *N);
243 SDValue visitSRL(SDNode *N);
244 SDValue visitRotate(SDNode *N);
245 SDValue visitCTLZ(SDNode *N);
246 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
247 SDValue visitCTTZ(SDNode *N);
248 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
249 SDValue visitCTPOP(SDNode *N);
250 SDValue visitSELECT(SDNode *N);
251 SDValue visitVSELECT(SDNode *N);
252 SDValue visitSELECT_CC(SDNode *N);
253 SDValue visitSETCC(SDNode *N);
254 SDValue visitSIGN_EXTEND(SDNode *N);
255 SDValue visitZERO_EXTEND(SDNode *N);
256 SDValue visitANY_EXTEND(SDNode *N);
257 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
258 SDValue visitTRUNCATE(SDNode *N);
259 SDValue visitBITCAST(SDNode *N);
260 SDValue visitBUILD_PAIR(SDNode *N);
261 SDValue visitFADD(SDNode *N);
262 SDValue visitFSUB(SDNode *N);
263 SDValue visitFMUL(SDNode *N);
264 SDValue visitFMA(SDNode *N);
265 SDValue visitFDIV(SDNode *N);
266 SDValue visitFREM(SDNode *N);
267 SDValue visitFCOPYSIGN(SDNode *N);
268 SDValue visitSINT_TO_FP(SDNode *N);
269 SDValue visitUINT_TO_FP(SDNode *N);
270 SDValue visitFP_TO_SINT(SDNode *N);
271 SDValue visitFP_TO_UINT(SDNode *N);
272 SDValue visitFP_ROUND(SDNode *N);
273 SDValue visitFP_ROUND_INREG(SDNode *N);
274 SDValue visitFP_EXTEND(SDNode *N);
275 SDValue visitFNEG(SDNode *N);
276 SDValue visitFABS(SDNode *N);
277 SDValue visitFCEIL(SDNode *N);
278 SDValue visitFTRUNC(SDNode *N);
279 SDValue visitFFLOOR(SDNode *N);
280 SDValue visitBRCOND(SDNode *N);
281 SDValue visitBR_CC(SDNode *N);
282 SDValue visitLOAD(SDNode *N);
283 SDValue visitSTORE(SDNode *N);
284 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
285 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
286 SDValue visitBUILD_VECTOR(SDNode *N);
287 SDValue visitCONCAT_VECTORS(SDNode *N);
288 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
289 SDValue visitVECTOR_SHUFFLE(SDNode *N);
290 SDValue visitINSERT_SUBVECTOR(SDNode *N);
292 SDValue XformToShuffleWithZero(SDNode *N);
293 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
295 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
297 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
298 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
299 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
300 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
301 SDValue N3, ISD::CondCode CC,
302 bool NotExtCompare = false);
303 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
304 SDLoc DL, bool foldBooleans = true);
306 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
308 bool isOneUseSetCC(SDValue N) const;
310 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
312 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
313 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
314 SDValue BuildSDIV(SDNode *N);
315 SDValue BuildSDIVPow2(SDNode *N);
316 SDValue BuildUDIV(SDNode *N);
317 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
318 bool DemandHighBits = true);
319 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
320 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
321 SDValue InnerPos, SDValue InnerNeg,
322 unsigned PosOpcode, unsigned NegOpcode,
324 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
325 SDValue ReduceLoadWidth(SDNode *N);
326 SDValue ReduceLoadOpStoreWidth(SDNode *N);
327 SDValue TransformFPLoadStorePair(SDNode *N);
328 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
329 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
331 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
333 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
334 /// looking for aliasing nodes and adding them to the Aliases vector.
335 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
336 SmallVectorImpl<SDValue> &Aliases);
338 /// isAlias - Return true if there is any possibility that the two addresses
340 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
342 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
343 /// looking for a better chain (aliasing node.)
344 SDValue FindBetterChain(SDNode *N, SDValue Chain);
346 /// Merge consecutive store operations into a wide store.
347 /// This optimization uses wide integers or vectors when possible.
348 /// \return True if some memory operations were changed.
349 bool MergeConsecutiveStores(StoreSDNode *N);
351 /// \brief Try to transform a truncation where C is a constant:
352 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
354 /// \p N needs to be a truncation and its first operand an AND. Other
355 /// requirements are checked by the function (e.g. that trunc is
356 /// single-use) and if missed an empty SDValue is returned.
357 SDValue distributeTruncateThroughAnd(SDNode *N);
360 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
361 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
362 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
363 AttributeSet FnAttrs =
364 DAG.getMachineFunction().getFunction()->getAttributes();
366 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
367 Attribute::OptimizeForSize) ||
368 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
371 /// Run - runs the dag combiner on all nodes in the work list
372 void Run(CombineLevel AtLevel);
374 SelectionDAG &getDAG() const { return DAG; }
376 /// getShiftAmountTy - Returns a type large enough to hold any valid
377 /// shift amount - before type legalization these can be huge.
378 EVT getShiftAmountTy(EVT LHSTy) {
379 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
380 if (LHSTy.isVector())
382 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
383 : TLI.getPointerTy();
386 /// isTypeLegal - This method returns true if we are running before type
387 /// legalization or if the specified VT is legal.
388 bool isTypeLegal(const EVT &VT) {
389 if (!LegalTypes) return true;
390 return TLI.isTypeLegal(VT);
393 /// getSetCCResultType - Convenience wrapper around
394 /// TargetLowering::getSetCCResultType
395 EVT getSetCCResultType(EVT VT) const {
396 return TLI.getSetCCResultType(*DAG.getContext(), VT);
403 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
404 /// nodes from the worklist.
405 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
408 explicit WorklistRemover(DAGCombiner &dc)
409 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
411 void NodeDeleted(SDNode *N, SDNode *E) override {
412 DC.removeFromWorklist(N);
417 //===----------------------------------------------------------------------===//
418 // TargetLowering::DAGCombinerInfo implementation
419 //===----------------------------------------------------------------------===//
421 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
422 ((DAGCombiner*)DC)->AddToWorklist(N);
425 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
426 ((DAGCombiner*)DC)->removeFromWorklist(N);
429 SDValue TargetLowering::DAGCombinerInfo::
430 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
431 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
434 SDValue TargetLowering::DAGCombinerInfo::
435 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
436 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
442 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
445 void TargetLowering::DAGCombinerInfo::
446 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
447 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
450 //===----------------------------------------------------------------------===//
452 //===----------------------------------------------------------------------===//
454 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
455 /// specified expression for the same cost as the expression itself, or 2 if we
456 /// can compute the negated form more cheaply than the expression itself.
457 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
458 const TargetLowering &TLI,
459 const TargetOptions *Options,
460 unsigned Depth = 0) {
461 // fneg is removable even if it has multiple uses.
462 if (Op.getOpcode() == ISD::FNEG) return 2;
464 // Don't allow anything with multiple uses.
465 if (!Op.hasOneUse()) return 0;
467 // Don't recurse exponentially.
468 if (Depth > 6) return 0;
470 switch (Op.getOpcode()) {
471 default: return false;
472 case ISD::ConstantFP:
473 // Don't invert constant FP values after legalize. The negated constant
474 // isn't necessarily legal.
475 return LegalOperations ? 0 : 1;
477 // FIXME: determine better conditions for this xform.
478 if (!Options->UnsafeFPMath) return 0;
480 // After operation legalization, it might not be legal to create new FSUBs.
481 if (LegalOperations &&
482 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
485 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
486 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
489 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
490 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
493 // We can't turn -(A-B) into B-A when we honor signed zeros.
494 if (!Options->UnsafeFPMath) return 0;
496 // fold (fneg (fsub A, B)) -> (fsub B, A)
501 if (Options->HonorSignDependentRoundingFPMath()) return 0;
503 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
504 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
508 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
514 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
519 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
520 /// returns the newly negated expression.
521 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
522 bool LegalOperations, unsigned Depth = 0) {
523 // fneg is removable even if it has multiple uses.
524 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
526 // Don't allow anything with multiple uses.
527 assert(Op.hasOneUse() && "Unknown reuse!");
529 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
530 switch (Op.getOpcode()) {
531 default: llvm_unreachable("Unknown code");
532 case ISD::ConstantFP: {
533 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
535 return DAG.getConstantFP(V, Op.getValueType());
538 // FIXME: determine better conditions for this xform.
539 assert(DAG.getTarget().Options.UnsafeFPMath);
541 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
542 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
543 DAG.getTargetLoweringInfo(),
544 &DAG.getTarget().Options, Depth+1))
545 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
546 GetNegatedExpression(Op.getOperand(0), DAG,
547 LegalOperations, Depth+1),
549 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
551 GetNegatedExpression(Op.getOperand(1), DAG,
552 LegalOperations, Depth+1),
555 // We can't turn -(A-B) into B-A when we honor signed zeros.
556 assert(DAG.getTarget().Options.UnsafeFPMath);
558 // fold (fneg (fsub 0, B)) -> B
559 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
560 if (N0CFP->getValueAPF().isZero())
561 return Op.getOperand(1);
563 // fold (fneg (fsub A, B)) -> (fsub B, A)
564 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
565 Op.getOperand(1), Op.getOperand(0));
569 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
571 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
572 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
573 DAG.getTargetLoweringInfo(),
574 &DAG.getTarget().Options, Depth+1))
575 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
576 GetNegatedExpression(Op.getOperand(0), DAG,
577 LegalOperations, Depth+1),
580 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
581 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
583 GetNegatedExpression(Op.getOperand(1), DAG,
584 LegalOperations, Depth+1));
588 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
589 GetNegatedExpression(Op.getOperand(0), DAG,
590 LegalOperations, Depth+1));
592 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
593 GetNegatedExpression(Op.getOperand(0), DAG,
594 LegalOperations, Depth+1),
599 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
600 // that selects between the target values used for true and false, making it
601 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
602 // the appropriate nodes based on the type of node we are checking. This
603 // simplifies life a bit for the callers.
604 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
606 if (N.getOpcode() == ISD::SETCC) {
607 LHS = N.getOperand(0);
608 RHS = N.getOperand(1);
609 CC = N.getOperand(2);
613 if (N.getOpcode() != ISD::SELECT_CC ||
614 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
615 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
618 LHS = N.getOperand(0);
619 RHS = N.getOperand(1);
620 CC = N.getOperand(4);
624 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
625 // one use. If this is true, it allows the users to invert the operation for
626 // free when it is profitable to do so.
627 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
629 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
634 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
635 /// elements are all the same constant or undefined.
636 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
637 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
642 unsigned SplatBitSize;
644 EVT EltVT = N->getValueType(0).getVectorElementType();
645 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
647 EltVT.getSizeInBits() >= SplatBitSize);
650 // \brief Returns the SDNode if it is a constant BuildVector or constant.
651 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
652 if (isa<ConstantSDNode>(N))
654 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
655 if(BV && BV->isConstant())
660 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
662 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
663 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
666 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
667 BitVector UndefElements;
668 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
670 // BuildVectors can truncate their operands. Ignore that case here.
671 // FIXME: We blindly ignore splats which include undef which is overly
673 if (CN && UndefElements.none() &&
674 CN->getValueType(0) == N.getValueType().getScalarType())
681 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
682 SDValue N0, SDValue N1) {
683 EVT VT = N0.getValueType();
684 if (N0.getOpcode() == Opc) {
685 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
686 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
687 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
688 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
689 if (!OpNode.getNode())
691 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
693 if (N0.hasOneUse()) {
694 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
696 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
697 if (!OpNode.getNode())
699 AddToWorklist(OpNode.getNode());
700 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
705 if (N1.getOpcode() == Opc) {
706 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
707 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
708 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
709 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
710 if (!OpNode.getNode())
712 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
714 if (N1.hasOneUse()) {
715 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
717 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
718 if (!OpNode.getNode())
720 AddToWorklist(OpNode.getNode());
721 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
729 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
731 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
733 DEBUG(dbgs() << "\nReplacing.1 ";
735 dbgs() << "\nWith: ";
736 To[0].getNode()->dump(&DAG);
737 dbgs() << " and " << NumTo-1 << " other values\n";
738 for (unsigned i = 0, e = NumTo; i != e; ++i)
739 assert((!To[i].getNode() ||
740 N->getValueType(i) == To[i].getValueType()) &&
741 "Cannot combine value to value of different type!"));
742 WorklistRemover DeadNodes(*this);
743 DAG.ReplaceAllUsesWith(N, To);
745 // Push the new nodes and any users onto the worklist
746 for (unsigned i = 0, e = NumTo; i != e; ++i) {
747 if (To[i].getNode()) {
748 AddToWorklist(To[i].getNode());
749 AddUsersToWorklist(To[i].getNode());
754 // Finally, if the node is now dead, remove it from the graph. The node
755 // may not be dead if the replacement process recursively simplified to
756 // something else needing this node.
757 if (N->use_empty()) {
758 // Nodes can be reintroduced into the worklist. Make sure we do not
759 // process a node that has been replaced.
760 removeFromWorklist(N);
762 // Finally, since the node is now dead, remove it from the graph.
765 return SDValue(N, 0);
769 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
770 // Replace all uses. If any nodes become isomorphic to other nodes and
771 // are deleted, make sure to remove them from our worklist.
772 WorklistRemover DeadNodes(*this);
773 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
775 // Push the new node and any (possibly new) users onto the worklist.
776 AddToWorklist(TLO.New.getNode());
777 AddUsersToWorklist(TLO.New.getNode());
779 // Finally, if the node is now dead, remove it from the graph. The node
780 // may not be dead if the replacement process recursively simplified to
781 // something else needing this node.
782 if (TLO.Old.getNode()->use_empty()) {
783 removeFromWorklist(TLO.Old.getNode());
785 // If the operands of this node are only used by the node, they will now
786 // be dead. Make sure to visit them first to delete dead nodes early.
787 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
788 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
789 AddToWorklist(TLO.Old.getNode()->getOperand(i).getNode());
791 DAG.DeleteNode(TLO.Old.getNode());
795 /// SimplifyDemandedBits - Check the specified integer node value to see if
796 /// it can be simplified or if things it uses can be simplified by bit
797 /// propagation. If so, return true.
798 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
799 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
800 APInt KnownZero, KnownOne;
801 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
805 AddToWorklist(Op.getNode());
807 // Replace the old value with the new one.
809 DEBUG(dbgs() << "\nReplacing.2 ";
810 TLO.Old.getNode()->dump(&DAG);
811 dbgs() << "\nWith: ";
812 TLO.New.getNode()->dump(&DAG);
815 CommitTargetLoweringOpt(TLO);
819 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
821 EVT VT = Load->getValueType(0);
822 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
824 DEBUG(dbgs() << "\nReplacing.9 ";
826 dbgs() << "\nWith: ";
827 Trunc.getNode()->dump(&DAG);
829 WorklistRemover DeadNodes(*this);
830 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
831 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
832 removeFromWorklist(Load);
833 DAG.DeleteNode(Load);
834 AddToWorklist(Trunc.getNode());
837 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
840 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
841 EVT MemVT = LD->getMemoryVT();
842 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
843 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
845 : LD->getExtensionType();
847 return DAG.getExtLoad(ExtType, dl, PVT,
848 LD->getChain(), LD->getBasePtr(),
849 MemVT, LD->getMemOperand());
852 unsigned Opc = Op.getOpcode();
855 case ISD::AssertSext:
856 return DAG.getNode(ISD::AssertSext, dl, PVT,
857 SExtPromoteOperand(Op.getOperand(0), PVT),
859 case ISD::AssertZext:
860 return DAG.getNode(ISD::AssertZext, dl, PVT,
861 ZExtPromoteOperand(Op.getOperand(0), PVT),
863 case ISD::Constant: {
865 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
866 return DAG.getNode(ExtOpc, dl, PVT, Op);
870 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
872 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
875 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
876 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
878 EVT OldVT = Op.getValueType();
880 bool Replace = false;
881 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
882 if (!NewOp.getNode())
884 AddToWorklist(NewOp.getNode());
887 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
888 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
889 DAG.getValueType(OldVT));
892 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
893 EVT OldVT = Op.getValueType();
895 bool Replace = false;
896 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
897 if (!NewOp.getNode())
899 AddToWorklist(NewOp.getNode());
902 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
903 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
906 /// PromoteIntBinOp - Promote the specified integer binary operation if the
907 /// target indicates it is beneficial. e.g. On x86, it's usually better to
908 /// promote i16 operations to i32 since i16 instructions are longer.
909 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
910 if (!LegalOperations)
913 EVT VT = Op.getValueType();
914 if (VT.isVector() || !VT.isInteger())
917 // If operation type is 'undesirable', e.g. i16 on x86, consider
919 unsigned Opc = Op.getOpcode();
920 if (TLI.isTypeDesirableForOp(Opc, VT))
924 // Consult target whether it is a good idea to promote this operation and
925 // what's the right type to promote it to.
926 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
927 assert(PVT != VT && "Don't know what type to promote to!");
929 bool Replace0 = false;
930 SDValue N0 = Op.getOperand(0);
931 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
935 bool Replace1 = false;
936 SDValue N1 = Op.getOperand(1);
941 NN1 = PromoteOperand(N1, PVT, Replace1);
946 AddToWorklist(NN0.getNode());
948 AddToWorklist(NN1.getNode());
951 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
953 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
955 DEBUG(dbgs() << "\nPromoting ";
956 Op.getNode()->dump(&DAG));
958 return DAG.getNode(ISD::TRUNCATE, dl, VT,
959 DAG.getNode(Opc, dl, PVT, NN0, NN1));
964 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
965 /// target indicates it is beneficial. e.g. On x86, it's usually better to
966 /// promote i16 operations to i32 since i16 instructions are longer.
967 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
968 if (!LegalOperations)
971 EVT VT = Op.getValueType();
972 if (VT.isVector() || !VT.isInteger())
975 // If operation type is 'undesirable', e.g. i16 on x86, consider
977 unsigned Opc = Op.getOpcode();
978 if (TLI.isTypeDesirableForOp(Opc, VT))
982 // Consult target whether it is a good idea to promote this operation and
983 // what's the right type to promote it to.
984 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
985 assert(PVT != VT && "Don't know what type to promote to!");
987 bool Replace = false;
988 SDValue N0 = Op.getOperand(0);
990 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
991 else if (Opc == ISD::SRL)
992 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
994 N0 = PromoteOperand(N0, PVT, Replace);
998 AddToWorklist(N0.getNode());
1000 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1002 DEBUG(dbgs() << "\nPromoting ";
1003 Op.getNode()->dump(&DAG));
1005 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1006 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1011 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1012 if (!LegalOperations)
1015 EVT VT = Op.getValueType();
1016 if (VT.isVector() || !VT.isInteger())
1019 // If operation type is 'undesirable', e.g. i16 on x86, consider
1021 unsigned Opc = Op.getOpcode();
1022 if (TLI.isTypeDesirableForOp(Opc, VT))
1026 // Consult target whether it is a good idea to promote this operation and
1027 // what's the right type to promote it to.
1028 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1029 assert(PVT != VT && "Don't know what type to promote to!");
1030 // fold (aext (aext x)) -> (aext x)
1031 // fold (aext (zext x)) -> (zext x)
1032 // fold (aext (sext x)) -> (sext x)
1033 DEBUG(dbgs() << "\nPromoting ";
1034 Op.getNode()->dump(&DAG));
1035 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1040 bool DAGCombiner::PromoteLoad(SDValue Op) {
1041 if (!LegalOperations)
1044 EVT VT = Op.getValueType();
1045 if (VT.isVector() || !VT.isInteger())
1048 // If operation type is 'undesirable', e.g. i16 on x86, consider
1050 unsigned Opc = Op.getOpcode();
1051 if (TLI.isTypeDesirableForOp(Opc, VT))
1055 // Consult target whether it is a good idea to promote this operation and
1056 // what's the right type to promote it to.
1057 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058 assert(PVT != VT && "Don't know what type to promote to!");
1061 SDNode *N = Op.getNode();
1062 LoadSDNode *LD = cast<LoadSDNode>(N);
1063 EVT MemVT = LD->getMemoryVT();
1064 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1065 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1067 : LD->getExtensionType();
1068 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1069 LD->getChain(), LD->getBasePtr(),
1070 MemVT, LD->getMemOperand());
1071 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1073 DEBUG(dbgs() << "\nPromoting ";
1076 Result.getNode()->dump(&DAG);
1078 WorklistRemover DeadNodes(*this);
1079 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1080 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1081 removeFromWorklist(N);
1083 AddToWorklist(Result.getNode());
1089 /// \brief Recursively delete a node which has no uses and any operands for
1090 /// which it is the only use.
1092 /// Note that this both deletes the nodes and removes them from the worklist.
1093 /// It also adds any nodes who have had a user deleted to the worklist as they
1094 /// may now have only one use and subject to other combines.
1095 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1096 if (!N->use_empty())
1099 SmallSetVector<SDNode *, 16> Nodes;
1102 N = Nodes.pop_back_val();
1106 if (N->use_empty()) {
1107 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1108 Nodes.insert(N->getOperand(i).getNode());
1110 removeFromWorklist(N);
1115 } while (!Nodes.empty());
1119 //===----------------------------------------------------------------------===//
1120 // Main DAG Combiner implementation
1121 //===----------------------------------------------------------------------===//
1123 void DAGCombiner::Run(CombineLevel AtLevel) {
1124 // set the instance variables, so that the various visit routines may use it.
1126 LegalOperations = Level >= AfterLegalizeVectorOps;
1127 LegalTypes = Level >= AfterLegalizeTypes;
1129 // Add all the dag nodes to the worklist.
1130 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1131 E = DAG.allnodes_end(); I != E; ++I)
1134 // Create a dummy node (which is not added to allnodes), that adds a reference
1135 // to the root node, preventing it from being deleted, and tracking any
1136 // changes of the root.
1137 HandleSDNode Dummy(DAG.getRoot());
1139 // The root of the dag may dangle to deleted nodes until the dag combiner is
1140 // done. Set it to null to avoid confusion.
1141 DAG.setRoot(SDValue());
1143 // while the worklist isn't empty, find a node and
1144 // try and combine it.
1145 while (!WorklistMap.empty()) {
1147 // The Worklist holds the SDNodes in order, but it may contain null entries.
1149 N = Worklist.pop_back_val();
1152 bool GoodWorklistEntry = WorklistMap.erase(N);
1153 (void)GoodWorklistEntry;
1154 assert(GoodWorklistEntry &&
1155 "Found a worklist entry without a corresponding map entry!");
1157 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1158 // N is deleted from the DAG, since they too may now be dead or may have a
1159 // reduced number of uses, allowing other xforms.
1160 if (recursivelyDeleteUnusedNodes(N))
1163 DEBUG(dbgs() << "\nCombining: ";
1166 // Add any operands of the new node which have not yet been combined to the
1167 // worklist as well. Because the worklist uniques things already, this
1168 // won't repeatedly process the same operand.
1169 CombinedNodes.insert(N);
1170 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1171 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1172 AddToWorklist(N->getOperand(i).getNode());
1174 WorklistRemover DeadNodes(*this);
1176 SDValue RV = combine(N);
1183 // If we get back the same node we passed in, rather than a new node or
1184 // zero, we know that the node must have defined multiple values and
1185 // CombineTo was used. Since CombineTo takes care of the worklist
1186 // mechanics for us, we have no work to do in this case.
1187 if (RV.getNode() == N)
1190 assert(N->getOpcode() != ISD::DELETED_NODE &&
1191 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1192 "Node was deleted but visit returned new node!");
1194 DEBUG(dbgs() << " ... into: ";
1195 RV.getNode()->dump(&DAG));
1197 // Transfer debug value.
1198 DAG.TransferDbgValues(SDValue(N, 0), RV);
1199 if (N->getNumValues() == RV.getNode()->getNumValues())
1200 DAG.ReplaceAllUsesWith(N, RV.getNode());
1202 assert(N->getValueType(0) == RV.getValueType() &&
1203 N->getNumValues() == 1 && "Type mismatch");
1205 DAG.ReplaceAllUsesWith(N, &OpV);
1208 // Push the new node and any users onto the worklist
1209 AddToWorklist(RV.getNode());
1210 AddUsersToWorklist(RV.getNode());
1212 // Finally, if the node is now dead, remove it from the graph. The node
1213 // may not be dead if the replacement process recursively simplified to
1214 // something else needing this node. This will also take care of adding any
1215 // operands which have lost a user to the worklist.
1216 recursivelyDeleteUnusedNodes(N);
1219 // If the root changed (e.g. it was a dead load, update the root).
1220 DAG.setRoot(Dummy.getValue());
1221 DAG.RemoveDeadNodes();
1224 SDValue DAGCombiner::visit(SDNode *N) {
1225 switch (N->getOpcode()) {
1227 case ISD::TokenFactor: return visitTokenFactor(N);
1228 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1229 case ISD::ADD: return visitADD(N);
1230 case ISD::SUB: return visitSUB(N);
1231 case ISD::ADDC: return visitADDC(N);
1232 case ISD::SUBC: return visitSUBC(N);
1233 case ISD::ADDE: return visitADDE(N);
1234 case ISD::SUBE: return visitSUBE(N);
1235 case ISD::MUL: return visitMUL(N);
1236 case ISD::SDIV: return visitSDIV(N);
1237 case ISD::UDIV: return visitUDIV(N);
1238 case ISD::SREM: return visitSREM(N);
1239 case ISD::UREM: return visitUREM(N);
1240 case ISD::MULHU: return visitMULHU(N);
1241 case ISD::MULHS: return visitMULHS(N);
1242 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1243 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1244 case ISD::SMULO: return visitSMULO(N);
1245 case ISD::UMULO: return visitUMULO(N);
1246 case ISD::SDIVREM: return visitSDIVREM(N);
1247 case ISD::UDIVREM: return visitUDIVREM(N);
1248 case ISD::AND: return visitAND(N);
1249 case ISD::OR: return visitOR(N);
1250 case ISD::XOR: return visitXOR(N);
1251 case ISD::SHL: return visitSHL(N);
1252 case ISD::SRA: return visitSRA(N);
1253 case ISD::SRL: return visitSRL(N);
1255 case ISD::ROTL: return visitRotate(N);
1256 case ISD::CTLZ: return visitCTLZ(N);
1257 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1258 case ISD::CTTZ: return visitCTTZ(N);
1259 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1260 case ISD::CTPOP: return visitCTPOP(N);
1261 case ISD::SELECT: return visitSELECT(N);
1262 case ISD::VSELECT: return visitVSELECT(N);
1263 case ISD::SELECT_CC: return visitSELECT_CC(N);
1264 case ISD::SETCC: return visitSETCC(N);
1265 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1266 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1267 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1268 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1269 case ISD::TRUNCATE: return visitTRUNCATE(N);
1270 case ISD::BITCAST: return visitBITCAST(N);
1271 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1272 case ISD::FADD: return visitFADD(N);
1273 case ISD::FSUB: return visitFSUB(N);
1274 case ISD::FMUL: return visitFMUL(N);
1275 case ISD::FMA: return visitFMA(N);
1276 case ISD::FDIV: return visitFDIV(N);
1277 case ISD::FREM: return visitFREM(N);
1278 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1279 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1280 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1281 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1282 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1283 case ISD::FP_ROUND: return visitFP_ROUND(N);
1284 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1285 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1286 case ISD::FNEG: return visitFNEG(N);
1287 case ISD::FABS: return visitFABS(N);
1288 case ISD::FFLOOR: return visitFFLOOR(N);
1289 case ISD::FCEIL: return visitFCEIL(N);
1290 case ISD::FTRUNC: return visitFTRUNC(N);
1291 case ISD::BRCOND: return visitBRCOND(N);
1292 case ISD::BR_CC: return visitBR_CC(N);
1293 case ISD::LOAD: return visitLOAD(N);
1294 case ISD::STORE: return visitSTORE(N);
1295 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1296 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1297 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1298 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1299 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1300 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1301 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1306 SDValue DAGCombiner::combine(SDNode *N) {
1307 SDValue RV = visit(N);
1309 // If nothing happened, try a target-specific DAG combine.
1310 if (!RV.getNode()) {
1311 assert(N->getOpcode() != ISD::DELETED_NODE &&
1312 "Node was deleted but visit returned NULL!");
1314 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1315 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1317 // Expose the DAG combiner to the target combiner impls.
1318 TargetLowering::DAGCombinerInfo
1319 DagCombineInfo(DAG, Level, false, this);
1321 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1325 // If nothing happened still, try promoting the operation.
1326 if (!RV.getNode()) {
1327 switch (N->getOpcode()) {
1335 RV = PromoteIntBinOp(SDValue(N, 0));
1340 RV = PromoteIntShiftOp(SDValue(N, 0));
1342 case ISD::SIGN_EXTEND:
1343 case ISD::ZERO_EXTEND:
1344 case ISD::ANY_EXTEND:
1345 RV = PromoteExtend(SDValue(N, 0));
1348 if (PromoteLoad(SDValue(N, 0)))
1354 // If N is a commutative binary node, try commuting it to enable more
1356 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1357 N->getNumValues() == 1) {
1358 SDValue N0 = N->getOperand(0);
1359 SDValue N1 = N->getOperand(1);
1361 // Constant operands are canonicalized to RHS.
1362 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1363 SDValue Ops[] = {N1, N0};
1365 if (const BinaryWithFlagsSDNode *BinNode =
1366 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1367 CSENode = DAG.getNodeIfExists(
1368 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1369 BinNode->hasNoSignedWrap(), BinNode->isExact());
1371 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1374 return SDValue(CSENode, 0);
1381 /// getInputChainForNode - Given a node, return its input chain if it has one,
1382 /// otherwise return a null sd operand.
1383 static SDValue getInputChainForNode(SDNode *N) {
1384 if (unsigned NumOps = N->getNumOperands()) {
1385 if (N->getOperand(0).getValueType() == MVT::Other)
1386 return N->getOperand(0);
1387 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1388 return N->getOperand(NumOps-1);
1389 for (unsigned i = 1; i < NumOps-1; ++i)
1390 if (N->getOperand(i).getValueType() == MVT::Other)
1391 return N->getOperand(i);
1396 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1397 // If N has two operands, where one has an input chain equal to the other,
1398 // the 'other' chain is redundant.
1399 if (N->getNumOperands() == 2) {
1400 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1401 return N->getOperand(0);
1402 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1403 return N->getOperand(1);
1406 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1407 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1408 SmallPtrSet<SDNode*, 16> SeenOps;
1409 bool Changed = false; // If we should replace this token factor.
1411 // Start out with this token factor.
1414 // Iterate through token factors. The TFs grows when new token factors are
1416 for (unsigned i = 0; i < TFs.size(); ++i) {
1417 SDNode *TF = TFs[i];
1419 // Check each of the operands.
1420 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1421 SDValue Op = TF->getOperand(i);
1423 switch (Op.getOpcode()) {
1424 case ISD::EntryToken:
1425 // Entry tokens don't need to be added to the list. They are
1430 case ISD::TokenFactor:
1431 if (Op.hasOneUse() &&
1432 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1433 // Queue up for processing.
1434 TFs.push_back(Op.getNode());
1435 // Clean up in case the token factor is removed.
1436 AddToWorklist(Op.getNode());
1443 // Only add if it isn't already in the list.
1444 if (SeenOps.insert(Op.getNode()))
1455 // If we've change things around then replace token factor.
1458 // The entry token is the only possible outcome.
1459 Result = DAG.getEntryNode();
1461 // New and improved token factor.
1462 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1465 // Don't add users to work list.
1466 return CombineTo(N, Result, false);
1472 /// MERGE_VALUES can always be eliminated.
1473 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1474 WorklistRemover DeadNodes(*this);
1475 // Replacing results may cause a different MERGE_VALUES to suddenly
1476 // be CSE'd with N, and carry its uses with it. Iterate until no
1477 // uses remain, to ensure that the node can be safely deleted.
1478 // First add the users of this node to the work list so that they
1479 // can be tried again once they have new operands.
1480 AddUsersToWorklist(N);
1482 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1483 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1484 } while (!N->use_empty());
1485 removeFromWorklist(N);
1487 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1491 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1492 SelectionDAG &DAG) {
1493 EVT VT = N0.getValueType();
1494 SDValue N00 = N0.getOperand(0);
1495 SDValue N01 = N0.getOperand(1);
1496 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1498 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1499 isa<ConstantSDNode>(N00.getOperand(1))) {
1500 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1501 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1502 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1503 N00.getOperand(0), N01),
1504 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1505 N00.getOperand(1), N01));
1506 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1512 SDValue DAGCombiner::visitADD(SDNode *N) {
1513 SDValue N0 = N->getOperand(0);
1514 SDValue N1 = N->getOperand(1);
1515 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1516 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1517 EVT VT = N0.getValueType();
1520 if (VT.isVector()) {
1521 SDValue FoldedVOp = SimplifyVBinOp(N);
1522 if (FoldedVOp.getNode()) return FoldedVOp;
1524 // fold (add x, 0) -> x, vector edition
1525 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1527 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1531 // fold (add x, undef) -> undef
1532 if (N0.getOpcode() == ISD::UNDEF)
1534 if (N1.getOpcode() == ISD::UNDEF)
1536 // fold (add c1, c2) -> c1+c2
1538 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1539 // canonicalize constant to RHS
1541 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1542 // fold (add x, 0) -> x
1543 if (N1C && N1C->isNullValue())
1545 // fold (add Sym, c) -> Sym+c
1546 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1547 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1548 GA->getOpcode() == ISD::GlobalAddress)
1549 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1551 (uint64_t)N1C->getSExtValue());
1552 // fold ((c1-A)+c2) -> (c1+c2)-A
1553 if (N1C && N0.getOpcode() == ISD::SUB)
1554 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1555 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1556 DAG.getConstant(N1C->getAPIntValue()+
1557 N0C->getAPIntValue(), VT),
1560 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1563 // fold ((0-A) + B) -> B-A
1564 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1565 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1566 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1567 // fold (A + (0-B)) -> A-B
1568 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1569 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1570 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1571 // fold (A+(B-A)) -> B
1572 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1573 return N1.getOperand(0);
1574 // fold ((B-A)+A) -> B
1575 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1576 return N0.getOperand(0);
1577 // fold (A+(B-(A+C))) to (B-C)
1578 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1579 N0 == N1.getOperand(1).getOperand(0))
1580 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1581 N1.getOperand(1).getOperand(1));
1582 // fold (A+(B-(C+A))) to (B-C)
1583 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1584 N0 == N1.getOperand(1).getOperand(1))
1585 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1586 N1.getOperand(1).getOperand(0));
1587 // fold (A+((B-A)+or-C)) to (B+or-C)
1588 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1589 N1.getOperand(0).getOpcode() == ISD::SUB &&
1590 N0 == N1.getOperand(0).getOperand(1))
1591 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1592 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1594 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1595 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1596 SDValue N00 = N0.getOperand(0);
1597 SDValue N01 = N0.getOperand(1);
1598 SDValue N10 = N1.getOperand(0);
1599 SDValue N11 = N1.getOperand(1);
1601 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1602 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1603 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1604 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1607 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1608 return SDValue(N, 0);
1610 // fold (a+b) -> (a|b) iff a and b share no bits.
1611 if (VT.isInteger() && !VT.isVector()) {
1612 APInt LHSZero, LHSOne;
1613 APInt RHSZero, RHSOne;
1614 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1616 if (LHSZero.getBoolValue()) {
1617 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1619 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1620 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1621 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1622 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1623 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1628 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1629 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1630 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1631 if (Result.getNode()) return Result;
1633 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1634 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1635 if (Result.getNode()) return Result;
1638 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1639 if (N1.getOpcode() == ISD::SHL &&
1640 N1.getOperand(0).getOpcode() == ISD::SUB)
1641 if (ConstantSDNode *C =
1642 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1643 if (C->getAPIntValue() == 0)
1644 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1645 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1646 N1.getOperand(0).getOperand(1),
1648 if (N0.getOpcode() == ISD::SHL &&
1649 N0.getOperand(0).getOpcode() == ISD::SUB)
1650 if (ConstantSDNode *C =
1651 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1652 if (C->getAPIntValue() == 0)
1653 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1654 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1655 N0.getOperand(0).getOperand(1),
1658 if (N1.getOpcode() == ISD::AND) {
1659 SDValue AndOp0 = N1.getOperand(0);
1660 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1661 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1662 unsigned DestBits = VT.getScalarType().getSizeInBits();
1664 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1665 // and similar xforms where the inner op is either ~0 or 0.
1666 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1668 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1672 // add (sext i1), X -> sub X, (zext i1)
1673 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1674 N0.getOperand(0).getValueType() == MVT::i1 &&
1675 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1677 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1678 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1684 SDValue DAGCombiner::visitADDC(SDNode *N) {
1685 SDValue N0 = N->getOperand(0);
1686 SDValue N1 = N->getOperand(1);
1687 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1688 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1689 EVT VT = N0.getValueType();
1691 // If the flag result is dead, turn this into an ADD.
1692 if (!N->hasAnyUseOfValue(1))
1693 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1694 DAG.getNode(ISD::CARRY_FALSE,
1695 SDLoc(N), MVT::Glue));
1697 // canonicalize constant to RHS.
1699 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1701 // fold (addc x, 0) -> x + no carry out
1702 if (N1C && N1C->isNullValue())
1703 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1704 SDLoc(N), MVT::Glue));
1706 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1707 APInt LHSZero, LHSOne;
1708 APInt RHSZero, RHSOne;
1709 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1711 if (LHSZero.getBoolValue()) {
1712 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1714 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1715 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1716 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1717 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1718 DAG.getNode(ISD::CARRY_FALSE,
1719 SDLoc(N), MVT::Glue));
1725 SDValue DAGCombiner::visitADDE(SDNode *N) {
1726 SDValue N0 = N->getOperand(0);
1727 SDValue N1 = N->getOperand(1);
1728 SDValue CarryIn = N->getOperand(2);
1729 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1730 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1732 // canonicalize constant to RHS
1734 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1737 // fold (adde x, y, false) -> (addc x, y)
1738 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1739 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1744 // Since it may not be valid to emit a fold to zero for vector initializers
1745 // check if we can before folding.
1746 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1748 bool LegalOperations, bool LegalTypes) {
1750 return DAG.getConstant(0, VT);
1751 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1752 return DAG.getConstant(0, VT);
1756 SDValue DAGCombiner::visitSUB(SDNode *N) {
1757 SDValue N0 = N->getOperand(0);
1758 SDValue N1 = N->getOperand(1);
1759 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1760 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1761 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1762 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1763 EVT VT = N0.getValueType();
1766 if (VT.isVector()) {
1767 SDValue FoldedVOp = SimplifyVBinOp(N);
1768 if (FoldedVOp.getNode()) return FoldedVOp;
1770 // fold (sub x, 0) -> x, vector edition
1771 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1775 // fold (sub x, x) -> 0
1776 // FIXME: Refactor this and xor and other similar operations together.
1778 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1779 // fold (sub c1, c2) -> c1-c2
1781 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1782 // fold (sub x, c) -> (add x, -c)
1784 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1785 DAG.getConstant(-N1C->getAPIntValue(), VT));
1786 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1787 if (N0C && N0C->isAllOnesValue())
1788 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1789 // fold A-(A-B) -> B
1790 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1791 return N1.getOperand(1);
1792 // fold (A+B)-A -> B
1793 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1794 return N0.getOperand(1);
1795 // fold (A+B)-B -> A
1796 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1797 return N0.getOperand(0);
1798 // fold C2-(A+C1) -> (C2-C1)-A
1799 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1800 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1802 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1805 // fold ((A+(B+or-C))-B) -> A+or-C
1806 if (N0.getOpcode() == ISD::ADD &&
1807 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1808 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1809 N0.getOperand(1).getOperand(0) == N1)
1810 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1811 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1812 // fold ((A+(C+B))-B) -> A+C
1813 if (N0.getOpcode() == ISD::ADD &&
1814 N0.getOperand(1).getOpcode() == ISD::ADD &&
1815 N0.getOperand(1).getOperand(1) == N1)
1816 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1817 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1818 // fold ((A-(B-C))-C) -> A-B
1819 if (N0.getOpcode() == ISD::SUB &&
1820 N0.getOperand(1).getOpcode() == ISD::SUB &&
1821 N0.getOperand(1).getOperand(1) == N1)
1822 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1823 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1825 // If either operand of a sub is undef, the result is undef
1826 if (N0.getOpcode() == ISD::UNDEF)
1828 if (N1.getOpcode() == ISD::UNDEF)
1831 // If the relocation model supports it, consider symbol offsets.
1832 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1833 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1834 // fold (sub Sym, c) -> Sym-c
1835 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1836 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1838 (uint64_t)N1C->getSExtValue());
1839 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1840 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1841 if (GA->getGlobal() == GB->getGlobal())
1842 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1849 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1850 SDValue N0 = N->getOperand(0);
1851 SDValue N1 = N->getOperand(1);
1852 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1853 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1854 EVT VT = N0.getValueType();
1856 // If the flag result is dead, turn this into an SUB.
1857 if (!N->hasAnyUseOfValue(1))
1858 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1859 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1862 // fold (subc x, x) -> 0 + no borrow
1864 return CombineTo(N, DAG.getConstant(0, VT),
1865 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1868 // fold (subc x, 0) -> x + no borrow
1869 if (N1C && N1C->isNullValue())
1870 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1873 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1874 if (N0C && N0C->isAllOnesValue())
1875 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1876 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1882 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1883 SDValue N0 = N->getOperand(0);
1884 SDValue N1 = N->getOperand(1);
1885 SDValue CarryIn = N->getOperand(2);
1887 // fold (sube x, y, false) -> (subc x, y)
1888 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1889 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1894 SDValue DAGCombiner::visitMUL(SDNode *N) {
1895 SDValue N0 = N->getOperand(0);
1896 SDValue N1 = N->getOperand(1);
1897 EVT VT = N0.getValueType();
1899 // fold (mul x, undef) -> 0
1900 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1901 return DAG.getConstant(0, VT);
1903 bool N0IsConst = false;
1904 bool N1IsConst = false;
1905 APInt ConstValue0, ConstValue1;
1907 if (VT.isVector()) {
1908 SDValue FoldedVOp = SimplifyVBinOp(N);
1909 if (FoldedVOp.getNode()) return FoldedVOp;
1911 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1912 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1914 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1915 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1917 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1918 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1922 // fold (mul c1, c2) -> c1*c2
1923 if (N0IsConst && N1IsConst)
1924 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1926 // canonicalize constant to RHS
1927 if (N0IsConst && !N1IsConst)
1928 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1929 // fold (mul x, 0) -> 0
1930 if (N1IsConst && ConstValue1 == 0)
1932 // We require a splat of the entire scalar bit width for non-contiguous
1935 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1936 // fold (mul x, 1) -> x
1937 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1939 // fold (mul x, -1) -> 0-x
1940 if (N1IsConst && ConstValue1.isAllOnesValue())
1941 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1942 DAG.getConstant(0, VT), N0);
1943 // fold (mul x, (1 << c)) -> x << c
1944 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1945 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1946 DAG.getConstant(ConstValue1.logBase2(),
1947 getShiftAmountTy(N0.getValueType())));
1948 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1949 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1950 unsigned Log2Val = (-ConstValue1).logBase2();
1951 // FIXME: If the input is something that is easily negated (e.g. a
1952 // single-use add), we should put the negate there.
1953 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1954 DAG.getConstant(0, VT),
1955 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1956 DAG.getConstant(Log2Val,
1957 getShiftAmountTy(N0.getValueType()))));
1961 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1962 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1963 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1964 isa<ConstantSDNode>(N0.getOperand(1)))) {
1965 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1966 N1, N0.getOperand(1));
1967 AddToWorklist(C3.getNode());
1968 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1969 N0.getOperand(0), C3);
1972 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1975 SDValue Sh(nullptr,0), Y(nullptr,0);
1976 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1977 if (N0.getOpcode() == ISD::SHL &&
1978 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1979 isa<ConstantSDNode>(N0.getOperand(1))) &&
1980 N0.getNode()->hasOneUse()) {
1982 } else if (N1.getOpcode() == ISD::SHL &&
1983 isa<ConstantSDNode>(N1.getOperand(1)) &&
1984 N1.getNode()->hasOneUse()) {
1989 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1990 Sh.getOperand(0), Y);
1991 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1992 Mul, Sh.getOperand(1));
1996 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1997 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1998 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1999 isa<ConstantSDNode>(N0.getOperand(1))))
2000 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2001 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2002 N0.getOperand(0), N1),
2003 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2004 N0.getOperand(1), N1));
2007 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2014 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2015 SDValue N0 = N->getOperand(0);
2016 SDValue N1 = N->getOperand(1);
2017 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2018 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2019 EVT VT = N->getValueType(0);
2022 if (VT.isVector()) {
2023 SDValue FoldedVOp = SimplifyVBinOp(N);
2024 if (FoldedVOp.getNode()) return FoldedVOp;
2027 // fold (sdiv c1, c2) -> c1/c2
2028 if (N0C && N1C && !N1C->isNullValue())
2029 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2030 // fold (sdiv X, 1) -> X
2031 if (N1C && N1C->getAPIntValue() == 1LL)
2033 // fold (sdiv X, -1) -> 0-X
2034 if (N1C && N1C->isAllOnesValue())
2035 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2036 DAG.getConstant(0, VT), N0);
2037 // If we know the sign bits of both operands are zero, strength reduce to a
2038 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2039 if (!VT.isVector()) {
2040 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2041 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2045 // fold (sdiv X, pow2) -> simple ops after legalize
2046 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2047 (-N1C->getAPIntValue()).isPowerOf2())) {
2048 // If dividing by powers of two is cheap, then don't perform the following
2050 if (TLI.isPow2DivCheap())
2053 // Target-specific implementation of sdiv x, pow2.
2054 SDValue Res = BuildSDIVPow2(N);
2058 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2060 // Splat the sign bit into the register
2062 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2063 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2064 getShiftAmountTy(N0.getValueType())));
2065 AddToWorklist(SGN.getNode());
2067 // Add (N0 < 0) ? abs2 - 1 : 0;
2069 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2070 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2071 getShiftAmountTy(SGN.getValueType())));
2072 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2073 AddToWorklist(SRL.getNode());
2074 AddToWorklist(ADD.getNode()); // Divide by pow2
2075 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2076 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2078 // If we're dividing by a positive value, we're done. Otherwise, we must
2079 // negate the result.
2080 if (N1C->getAPIntValue().isNonNegative())
2083 AddToWorklist(SRA.getNode());
2084 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2087 // if integer divide is expensive and we satisfy the requirements, emit an
2088 // alternate sequence.
2089 if (N1C && !TLI.isIntDivCheap()) {
2090 SDValue Op = BuildSDIV(N);
2091 if (Op.getNode()) return Op;
2095 if (N0.getOpcode() == ISD::UNDEF)
2096 return DAG.getConstant(0, VT);
2097 // X / undef -> undef
2098 if (N1.getOpcode() == ISD::UNDEF)
2104 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2105 SDValue N0 = N->getOperand(0);
2106 SDValue N1 = N->getOperand(1);
2107 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2108 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2109 EVT VT = N->getValueType(0);
2112 if (VT.isVector()) {
2113 SDValue FoldedVOp = SimplifyVBinOp(N);
2114 if (FoldedVOp.getNode()) return FoldedVOp;
2117 // fold (udiv c1, c2) -> c1/c2
2118 if (N0C && N1C && !N1C->isNullValue())
2119 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2120 // fold (udiv x, (1 << c)) -> x >>u c
2121 if (N1C && N1C->getAPIntValue().isPowerOf2())
2122 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2123 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2124 getShiftAmountTy(N0.getValueType())));
2125 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2126 if (N1.getOpcode() == ISD::SHL) {
2127 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2128 if (SHC->getAPIntValue().isPowerOf2()) {
2129 EVT ADDVT = N1.getOperand(1).getValueType();
2130 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2132 DAG.getConstant(SHC->getAPIntValue()
2135 AddToWorklist(Add.getNode());
2136 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2140 // fold (udiv x, c) -> alternate
2141 if (N1C && !TLI.isIntDivCheap()) {
2142 SDValue Op = BuildUDIV(N);
2143 if (Op.getNode()) return Op;
2147 if (N0.getOpcode() == ISD::UNDEF)
2148 return DAG.getConstant(0, VT);
2149 // X / undef -> undef
2150 if (N1.getOpcode() == ISD::UNDEF)
2156 SDValue DAGCombiner::visitSREM(SDNode *N) {
2157 SDValue N0 = N->getOperand(0);
2158 SDValue N1 = N->getOperand(1);
2159 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2160 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2161 EVT VT = N->getValueType(0);
2163 // fold (srem c1, c2) -> c1%c2
2164 if (N0C && N1C && !N1C->isNullValue())
2165 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2166 // If we know the sign bits of both operands are zero, strength reduce to a
2167 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2168 if (!VT.isVector()) {
2169 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2170 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2173 // If X/C can be simplified by the division-by-constant logic, lower
2174 // X%C to the equivalent of X-X/C*C.
2175 if (N1C && !N1C->isNullValue()) {
2176 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2177 AddToWorklist(Div.getNode());
2178 SDValue OptimizedDiv = combine(Div.getNode());
2179 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2180 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2182 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2183 AddToWorklist(Mul.getNode());
2189 if (N0.getOpcode() == ISD::UNDEF)
2190 return DAG.getConstant(0, VT);
2191 // X % undef -> undef
2192 if (N1.getOpcode() == ISD::UNDEF)
2198 SDValue DAGCombiner::visitUREM(SDNode *N) {
2199 SDValue N0 = N->getOperand(0);
2200 SDValue N1 = N->getOperand(1);
2201 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2202 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2203 EVT VT = N->getValueType(0);
2205 // fold (urem c1, c2) -> c1%c2
2206 if (N0C && N1C && !N1C->isNullValue())
2207 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2208 // fold (urem x, pow2) -> (and x, pow2-1)
2209 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2210 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2211 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2212 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2213 if (N1.getOpcode() == ISD::SHL) {
2214 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2215 if (SHC->getAPIntValue().isPowerOf2()) {
2217 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2218 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2220 AddToWorklist(Add.getNode());
2221 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2226 // If X/C can be simplified by the division-by-constant logic, lower
2227 // X%C to the equivalent of X-X/C*C.
2228 if (N1C && !N1C->isNullValue()) {
2229 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2230 AddToWorklist(Div.getNode());
2231 SDValue OptimizedDiv = combine(Div.getNode());
2232 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2233 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2235 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2236 AddToWorklist(Mul.getNode());
2242 if (N0.getOpcode() == ISD::UNDEF)
2243 return DAG.getConstant(0, VT);
2244 // X % undef -> undef
2245 if (N1.getOpcode() == ISD::UNDEF)
2251 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2252 SDValue N0 = N->getOperand(0);
2253 SDValue N1 = N->getOperand(1);
2254 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2255 EVT VT = N->getValueType(0);
2258 // fold (mulhs x, 0) -> 0
2259 if (N1C && N1C->isNullValue())
2261 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2262 if (N1C && N1C->getAPIntValue() == 1)
2263 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2264 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2265 getShiftAmountTy(N0.getValueType())));
2266 // fold (mulhs x, undef) -> 0
2267 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2268 return DAG.getConstant(0, VT);
2270 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2272 if (VT.isSimple() && !VT.isVector()) {
2273 MVT Simple = VT.getSimpleVT();
2274 unsigned SimpleSize = Simple.getSizeInBits();
2275 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2276 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2277 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2278 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2279 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2280 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2281 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2282 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2289 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2290 SDValue N0 = N->getOperand(0);
2291 SDValue N1 = N->getOperand(1);
2292 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2293 EVT VT = N->getValueType(0);
2296 // fold (mulhu x, 0) -> 0
2297 if (N1C && N1C->isNullValue())
2299 // fold (mulhu x, 1) -> 0
2300 if (N1C && N1C->getAPIntValue() == 1)
2301 return DAG.getConstant(0, N0.getValueType());
2302 // fold (mulhu x, undef) -> 0
2303 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2304 return DAG.getConstant(0, VT);
2306 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2308 if (VT.isSimple() && !VT.isVector()) {
2309 MVT Simple = VT.getSimpleVT();
2310 unsigned SimpleSize = Simple.getSizeInBits();
2311 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2312 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2313 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2314 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2315 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2316 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2317 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2318 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2325 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2326 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2327 /// that are being performed. Return true if a simplification was made.
2329 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2331 // If the high half is not needed, just compute the low half.
2332 bool HiExists = N->hasAnyUseOfValue(1);
2334 (!LegalOperations ||
2335 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2336 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2337 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2338 return CombineTo(N, Res, Res);
2341 // If the low half is not needed, just compute the high half.
2342 bool LoExists = N->hasAnyUseOfValue(0);
2344 (!LegalOperations ||
2345 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2346 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2347 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2348 return CombineTo(N, Res, Res);
2351 // If both halves are used, return as it is.
2352 if (LoExists && HiExists)
2355 // If the two computed results can be simplified separately, separate them.
2357 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2358 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2359 AddToWorklist(Lo.getNode());
2360 SDValue LoOpt = combine(Lo.getNode());
2361 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2362 (!LegalOperations ||
2363 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2364 return CombineTo(N, LoOpt, LoOpt);
2368 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2369 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2370 AddToWorklist(Hi.getNode());
2371 SDValue HiOpt = combine(Hi.getNode());
2372 if (HiOpt.getNode() && HiOpt != Hi &&
2373 (!LegalOperations ||
2374 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2375 return CombineTo(N, HiOpt, HiOpt);
2381 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2382 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2383 if (Res.getNode()) return Res;
2385 EVT VT = N->getValueType(0);
2388 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2390 if (VT.isSimple() && !VT.isVector()) {
2391 MVT Simple = VT.getSimpleVT();
2392 unsigned SimpleSize = Simple.getSizeInBits();
2393 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2394 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2395 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2396 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2397 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2398 // Compute the high part as N1.
2399 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2400 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2401 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2402 // Compute the low part as N0.
2403 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2404 return CombineTo(N, Lo, Hi);
2411 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2412 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2413 if (Res.getNode()) return Res;
2415 EVT VT = N->getValueType(0);
2418 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2420 if (VT.isSimple() && !VT.isVector()) {
2421 MVT Simple = VT.getSimpleVT();
2422 unsigned SimpleSize = Simple.getSizeInBits();
2423 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2424 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2425 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2426 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2427 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2428 // Compute the high part as N1.
2429 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2430 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2431 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2432 // Compute the low part as N0.
2433 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2434 return CombineTo(N, Lo, Hi);
2441 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2442 // (smulo x, 2) -> (saddo x, x)
2443 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2444 if (C2->getAPIntValue() == 2)
2445 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2446 N->getOperand(0), N->getOperand(0));
2451 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2452 // (umulo x, 2) -> (uaddo x, x)
2453 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2454 if (C2->getAPIntValue() == 2)
2455 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2456 N->getOperand(0), N->getOperand(0));
2461 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2462 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2463 if (Res.getNode()) return Res;
2468 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2469 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2470 if (Res.getNode()) return Res;
2475 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2476 /// two operands of the same opcode, try to simplify it.
2477 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2478 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2479 EVT VT = N0.getValueType();
2480 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2482 // Bail early if none of these transforms apply.
2483 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2485 // For each of OP in AND/OR/XOR:
2486 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2487 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2488 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2489 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2491 // do not sink logical op inside of a vector extend, since it may combine
2493 EVT Op0VT = N0.getOperand(0).getValueType();
2494 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2495 N0.getOpcode() == ISD::SIGN_EXTEND ||
2496 // Avoid infinite looping with PromoteIntBinOp.
2497 (N0.getOpcode() == ISD::ANY_EXTEND &&
2498 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2499 (N0.getOpcode() == ISD::TRUNCATE &&
2500 (!TLI.isZExtFree(VT, Op0VT) ||
2501 !TLI.isTruncateFree(Op0VT, VT)) &&
2502 TLI.isTypeLegal(Op0VT))) &&
2504 Op0VT == N1.getOperand(0).getValueType() &&
2505 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2506 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2507 N0.getOperand(0).getValueType(),
2508 N0.getOperand(0), N1.getOperand(0));
2509 AddToWorklist(ORNode.getNode());
2510 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2513 // For each of OP in SHL/SRL/SRA/AND...
2514 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2515 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2516 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2517 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2518 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2519 N0.getOperand(1) == N1.getOperand(1)) {
2520 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2521 N0.getOperand(0).getValueType(),
2522 N0.getOperand(0), N1.getOperand(0));
2523 AddToWorklist(ORNode.getNode());
2524 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2525 ORNode, N0.getOperand(1));
2528 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2529 // Only perform this optimization after type legalization and before
2530 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2531 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2532 // we don't want to undo this promotion.
2533 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2535 if ((N0.getOpcode() == ISD::BITCAST ||
2536 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2537 Level == AfterLegalizeTypes) {
2538 SDValue In0 = N0.getOperand(0);
2539 SDValue In1 = N1.getOperand(0);
2540 EVT In0Ty = In0.getValueType();
2541 EVT In1Ty = In1.getValueType();
2543 // If both incoming values are integers, and the original types are the
2545 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2546 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2547 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2548 AddToWorklist(Op.getNode());
2553 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2554 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2555 // If both shuffles use the same mask, and both shuffle within a single
2556 // vector, then it is worthwhile to move the swizzle after the operation.
2557 // The type-legalizer generates this pattern when loading illegal
2558 // vector types from memory. In many cases this allows additional shuffle
2560 // There are other cases where moving the shuffle after the xor/and/or
2561 // is profitable even if shuffles don't perform a swizzle.
2562 // If both shuffles use the same mask, and both shuffles have the same first
2563 // or second operand, then it might still be profitable to move the shuffle
2564 // after the xor/and/or operation.
2565 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2566 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2567 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2569 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2570 "Inputs to shuffles are not the same type");
2572 // Check that both shuffles use the same mask. The masks are known to be of
2573 // the same length because the result vector type is the same.
2574 // Check also that shuffles have only one use to avoid introducing extra
2576 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2577 SVN0->getMask().equals(SVN1->getMask())) {
2578 SDValue ShOp = N0->getOperand(1);
2580 // Don't try to fold this node if it requires introducing a
2581 // build vector of all zeros that might be illegal at this stage.
2582 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2584 ShOp = DAG.getConstant(0, VT);
2589 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2590 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2591 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2592 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2593 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2594 N0->getOperand(0), N1->getOperand(0));
2595 AddToWorklist(NewNode.getNode());
2596 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2597 &SVN0->getMask()[0]);
2600 // Don't try to fold this node if it requires introducing a
2601 // build vector of all zeros that might be illegal at this stage.
2602 ShOp = N0->getOperand(0);
2603 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2605 ShOp = DAG.getConstant(0, VT);
2610 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2611 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2612 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2613 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2614 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2615 N0->getOperand(1), N1->getOperand(1));
2616 AddToWorklist(NewNode.getNode());
2617 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2618 &SVN0->getMask()[0]);
2626 SDValue DAGCombiner::visitAND(SDNode *N) {
2627 SDValue N0 = N->getOperand(0);
2628 SDValue N1 = N->getOperand(1);
2629 SDValue LL, LR, RL, RR, CC0, CC1;
2630 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2631 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2632 EVT VT = N1.getValueType();
2633 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2636 if (VT.isVector()) {
2637 SDValue FoldedVOp = SimplifyVBinOp(N);
2638 if (FoldedVOp.getNode()) return FoldedVOp;
2640 // fold (and x, 0) -> 0, vector edition
2641 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2643 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2646 // fold (and x, -1) -> x, vector edition
2647 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2649 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2653 // fold (and x, undef) -> 0
2654 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2655 return DAG.getConstant(0, VT);
2656 // fold (and c1, c2) -> c1&c2
2658 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2659 // canonicalize constant to RHS
2661 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2662 // fold (and x, -1) -> x
2663 if (N1C && N1C->isAllOnesValue())
2665 // if (and x, c) is known to be zero, return 0
2666 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2667 APInt::getAllOnesValue(BitWidth)))
2668 return DAG.getConstant(0, VT);
2670 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2673 // fold (and (or x, C), D) -> D if (C & D) == D
2674 if (N1C && N0.getOpcode() == ISD::OR)
2675 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2676 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2678 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2679 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2680 SDValue N0Op0 = N0.getOperand(0);
2681 APInt Mask = ~N1C->getAPIntValue();
2682 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2683 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2684 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2685 N0.getValueType(), N0Op0);
2687 // Replace uses of the AND with uses of the Zero extend node.
2690 // We actually want to replace all uses of the any_extend with the
2691 // zero_extend, to avoid duplicating things. This will later cause this
2692 // AND to be folded.
2693 CombineTo(N0.getNode(), Zext);
2694 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2697 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2698 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2699 // already be zero by virtue of the width of the base type of the load.
2701 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2703 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2704 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2705 N0.getOpcode() == ISD::LOAD) {
2706 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2707 N0 : N0.getOperand(0) );
2709 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2710 // This can be a pure constant or a vector splat, in which case we treat the
2711 // vector as a scalar and use the splat value.
2712 APInt Constant = APInt::getNullValue(1);
2713 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2714 Constant = C->getAPIntValue();
2715 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2716 APInt SplatValue, SplatUndef;
2717 unsigned SplatBitSize;
2719 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2720 SplatBitSize, HasAnyUndefs);
2722 // Undef bits can contribute to a possible optimisation if set, so
2724 SplatValue |= SplatUndef;
2726 // The splat value may be something like "0x00FFFFFF", which means 0 for
2727 // the first vector value and FF for the rest, repeating. We need a mask
2728 // that will apply equally to all members of the vector, so AND all the
2729 // lanes of the constant together.
2730 EVT VT = Vector->getValueType(0);
2731 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2733 // If the splat value has been compressed to a bitlength lower
2734 // than the size of the vector lane, we need to re-expand it to
2736 if (BitWidth > SplatBitSize)
2737 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2738 SplatBitSize < BitWidth;
2739 SplatBitSize = SplatBitSize * 2)
2740 SplatValue |= SplatValue.shl(SplatBitSize);
2742 Constant = APInt::getAllOnesValue(BitWidth);
2743 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2744 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2748 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2749 // actually legal and isn't going to get expanded, else this is a false
2751 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2752 Load->getMemoryVT());
2754 // Resize the constant to the same size as the original memory access before
2755 // extension. If it is still the AllOnesValue then this AND is completely
2758 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2761 switch (Load->getExtensionType()) {
2762 default: B = false; break;
2763 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2765 case ISD::NON_EXTLOAD: B = true; break;
2768 if (B && Constant.isAllOnesValue()) {
2769 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2770 // preserve semantics once we get rid of the AND.
2771 SDValue NewLoad(Load, 0);
2772 if (Load->getExtensionType() == ISD::EXTLOAD) {
2773 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2774 Load->getValueType(0), SDLoc(Load),
2775 Load->getChain(), Load->getBasePtr(),
2776 Load->getOffset(), Load->getMemoryVT(),
2777 Load->getMemOperand());
2778 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2779 if (Load->getNumValues() == 3) {
2780 // PRE/POST_INC loads have 3 values.
2781 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2782 NewLoad.getValue(2) };
2783 CombineTo(Load, To, 3, true);
2785 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2789 // Fold the AND away, taking care not to fold to the old load node if we
2791 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2793 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2796 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2797 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2798 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2799 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2801 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2802 LL.getValueType().isInteger()) {
2803 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2804 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2805 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2806 LR.getValueType(), LL, RL);
2807 AddToWorklist(ORNode.getNode());
2808 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2810 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2811 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2812 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2813 LR.getValueType(), LL, RL);
2814 AddToWorklist(ANDNode.getNode());
2815 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2817 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2818 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2819 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2820 LR.getValueType(), LL, RL);
2821 AddToWorklist(ORNode.getNode());
2822 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2825 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2826 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2827 Op0 == Op1 && LL.getValueType().isInteger() &&
2828 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2829 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2830 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2831 cast<ConstantSDNode>(RR)->isNullValue()))) {
2832 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2833 LL, DAG.getConstant(1, LL.getValueType()));
2834 AddToWorklist(ADDNode.getNode());
2835 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2836 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2838 // canonicalize equivalent to ll == rl
2839 if (LL == RR && LR == RL) {
2840 Op1 = ISD::getSetCCSwappedOperands(Op1);
2843 if (LL == RL && LR == RR) {
2844 bool isInteger = LL.getValueType().isInteger();
2845 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2846 if (Result != ISD::SETCC_INVALID &&
2847 (!LegalOperations ||
2848 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2849 TLI.isOperationLegal(ISD::SETCC,
2850 getSetCCResultType(N0.getSimpleValueType())))))
2851 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2856 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2857 if (N0.getOpcode() == N1.getOpcode()) {
2858 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2859 if (Tmp.getNode()) return Tmp;
2862 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2863 // fold (and (sra)) -> (and (srl)) when possible.
2864 if (!VT.isVector() &&
2865 SimplifyDemandedBits(SDValue(N, 0)))
2866 return SDValue(N, 0);
2868 // fold (zext_inreg (extload x)) -> (zextload x)
2869 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2870 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2871 EVT MemVT = LN0->getMemoryVT();
2872 // If we zero all the possible extended bits, then we can turn this into
2873 // a zextload if we are running before legalize or the operation is legal.
2874 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2875 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2876 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2877 ((!LegalOperations && !LN0->isVolatile()) ||
2878 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2879 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2880 LN0->getChain(), LN0->getBasePtr(),
2881 MemVT, LN0->getMemOperand());
2883 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2884 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2887 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2888 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2890 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2891 EVT MemVT = LN0->getMemoryVT();
2892 // If we zero all the possible extended bits, then we can turn this into
2893 // a zextload if we are running before legalize or the operation is legal.
2894 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2895 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2896 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2897 ((!LegalOperations && !LN0->isVolatile()) ||
2898 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2899 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2900 LN0->getChain(), LN0->getBasePtr(),
2901 MemVT, LN0->getMemOperand());
2903 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2904 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2908 // fold (and (load x), 255) -> (zextload x, i8)
2909 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2910 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2911 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2912 (N0.getOpcode() == ISD::ANY_EXTEND &&
2913 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2914 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2915 LoadSDNode *LN0 = HasAnyExt
2916 ? cast<LoadSDNode>(N0.getOperand(0))
2917 : cast<LoadSDNode>(N0);
2918 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2919 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2920 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2921 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2922 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2923 EVT LoadedVT = LN0->getMemoryVT();
2925 if (ExtVT == LoadedVT &&
2926 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2927 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2930 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2931 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2932 LN0->getMemOperand());
2934 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2935 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2938 // Do not change the width of a volatile load.
2939 // Do not generate loads of non-round integer types since these can
2940 // be expensive (and would be wrong if the type is not byte sized).
2941 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2942 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2943 EVT PtrType = LN0->getOperand(1).getValueType();
2945 unsigned Alignment = LN0->getAlignment();
2946 SDValue NewPtr = LN0->getBasePtr();
2948 // For big endian targets, we need to add an offset to the pointer
2949 // to load the correct bytes. For little endian systems, we merely
2950 // need to read fewer bytes from the same pointer.
2951 if (TLI.isBigEndian()) {
2952 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2953 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2954 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2955 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2956 NewPtr, DAG.getConstant(PtrOff, PtrType));
2957 Alignment = MinAlign(Alignment, PtrOff);
2960 AddToWorklist(NewPtr.getNode());
2962 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2964 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2965 LN0->getChain(), NewPtr,
2966 LN0->getPointerInfo(),
2967 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2968 Alignment, LN0->getAAInfo());
2970 CombineTo(LN0, Load, Load.getValue(1));
2971 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2977 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2978 VT.getSizeInBits() <= 64) {
2979 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2980 APInt ADDC = ADDI->getAPIntValue();
2981 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2982 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2983 // immediate for an add, but it is legal if its top c2 bits are set,
2984 // transform the ADD so the immediate doesn't need to be materialized
2986 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2987 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2988 SRLI->getZExtValue());
2989 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2991 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2993 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2994 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2995 CombineTo(N0.getNode(), NewAdd);
2996 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3004 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3005 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3006 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3007 N0.getOperand(1), false);
3008 if (BSwap.getNode())
3015 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3017 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3018 bool DemandHighBits) {
3019 if (!LegalOperations)
3022 EVT VT = N->getValueType(0);
3023 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3025 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3028 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3029 bool LookPassAnd0 = false;
3030 bool LookPassAnd1 = false;
3031 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3033 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3035 if (N0.getOpcode() == ISD::AND) {
3036 if (!N0.getNode()->hasOneUse())
3038 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3039 if (!N01C || N01C->getZExtValue() != 0xFF00)
3041 N0 = N0.getOperand(0);
3042 LookPassAnd0 = true;
3045 if (N1.getOpcode() == ISD::AND) {
3046 if (!N1.getNode()->hasOneUse())
3048 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3049 if (!N11C || N11C->getZExtValue() != 0xFF)
3051 N1 = N1.getOperand(0);
3052 LookPassAnd1 = true;
3055 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3057 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3059 if (!N0.getNode()->hasOneUse() ||
3060 !N1.getNode()->hasOneUse())
3063 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3064 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3067 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3070 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3071 SDValue N00 = N0->getOperand(0);
3072 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3073 if (!N00.getNode()->hasOneUse())
3075 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3076 if (!N001C || N001C->getZExtValue() != 0xFF)
3078 N00 = N00.getOperand(0);
3079 LookPassAnd0 = true;
3082 SDValue N10 = N1->getOperand(0);
3083 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3084 if (!N10.getNode()->hasOneUse())
3086 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3087 if (!N101C || N101C->getZExtValue() != 0xFF00)
3089 N10 = N10.getOperand(0);
3090 LookPassAnd1 = true;
3096 // Make sure everything beyond the low halfword gets set to zero since the SRL
3097 // 16 will clear the top bits.
3098 unsigned OpSizeInBits = VT.getSizeInBits();
3099 if (DemandHighBits && OpSizeInBits > 16) {
3100 // If the left-shift isn't masked out then the only way this is a bswap is
3101 // if all bits beyond the low 8 are 0. In that case the entire pattern
3102 // reduces to a left shift anyway: leave it for other parts of the combiner.
3106 // However, if the right shift isn't masked out then it might be because
3107 // it's not needed. See if we can spot that too.
3108 if (!LookPassAnd1 &&
3109 !DAG.MaskedValueIsZero(
3110 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3114 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3115 if (OpSizeInBits > 16)
3116 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3117 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3121 /// isBSwapHWordElement - Return true if the specified node is an element
3122 /// that makes up a 32-bit packed halfword byteswap. i.e.
3123 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3124 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3125 if (!N.getNode()->hasOneUse())
3128 unsigned Opc = N.getOpcode();
3129 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3132 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3137 switch (N1C->getZExtValue()) {
3140 case 0xFF: Num = 0; break;
3141 case 0xFF00: Num = 1; break;
3142 case 0xFF0000: Num = 2; break;
3143 case 0xFF000000: Num = 3; break;
3146 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3147 SDValue N0 = N.getOperand(0);
3148 if (Opc == ISD::AND) {
3149 if (Num == 0 || Num == 2) {
3151 // (x >> 8) & 0xff0000
3152 if (N0.getOpcode() != ISD::SRL)
3154 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3155 if (!C || C->getZExtValue() != 8)
3158 // (x << 8) & 0xff00
3159 // (x << 8) & 0xff000000
3160 if (N0.getOpcode() != ISD::SHL)
3162 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3163 if (!C || C->getZExtValue() != 8)
3166 } else if (Opc == ISD::SHL) {
3168 // (x & 0xff0000) << 8
3169 if (Num != 0 && Num != 2)
3171 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3172 if (!C || C->getZExtValue() != 8)
3174 } else { // Opc == ISD::SRL
3175 // (x & 0xff00) >> 8
3176 // (x & 0xff000000) >> 8
3177 if (Num != 1 && Num != 3)
3179 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3180 if (!C || C->getZExtValue() != 8)
3187 Parts[Num] = N0.getOperand(0).getNode();
3191 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3192 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3193 /// => (rotl (bswap x), 16)
3194 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3195 if (!LegalOperations)
3198 EVT VT = N->getValueType(0);
3201 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3204 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3206 // (or (or (and), (and)), (or (and), (and)))
3207 // (or (or (or (and), (and)), (and)), (and))
3208 if (N0.getOpcode() != ISD::OR)
3210 SDValue N00 = N0.getOperand(0);
3211 SDValue N01 = N0.getOperand(1);
3213 if (N1.getOpcode() == ISD::OR &&
3214 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3215 // (or (or (and), (and)), (or (and), (and)))
3216 SDValue N000 = N00.getOperand(0);
3217 if (!isBSwapHWordElement(N000, Parts))
3220 SDValue N001 = N00.getOperand(1);
3221 if (!isBSwapHWordElement(N001, Parts))
3223 SDValue N010 = N01.getOperand(0);
3224 if (!isBSwapHWordElement(N010, Parts))
3226 SDValue N011 = N01.getOperand(1);
3227 if (!isBSwapHWordElement(N011, Parts))
3230 // (or (or (or (and), (and)), (and)), (and))
3231 if (!isBSwapHWordElement(N1, Parts))
3233 if (!isBSwapHWordElement(N01, Parts))
3235 if (N00.getOpcode() != ISD::OR)
3237 SDValue N000 = N00.getOperand(0);
3238 if (!isBSwapHWordElement(N000, Parts))
3240 SDValue N001 = N00.getOperand(1);
3241 if (!isBSwapHWordElement(N001, Parts))
3245 // Make sure the parts are all coming from the same node.
3246 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3249 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3250 SDValue(Parts[0],0));
3252 // Result of the bswap should be rotated by 16. If it's not legal, then
3253 // do (x << 16) | (x >> 16).
3254 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3255 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3256 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3257 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3258 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3259 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3260 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3261 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3264 SDValue DAGCombiner::visitOR(SDNode *N) {
3265 SDValue N0 = N->getOperand(0);
3266 SDValue N1 = N->getOperand(1);
3267 SDValue LL, LR, RL, RR, CC0, CC1;
3268 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3269 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3270 EVT VT = N1.getValueType();
3273 if (VT.isVector()) {
3274 SDValue FoldedVOp = SimplifyVBinOp(N);
3275 if (FoldedVOp.getNode()) return FoldedVOp;
3277 // fold (or x, 0) -> x, vector edition
3278 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3280 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3283 // fold (or x, -1) -> -1, vector edition
3284 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3286 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3289 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3290 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3291 // Do this only if the resulting shuffle is legal.
3292 if (isa<ShuffleVectorSDNode>(N0) &&
3293 isa<ShuffleVectorSDNode>(N1) &&
3294 // Avoid folding a node with illegal type.
3295 TLI.isTypeLegal(VT) &&
3296 N0->getOperand(1) == N1->getOperand(1) &&
3297 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3298 bool CanFold = true;
3299 unsigned NumElts = VT.getVectorNumElements();
3300 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3301 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3302 // We construct two shuffle masks:
3303 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3304 // and N1 as the second operand.
3305 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3306 // and N0 as the second operand.
3307 // We do this because OR is commutable and therefore there might be
3308 // two ways to fold this node into a shuffle.
3309 SmallVector<int,4> Mask1;
3310 SmallVector<int,4> Mask2;
3312 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3313 int M0 = SV0->getMaskElt(i);
3314 int M1 = SV1->getMaskElt(i);
3316 // Both shuffle indexes are undef. Propagate Undef.
3317 if (M0 < 0 && M1 < 0) {
3318 Mask1.push_back(M0);
3319 Mask2.push_back(M0);
3323 if (M0 < 0 || M1 < 0 ||
3324 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3325 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3330 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3331 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3335 // Fold this sequence only if the resulting shuffle is 'legal'.
3336 if (TLI.isShuffleMaskLegal(Mask1, VT))
3337 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3338 N1->getOperand(0), &Mask1[0]);
3339 if (TLI.isShuffleMaskLegal(Mask2, VT))
3340 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3341 N0->getOperand(0), &Mask2[0]);
3346 // fold (or x, undef) -> -1
3347 if (!LegalOperations &&
3348 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3349 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3350 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3352 // fold (or c1, c2) -> c1|c2
3354 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3355 // canonicalize constant to RHS
3357 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3358 // fold (or x, 0) -> x
3359 if (N1C && N1C->isNullValue())
3361 // fold (or x, -1) -> -1
3362 if (N1C && N1C->isAllOnesValue())
3364 // fold (or x, c) -> c iff (x & ~c) == 0
3365 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3368 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3369 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3370 if (BSwap.getNode())
3372 BSwap = MatchBSwapHWordLow(N, N0, N1);
3373 if (BSwap.getNode())
3377 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3380 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3381 // iff (c1 & c2) == 0.
3382 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3383 isa<ConstantSDNode>(N0.getOperand(1))) {
3384 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3385 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3386 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3389 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3390 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3391 N0.getOperand(0), N1), COR);
3394 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3395 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3396 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3397 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3399 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3400 LL.getValueType().isInteger()) {
3401 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3402 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3403 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3404 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3405 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3406 LR.getValueType(), LL, RL);
3407 AddToWorklist(ORNode.getNode());
3408 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3410 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3411 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3412 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3413 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3414 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3415 LR.getValueType(), LL, RL);
3416 AddToWorklist(ANDNode.getNode());
3417 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3420 // canonicalize equivalent to ll == rl
3421 if (LL == RR && LR == RL) {
3422 Op1 = ISD::getSetCCSwappedOperands(Op1);
3425 if (LL == RL && LR == RR) {
3426 bool isInteger = LL.getValueType().isInteger();
3427 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3428 if (Result != ISD::SETCC_INVALID &&
3429 (!LegalOperations ||
3430 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3431 TLI.isOperationLegal(ISD::SETCC,
3432 getSetCCResultType(N0.getValueType())))))
3433 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3438 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3439 if (N0.getOpcode() == N1.getOpcode()) {
3440 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3441 if (Tmp.getNode()) return Tmp;
3444 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3445 if (N0.getOpcode() == ISD::AND &&
3446 N1.getOpcode() == ISD::AND &&
3447 N0.getOperand(1).getOpcode() == ISD::Constant &&
3448 N1.getOperand(1).getOpcode() == ISD::Constant &&
3449 // Don't increase # computations.
3450 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3451 // We can only do this xform if we know that bits from X that are set in C2
3452 // but not in C1 are already zero. Likewise for Y.
3453 const APInt &LHSMask =
3454 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3455 const APInt &RHSMask =
3456 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3458 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3459 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3460 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3461 N0.getOperand(0), N1.getOperand(0));
3462 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3463 DAG.getConstant(LHSMask | RHSMask, VT));
3467 // See if this is some rotate idiom.
3468 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3469 return SDValue(Rot, 0);
3471 // Simplify the operands using demanded-bits information.
3472 if (!VT.isVector() &&
3473 SimplifyDemandedBits(SDValue(N, 0)))
3474 return SDValue(N, 0);
3479 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3480 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3481 if (Op.getOpcode() == ISD::AND) {
3482 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3483 Mask = Op.getOperand(1);
3484 Op = Op.getOperand(0);
3490 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3498 // Return true if we can prove that, whenever Neg and Pos are both in the
3499 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3500 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3502 // (or (shift1 X, Neg), (shift2 X, Pos))
3504 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3505 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3506 // to consider shift amounts with defined behavior.
3507 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3508 // If OpSize is a power of 2 then:
3510 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3511 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3513 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3514 // for the stronger condition:
3516 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3518 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3519 // we can just replace Neg with Neg' for the rest of the function.
3521 // In other cases we check for the even stronger condition:
3523 // Neg == OpSize - Pos [B]
3525 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3526 // behavior if Pos == 0 (and consequently Neg == OpSize).
3528 // We could actually use [A] whenever OpSize is a power of 2, but the
3529 // only extra cases that it would match are those uninteresting ones
3530 // where Neg and Pos are never in range at the same time. E.g. for
3531 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3532 // as well as (sub 32, Pos), but:
3534 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3536 // always invokes undefined behavior for 32-bit X.
3538 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3539 unsigned MaskLoBits = 0;
3540 if (Neg.getOpcode() == ISD::AND &&
3541 isPowerOf2_64(OpSize) &&
3542 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3543 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3544 Neg = Neg.getOperand(0);
3545 MaskLoBits = Log2_64(OpSize);
3548 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3549 if (Neg.getOpcode() != ISD::SUB)
3551 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3554 SDValue NegOp1 = Neg.getOperand(1);
3556 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3557 // Pos'. The truncation is redundant for the purpose of the equality.
3559 Pos.getOpcode() == ISD::AND &&
3560 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3561 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3562 Pos = Pos.getOperand(0);
3564 // The condition we need is now:
3566 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3568 // If NegOp1 == Pos then we need:
3570 // OpSize & Mask == NegC & Mask
3572 // (because "x & Mask" is a truncation and distributes through subtraction).
3575 Width = NegC->getAPIntValue();
3576 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3577 // Then the condition we want to prove becomes:
3579 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3581 // which, again because "x & Mask" is a truncation, becomes:
3583 // NegC & Mask == (OpSize - PosC) & Mask
3584 // OpSize & Mask == (NegC + PosC) & Mask
3585 else if (Pos.getOpcode() == ISD::ADD &&
3586 Pos.getOperand(0) == NegOp1 &&
3587 Pos.getOperand(1).getOpcode() == ISD::Constant)
3588 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3589 NegC->getAPIntValue());
3593 // Now we just need to check that OpSize & Mask == Width & Mask.
3595 // Opsize & Mask is 0 since Mask is Opsize - 1.
3596 return Width.getLoBits(MaskLoBits) == 0;
3597 return Width == OpSize;
3600 // A subroutine of MatchRotate used once we have found an OR of two opposite
3601 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3602 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3603 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3604 // Neg with outer conversions stripped away.
3605 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3606 SDValue Neg, SDValue InnerPos,
3607 SDValue InnerNeg, unsigned PosOpcode,
3608 unsigned NegOpcode, SDLoc DL) {
3609 // fold (or (shl x, (*ext y)),
3610 // (srl x, (*ext (sub 32, y)))) ->
3611 // (rotl x, y) or (rotr x, (sub 32, y))
3613 // fold (or (shl x, (*ext (sub 32, y))),
3614 // (srl x, (*ext y))) ->
3615 // (rotr x, y) or (rotl x, (sub 32, y))
3616 EVT VT = Shifted.getValueType();
3617 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3618 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3619 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3620 HasPos ? Pos : Neg).getNode();
3626 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3627 // idioms for rotate, and if the target supports rotation instructions, generate
3629 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3630 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3631 EVT VT = LHS.getValueType();
3632 if (!TLI.isTypeLegal(VT)) return nullptr;
3634 // The target must have at least one rotate flavor.
3635 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3636 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3637 if (!HasROTL && !HasROTR) return nullptr;
3639 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3640 SDValue LHSShift; // The shift.
3641 SDValue LHSMask; // AND value if any.
3642 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3643 return nullptr; // Not part of a rotate.
3645 SDValue RHSShift; // The shift.
3646 SDValue RHSMask; // AND value if any.
3647 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3648 return nullptr; // Not part of a rotate.
3650 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3651 return nullptr; // Not shifting the same value.
3653 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3654 return nullptr; // Shifts must disagree.
3656 // Canonicalize shl to left side in a shl/srl pair.
3657 if (RHSShift.getOpcode() == ISD::SHL) {
3658 std::swap(LHS, RHS);
3659 std::swap(LHSShift, RHSShift);
3660 std::swap(LHSMask , RHSMask );
3663 unsigned OpSizeInBits = VT.getSizeInBits();
3664 SDValue LHSShiftArg = LHSShift.getOperand(0);
3665 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3666 SDValue RHSShiftArg = RHSShift.getOperand(0);
3667 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3669 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3670 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3671 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3672 RHSShiftAmt.getOpcode() == ISD::Constant) {
3673 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3674 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3675 if ((LShVal + RShVal) != OpSizeInBits)
3678 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3679 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3681 // If there is an AND of either shifted operand, apply it to the result.
3682 if (LHSMask.getNode() || RHSMask.getNode()) {
3683 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3685 if (LHSMask.getNode()) {
3686 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3687 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3689 if (RHSMask.getNode()) {
3690 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3691 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3694 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3697 return Rot.getNode();
3700 // If there is a mask here, and we have a variable shift, we can't be sure
3701 // that we're masking out the right stuff.
3702 if (LHSMask.getNode() || RHSMask.getNode())
3705 // If the shift amount is sign/zext/any-extended just peel it off.
3706 SDValue LExtOp0 = LHSShiftAmt;
3707 SDValue RExtOp0 = RHSShiftAmt;
3708 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3709 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3710 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3711 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3712 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3713 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3714 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3715 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3716 LExtOp0 = LHSShiftAmt.getOperand(0);
3717 RExtOp0 = RHSShiftAmt.getOperand(0);
3720 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3721 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3725 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3726 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3733 SDValue DAGCombiner::visitXOR(SDNode *N) {
3734 SDValue N0 = N->getOperand(0);
3735 SDValue N1 = N->getOperand(1);
3736 SDValue LHS, RHS, CC;
3737 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3738 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3739 EVT VT = N0.getValueType();
3742 if (VT.isVector()) {
3743 SDValue FoldedVOp = SimplifyVBinOp(N);
3744 if (FoldedVOp.getNode()) return FoldedVOp;
3746 // fold (xor x, 0) -> x, vector edition
3747 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3749 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3753 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3754 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3755 return DAG.getConstant(0, VT);
3756 // fold (xor x, undef) -> undef
3757 if (N0.getOpcode() == ISD::UNDEF)
3759 if (N1.getOpcode() == ISD::UNDEF)
3761 // fold (xor c1, c2) -> c1^c2
3763 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3764 // canonicalize constant to RHS
3766 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3767 // fold (xor x, 0) -> x
3768 if (N1C && N1C->isNullValue())
3771 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3775 // fold !(x cc y) -> (x !cc y)
3776 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3777 bool isInt = LHS.getValueType().isInteger();
3778 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3781 if (!LegalOperations ||
3782 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3783 switch (N0.getOpcode()) {
3785 llvm_unreachable("Unhandled SetCC Equivalent!");
3787 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3788 case ISD::SELECT_CC:
3789 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3790 N0.getOperand(3), NotCC);
3795 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3796 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3797 N0.getNode()->hasOneUse() &&
3798 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3799 SDValue V = N0.getOperand(0);
3800 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3801 DAG.getConstant(1, V.getValueType()));
3802 AddToWorklist(V.getNode());
3803 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3806 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3807 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3808 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3809 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3810 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3811 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3812 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3813 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3814 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3815 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3818 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3819 if (N1C && N1C->isAllOnesValue() &&
3820 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3821 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3822 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3823 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3824 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3825 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3826 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3827 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3830 // fold (xor (and x, y), y) -> (and (not x), y)
3831 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3832 N0->getOperand(1) == N1) {
3833 SDValue X = N0->getOperand(0);
3834 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3835 AddToWorklist(NotX.getNode());
3836 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3838 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3839 if (N1C && N0.getOpcode() == ISD::XOR) {
3840 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3841 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3843 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3844 DAG.getConstant(N1C->getAPIntValue() ^
3845 N00C->getAPIntValue(), VT));
3847 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3848 DAG.getConstant(N1C->getAPIntValue() ^
3849 N01C->getAPIntValue(), VT));
3851 // fold (xor x, x) -> 0
3853 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3855 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3856 if (N0.getOpcode() == N1.getOpcode()) {
3857 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3858 if (Tmp.getNode()) return Tmp;
3861 // Simplify the expression using non-local knowledge.
3862 if (!VT.isVector() &&
3863 SimplifyDemandedBits(SDValue(N, 0)))
3864 return SDValue(N, 0);
3869 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3870 /// the shift amount is a constant.
3871 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3872 // We can't and shouldn't fold opaque constants.
3873 if (Amt->isOpaque())
3876 SDNode *LHS = N->getOperand(0).getNode();
3877 if (!LHS->hasOneUse()) return SDValue();
3879 // We want to pull some binops through shifts, so that we have (and (shift))
3880 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3881 // thing happens with address calculations, so it's important to canonicalize
3883 bool HighBitSet = false; // Can we transform this if the high bit is set?
3885 switch (LHS->getOpcode()) {
3886 default: return SDValue();
3889 HighBitSet = false; // We can only transform sra if the high bit is clear.
3892 HighBitSet = true; // We can only transform sra if the high bit is set.
3895 if (N->getOpcode() != ISD::SHL)
3896 return SDValue(); // only shl(add) not sr[al](add).
3897 HighBitSet = false; // We can only transform sra if the high bit is clear.
3901 // We require the RHS of the binop to be a constant and not opaque as well.
3902 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3903 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3905 // FIXME: disable this unless the input to the binop is a shift by a constant.
3906 // If it is not a shift, it pessimizes some common cases like:
3908 // void foo(int *X, int i) { X[i & 1235] = 1; }
3909 // int bar(int *X, int i) { return X[i & 255]; }
3910 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3911 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3912 BinOpLHSVal->getOpcode() != ISD::SRA &&
3913 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3914 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3917 EVT VT = N->getValueType(0);
3919 // If this is a signed shift right, and the high bit is modified by the
3920 // logical operation, do not perform the transformation. The highBitSet
3921 // boolean indicates the value of the high bit of the constant which would
3922 // cause it to be modified for this operation.
3923 if (N->getOpcode() == ISD::SRA) {
3924 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3925 if (BinOpRHSSignSet != HighBitSet)
3929 if (!TLI.isDesirableToCommuteWithShift(LHS))
3932 // Fold the constants, shifting the binop RHS by the shift amount.
3933 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3935 LHS->getOperand(1), N->getOperand(1));
3936 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3938 // Create the new shift.
3939 SDValue NewShift = DAG.getNode(N->getOpcode(),
3940 SDLoc(LHS->getOperand(0)),
3941 VT, LHS->getOperand(0), N->getOperand(1));
3943 // Create the new binop.
3944 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3947 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3948 assert(N->getOpcode() == ISD::TRUNCATE);
3949 assert(N->getOperand(0).getOpcode() == ISD::AND);
3951 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3952 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3953 SDValue N01 = N->getOperand(0).getOperand(1);
3955 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3956 EVT TruncVT = N->getValueType(0);
3957 SDValue N00 = N->getOperand(0).getOperand(0);
3958 APInt TruncC = N01C->getAPIntValue();
3959 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3961 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3962 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3963 DAG.getConstant(TruncC, TruncVT));
3970 SDValue DAGCombiner::visitRotate(SDNode *N) {
3971 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3972 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3973 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3974 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3975 if (NewOp1.getNode())
3976 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3977 N->getOperand(0), NewOp1);
3982 SDValue DAGCombiner::visitSHL(SDNode *N) {
3983 SDValue N0 = N->getOperand(0);
3984 SDValue N1 = N->getOperand(1);
3985 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3986 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3987 EVT VT = N0.getValueType();
3988 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3991 if (VT.isVector()) {
3992 SDValue FoldedVOp = SimplifyVBinOp(N);
3993 if (FoldedVOp.getNode()) return FoldedVOp;
3995 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3996 // If setcc produces all-one true value then:
3997 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3998 if (N1CV && N1CV->isConstant()) {
3999 if (N0.getOpcode() == ISD::AND) {
4000 SDValue N00 = N0->getOperand(0);
4001 SDValue N01 = N0->getOperand(1);
4002 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4004 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4005 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4006 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4007 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4009 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4012 N1C = isConstOrConstSplat(N1);
4017 // fold (shl c1, c2) -> c1<<c2
4019 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4020 // fold (shl 0, x) -> 0
4021 if (N0C && N0C->isNullValue())
4023 // fold (shl x, c >= size(x)) -> undef
4024 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4025 return DAG.getUNDEF(VT);
4026 // fold (shl x, 0) -> x
4027 if (N1C && N1C->isNullValue())
4029 // fold (shl undef, x) -> 0
4030 if (N0.getOpcode() == ISD::UNDEF)
4031 return DAG.getConstant(0, VT);
4032 // if (shl x, c) is known to be zero, return 0
4033 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4034 APInt::getAllOnesValue(OpSizeInBits)))
4035 return DAG.getConstant(0, VT);
4036 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4037 if (N1.getOpcode() == ISD::TRUNCATE &&
4038 N1.getOperand(0).getOpcode() == ISD::AND) {
4039 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4040 if (NewOp1.getNode())
4041 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4044 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4045 return SDValue(N, 0);
4047 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4048 if (N1C && N0.getOpcode() == ISD::SHL) {
4049 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4050 uint64_t c1 = N0C1->getZExtValue();
4051 uint64_t c2 = N1C->getZExtValue();
4052 if (c1 + c2 >= OpSizeInBits)
4053 return DAG.getConstant(0, VT);
4054 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4055 DAG.getConstant(c1 + c2, N1.getValueType()));
4059 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4060 // For this to be valid, the second form must not preserve any of the bits
4061 // that are shifted out by the inner shift in the first form. This means
4062 // the outer shift size must be >= the number of bits added by the ext.
4063 // As a corollary, we don't care what kind of ext it is.
4064 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4065 N0.getOpcode() == ISD::ANY_EXTEND ||
4066 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4067 N0.getOperand(0).getOpcode() == ISD::SHL) {
4068 SDValue N0Op0 = N0.getOperand(0);
4069 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4070 uint64_t c1 = N0Op0C1->getZExtValue();
4071 uint64_t c2 = N1C->getZExtValue();
4072 EVT InnerShiftVT = N0Op0.getValueType();
4073 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4074 if (c2 >= OpSizeInBits - InnerShiftSize) {
4075 if (c1 + c2 >= OpSizeInBits)
4076 return DAG.getConstant(0, VT);
4077 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4078 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4079 N0Op0->getOperand(0)),
4080 DAG.getConstant(c1 + c2, N1.getValueType()));
4085 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4086 // Only fold this if the inner zext has no other uses to avoid increasing
4087 // the total number of instructions.
4088 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4089 N0.getOperand(0).getOpcode() == ISD::SRL) {
4090 SDValue N0Op0 = N0.getOperand(0);
4091 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4092 uint64_t c1 = N0Op0C1->getZExtValue();
4093 if (c1 < VT.getScalarSizeInBits()) {
4094 uint64_t c2 = N1C->getZExtValue();
4096 SDValue NewOp0 = N0.getOperand(0);
4097 EVT CountVT = NewOp0.getOperand(1).getValueType();
4098 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4099 NewOp0, DAG.getConstant(c2, CountVT));
4100 AddToWorklist(NewSHL.getNode());
4101 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4107 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4108 // (and (srl x, (sub c1, c2), MASK)
4109 // Only fold this if the inner shift has no other uses -- if it does, folding
4110 // this will increase the total number of instructions.
4111 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4112 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4113 uint64_t c1 = N0C1->getZExtValue();
4114 if (c1 < OpSizeInBits) {
4115 uint64_t c2 = N1C->getZExtValue();
4116 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4119 Mask = Mask.shl(c2 - c1);
4120 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4121 DAG.getConstant(c2 - c1, N1.getValueType()));
4123 Mask = Mask.lshr(c1 - c2);
4124 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4125 DAG.getConstant(c1 - c2, N1.getValueType()));
4127 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4128 DAG.getConstant(Mask, VT));
4132 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4133 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4134 unsigned BitSize = VT.getScalarSizeInBits();
4135 SDValue HiBitsMask =
4136 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4137 BitSize - N1C->getZExtValue()), VT);
4138 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4143 SDValue NewSHL = visitShiftByConstant(N, N1C);
4144 if (NewSHL.getNode())
4151 SDValue DAGCombiner::visitSRA(SDNode *N) {
4152 SDValue N0 = N->getOperand(0);
4153 SDValue N1 = N->getOperand(1);
4154 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4155 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4156 EVT VT = N0.getValueType();
4157 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4160 if (VT.isVector()) {
4161 SDValue FoldedVOp = SimplifyVBinOp(N);
4162 if (FoldedVOp.getNode()) return FoldedVOp;
4164 N1C = isConstOrConstSplat(N1);
4167 // fold (sra c1, c2) -> (sra c1, c2)
4169 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4170 // fold (sra 0, x) -> 0
4171 if (N0C && N0C->isNullValue())
4173 // fold (sra -1, x) -> -1
4174 if (N0C && N0C->isAllOnesValue())
4176 // fold (sra x, (setge c, size(x))) -> undef
4177 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4178 return DAG.getUNDEF(VT);
4179 // fold (sra x, 0) -> x
4180 if (N1C && N1C->isNullValue())
4182 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4184 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4185 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4186 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4188 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4189 ExtVT, VT.getVectorNumElements());
4190 if ((!LegalOperations ||
4191 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4192 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4193 N0.getOperand(0), DAG.getValueType(ExtVT));
4196 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4197 if (N1C && N0.getOpcode() == ISD::SRA) {
4198 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4199 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4200 if (Sum >= OpSizeInBits)
4201 Sum = OpSizeInBits - 1;
4202 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4203 DAG.getConstant(Sum, N1.getValueType()));
4207 // fold (sra (shl X, m), (sub result_size, n))
4208 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4209 // result_size - n != m.
4210 // If truncate is free for the target sext(shl) is likely to result in better
4212 if (N0.getOpcode() == ISD::SHL && N1C) {
4213 // Get the two constanst of the shifts, CN0 = m, CN = n.
4214 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4216 LLVMContext &Ctx = *DAG.getContext();
4217 // Determine what the truncate's result bitsize and type would be.
4218 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4221 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4223 // Determine the residual right-shift amount.
4224 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4226 // If the shift is not a no-op (in which case this should be just a sign
4227 // extend already), the truncated to type is legal, sign_extend is legal
4228 // on that type, and the truncate to that type is both legal and free,
4229 // perform the transform.
4230 if ((ShiftAmt > 0) &&
4231 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4232 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4233 TLI.isTruncateFree(VT, TruncVT)) {
4235 SDValue Amt = DAG.getConstant(ShiftAmt,
4236 getShiftAmountTy(N0.getOperand(0).getValueType()));
4237 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4238 N0.getOperand(0), Amt);
4239 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4241 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4242 N->getValueType(0), Trunc);
4247 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4248 if (N1.getOpcode() == ISD::TRUNCATE &&
4249 N1.getOperand(0).getOpcode() == ISD::AND) {
4250 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4251 if (NewOp1.getNode())
4252 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4255 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4256 // if c1 is equal to the number of bits the trunc removes
4257 if (N0.getOpcode() == ISD::TRUNCATE &&
4258 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4259 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4260 N0.getOperand(0).hasOneUse() &&
4261 N0.getOperand(0).getOperand(1).hasOneUse() &&
4263 SDValue N0Op0 = N0.getOperand(0);
4264 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4265 unsigned LargeShiftVal = LargeShift->getZExtValue();
4266 EVT LargeVT = N0Op0.getValueType();
4268 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4270 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4271 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4272 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4273 N0Op0.getOperand(0), Amt);
4274 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4279 // Simplify, based on bits shifted out of the LHS.
4280 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4281 return SDValue(N, 0);
4284 // If the sign bit is known to be zero, switch this to a SRL.
4285 if (DAG.SignBitIsZero(N0))
4286 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4289 SDValue NewSRA = visitShiftByConstant(N, N1C);
4290 if (NewSRA.getNode())
4297 SDValue DAGCombiner::visitSRL(SDNode *N) {
4298 SDValue N0 = N->getOperand(0);
4299 SDValue N1 = N->getOperand(1);
4300 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4301 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4302 EVT VT = N0.getValueType();
4303 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4306 if (VT.isVector()) {
4307 SDValue FoldedVOp = SimplifyVBinOp(N);
4308 if (FoldedVOp.getNode()) return FoldedVOp;
4310 N1C = isConstOrConstSplat(N1);
4313 // fold (srl c1, c2) -> c1 >>u c2
4315 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4316 // fold (srl 0, x) -> 0
4317 if (N0C && N0C->isNullValue())
4319 // fold (srl x, c >= size(x)) -> undef
4320 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4321 return DAG.getUNDEF(VT);
4322 // fold (srl x, 0) -> x
4323 if (N1C && N1C->isNullValue())
4325 // if (srl x, c) is known to be zero, return 0
4326 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4327 APInt::getAllOnesValue(OpSizeInBits)))
4328 return DAG.getConstant(0, VT);
4330 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4331 if (N1C && N0.getOpcode() == ISD::SRL) {
4332 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4333 uint64_t c1 = N01C->getZExtValue();
4334 uint64_t c2 = N1C->getZExtValue();
4335 if (c1 + c2 >= OpSizeInBits)
4336 return DAG.getConstant(0, VT);
4337 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4338 DAG.getConstant(c1 + c2, N1.getValueType()));
4342 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4343 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4344 N0.getOperand(0).getOpcode() == ISD::SRL &&
4345 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4347 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4348 uint64_t c2 = N1C->getZExtValue();
4349 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4350 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4351 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4352 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4353 if (c1 + OpSizeInBits == InnerShiftSize) {
4354 if (c1 + c2 >= InnerShiftSize)
4355 return DAG.getConstant(0, VT);
4356 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4357 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4358 N0.getOperand(0)->getOperand(0),
4359 DAG.getConstant(c1 + c2, ShiftCountVT)));
4363 // fold (srl (shl x, c), c) -> (and x, cst2)
4364 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4365 unsigned BitSize = N0.getScalarValueSizeInBits();
4366 if (BitSize <= 64) {
4367 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4368 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4369 DAG.getConstant(~0ULL >> ShAmt, VT));
4373 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4374 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4375 // Shifting in all undef bits?
4376 EVT SmallVT = N0.getOperand(0).getValueType();
4377 unsigned BitSize = SmallVT.getScalarSizeInBits();
4378 if (N1C->getZExtValue() >= BitSize)
4379 return DAG.getUNDEF(VT);
4381 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4382 uint64_t ShiftAmt = N1C->getZExtValue();
4383 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4385 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4386 AddToWorklist(SmallShift.getNode());
4387 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4388 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4389 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4390 DAG.getConstant(Mask, VT));
4394 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4395 // bit, which is unmodified by sra.
4396 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4397 if (N0.getOpcode() == ISD::SRA)
4398 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4401 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4402 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4403 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4404 APInt KnownZero, KnownOne;
4405 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4407 // If any of the input bits are KnownOne, then the input couldn't be all
4408 // zeros, thus the result of the srl will always be zero.
4409 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4411 // If all of the bits input the to ctlz node are known to be zero, then
4412 // the result of the ctlz is "32" and the result of the shift is one.
4413 APInt UnknownBits = ~KnownZero;
4414 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4416 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4417 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4418 // Okay, we know that only that the single bit specified by UnknownBits
4419 // could be set on input to the CTLZ node. If this bit is set, the SRL
4420 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4421 // to an SRL/XOR pair, which is likely to simplify more.
4422 unsigned ShAmt = UnknownBits.countTrailingZeros();
4423 SDValue Op = N0.getOperand(0);
4426 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4427 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4428 AddToWorklist(Op.getNode());
4431 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4432 Op, DAG.getConstant(1, VT));
4436 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4437 if (N1.getOpcode() == ISD::TRUNCATE &&
4438 N1.getOperand(0).getOpcode() == ISD::AND) {
4439 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4440 if (NewOp1.getNode())
4441 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4444 // fold operands of srl based on knowledge that the low bits are not
4446 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4447 return SDValue(N, 0);
4450 SDValue NewSRL = visitShiftByConstant(N, N1C);
4451 if (NewSRL.getNode())
4455 // Attempt to convert a srl of a load into a narrower zero-extending load.
4456 SDValue NarrowLoad = ReduceLoadWidth(N);
4457 if (NarrowLoad.getNode())
4460 // Here is a common situation. We want to optimize:
4463 // %b = and i32 %a, 2
4464 // %c = srl i32 %b, 1
4465 // brcond i32 %c ...
4471 // %c = setcc eq %b, 0
4474 // However when after the source operand of SRL is optimized into AND, the SRL
4475 // itself may not be optimized further. Look for it and add the BRCOND into
4477 if (N->hasOneUse()) {
4478 SDNode *Use = *N->use_begin();
4479 if (Use->getOpcode() == ISD::BRCOND)
4481 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4482 // Also look pass the truncate.
4483 Use = *Use->use_begin();
4484 if (Use->getOpcode() == ISD::BRCOND)
4492 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4493 SDValue N0 = N->getOperand(0);
4494 EVT VT = N->getValueType(0);
4496 // fold (ctlz c1) -> c2
4497 if (isa<ConstantSDNode>(N0))
4498 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4502 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4503 SDValue N0 = N->getOperand(0);
4504 EVT VT = N->getValueType(0);
4506 // fold (ctlz_zero_undef c1) -> c2
4507 if (isa<ConstantSDNode>(N0))
4508 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4512 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4513 SDValue N0 = N->getOperand(0);
4514 EVT VT = N->getValueType(0);
4516 // fold (cttz c1) -> c2
4517 if (isa<ConstantSDNode>(N0))
4518 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4522 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4523 SDValue N0 = N->getOperand(0);
4524 EVT VT = N->getValueType(0);
4526 // fold (cttz_zero_undef c1) -> c2
4527 if (isa<ConstantSDNode>(N0))
4528 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4532 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4533 SDValue N0 = N->getOperand(0);
4534 EVT VT = N->getValueType(0);
4536 // fold (ctpop c1) -> c2
4537 if (isa<ConstantSDNode>(N0))
4538 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4542 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4543 SDValue N0 = N->getOperand(0);
4544 SDValue N1 = N->getOperand(1);
4545 SDValue N2 = N->getOperand(2);
4546 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4547 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4548 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4549 EVT VT = N->getValueType(0);
4550 EVT VT0 = N0.getValueType();
4552 // fold (select C, X, X) -> X
4555 // fold (select true, X, Y) -> X
4556 if (N0C && !N0C->isNullValue())
4558 // fold (select false, X, Y) -> Y
4559 if (N0C && N0C->isNullValue())
4561 // fold (select C, 1, X) -> (or C, X)
4562 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4563 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4564 // fold (select C, 0, 1) -> (xor C, 1)
4565 // We can't do this reliably if integer based booleans have different contents
4566 // to floating point based booleans. This is because we can't tell whether we
4567 // have an integer-based boolean or a floating-point-based boolean unless we
4568 // can find the SETCC that produced it and inspect its operands. This is
4569 // fairly easy if C is the SETCC node, but it can potentially be
4570 // undiscoverable (or not reasonably discoverable). For example, it could be
4571 // in another basic block or it could require searching a complicated
4573 if (VT.isInteger() &&
4574 (VT0 == MVT::i1 || (VT0.isInteger() &&
4575 TLI.getBooleanContents(false, false) ==
4576 TLI.getBooleanContents(false, true) &&
4577 TLI.getBooleanContents(false, false) ==
4578 TargetLowering::ZeroOrOneBooleanContent)) &&
4579 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4582 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4583 N0, DAG.getConstant(1, VT0));
4584 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4585 N0, DAG.getConstant(1, VT0));
4586 AddToWorklist(XORNode.getNode());
4588 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4589 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4591 // fold (select C, 0, X) -> (and (not C), X)
4592 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4593 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4594 AddToWorklist(NOTNode.getNode());
4595 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4597 // fold (select C, X, 1) -> (or (not C), X)
4598 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4599 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4600 AddToWorklist(NOTNode.getNode());
4601 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4603 // fold (select C, X, 0) -> (and C, X)
4604 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4605 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4606 // fold (select X, X, Y) -> (or X, Y)
4607 // fold (select X, 1, Y) -> (or X, Y)
4608 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4609 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4610 // fold (select X, Y, X) -> (and X, Y)
4611 // fold (select X, Y, 0) -> (and X, Y)
4612 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4613 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4615 // If we can fold this based on the true/false value, do so.
4616 if (SimplifySelectOps(N, N1, N2))
4617 return SDValue(N, 0); // Don't revisit N.
4619 // fold selects based on a setcc into other things, such as min/max/abs
4620 if (N0.getOpcode() == ISD::SETCC) {
4621 if ((!LegalOperations &&
4622 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4623 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4624 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4625 N0.getOperand(0), N0.getOperand(1),
4626 N1, N2, N0.getOperand(2));
4627 return SimplifySelect(SDLoc(N), N0, N1, N2);
4634 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4637 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4639 // Split the inputs.
4640 SDValue Lo, Hi, LL, LH, RL, RH;
4641 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4642 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4644 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4645 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4647 return std::make_pair(Lo, Hi);
4650 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4651 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4652 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4654 SDValue Cond = N->getOperand(0);
4655 SDValue LHS = N->getOperand(1);
4656 SDValue RHS = N->getOperand(2);
4657 MVT VT = N->getSimpleValueType(0);
4658 int NumElems = VT.getVectorNumElements();
4659 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4660 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4661 Cond.getOpcode() == ISD::BUILD_VECTOR);
4663 // We're sure we have an even number of elements due to the
4664 // concat_vectors we have as arguments to vselect.
4665 // Skip BV elements until we find one that's not an UNDEF
4666 // After we find an UNDEF element, keep looping until we get to half the
4667 // length of the BV and see if all the non-undef nodes are the same.
4668 ConstantSDNode *BottomHalf = nullptr;
4669 for (int i = 0; i < NumElems / 2; ++i) {
4670 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4673 if (BottomHalf == nullptr)
4674 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4675 else if (Cond->getOperand(i).getNode() != BottomHalf)
4679 // Do the same for the second half of the BuildVector
4680 ConstantSDNode *TopHalf = nullptr;
4681 for (int i = NumElems / 2; i < NumElems; ++i) {
4682 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4685 if (TopHalf == nullptr)
4686 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4687 else if (Cond->getOperand(i).getNode() != TopHalf)
4691 assert(TopHalf && BottomHalf &&
4692 "One half of the selector was all UNDEFs and the other was all the "
4693 "same value. This should have been addressed before this function.");
4695 ISD::CONCAT_VECTORS, dl, VT,
4696 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4697 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4700 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4701 SDValue N0 = N->getOperand(0);
4702 SDValue N1 = N->getOperand(1);
4703 SDValue N2 = N->getOperand(2);
4706 // Canonicalize integer abs.
4707 // vselect (setg[te] X, 0), X, -X ->
4708 // vselect (setgt X, -1), X, -X ->
4709 // vselect (setl[te] X, 0), -X, X ->
4710 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4711 if (N0.getOpcode() == ISD::SETCC) {
4712 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4713 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4715 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4717 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4718 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4719 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4720 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4721 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4722 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4723 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4726 EVT VT = LHS.getValueType();
4727 SDValue Shift = DAG.getNode(
4728 ISD::SRA, DL, VT, LHS,
4729 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4730 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4731 AddToWorklist(Shift.getNode());
4732 AddToWorklist(Add.getNode());
4733 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4737 // If the VSELECT result requires splitting and the mask is provided by a
4738 // SETCC, then split both nodes and its operands before legalization. This
4739 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4740 // and enables future optimizations (e.g. min/max pattern matching on X86).
4741 if (N0.getOpcode() == ISD::SETCC) {
4742 EVT VT = N->getValueType(0);
4744 // Check if any splitting is required.
4745 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4746 TargetLowering::TypeSplitVector)
4749 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4750 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4751 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4752 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4754 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4755 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4757 // Add the new VSELECT nodes to the work list in case they need to be split
4759 AddToWorklist(Lo.getNode());
4760 AddToWorklist(Hi.getNode());
4762 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4765 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4766 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4768 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4769 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4772 // The ConvertSelectToConcatVector function is assuming both the above
4773 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4775 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4776 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4777 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4778 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4786 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4787 SDValue N0 = N->getOperand(0);
4788 SDValue N1 = N->getOperand(1);
4789 SDValue N2 = N->getOperand(2);
4790 SDValue N3 = N->getOperand(3);
4791 SDValue N4 = N->getOperand(4);
4792 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4794 // fold select_cc lhs, rhs, x, x, cc -> x
4798 // Determine if the condition we're dealing with is constant
4799 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4800 N0, N1, CC, SDLoc(N), false);
4801 if (SCC.getNode()) {
4802 AddToWorklist(SCC.getNode());
4804 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4805 if (!SCCC->isNullValue())
4806 return N2; // cond always true -> true val
4808 return N3; // cond always false -> false val
4811 // Fold to a simpler select_cc
4812 if (SCC.getOpcode() == ISD::SETCC)
4813 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4814 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4818 // If we can fold this based on the true/false value, do so.
4819 if (SimplifySelectOps(N, N2, N3))
4820 return SDValue(N, 0); // Don't revisit N.
4822 // fold select_cc into other things, such as min/max/abs
4823 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4826 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4827 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4828 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4832 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4833 // dag node into a ConstantSDNode or a build_vector of constants.
4834 // This function is called by the DAGCombiner when visiting sext/zext/aext
4835 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4836 // Vector extends are not folded if operations are legal; this is to
4837 // avoid introducing illegal build_vector dag nodes.
4838 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4839 SelectionDAG &DAG, bool LegalTypes,
4840 bool LegalOperations) {
4841 unsigned Opcode = N->getOpcode();
4842 SDValue N0 = N->getOperand(0);
4843 EVT VT = N->getValueType(0);
4845 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4846 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4848 // fold (sext c1) -> c1
4849 // fold (zext c1) -> c1
4850 // fold (aext c1) -> c1
4851 if (isa<ConstantSDNode>(N0))
4852 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4854 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4855 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4856 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4857 EVT SVT = VT.getScalarType();
4858 if (!(VT.isVector() &&
4859 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4860 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4863 // We can fold this node into a build_vector.
4864 unsigned VTBits = SVT.getSizeInBits();
4865 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4866 unsigned ShAmt = VTBits - EVTBits;
4867 SmallVector<SDValue, 8> Elts;
4868 unsigned NumElts = N0->getNumOperands();
4871 for (unsigned i=0; i != NumElts; ++i) {
4872 SDValue Op = N0->getOperand(i);
4873 if (Op->getOpcode() == ISD::UNDEF) {
4874 Elts.push_back(DAG.getUNDEF(SVT));
4878 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4879 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4880 if (Opcode == ISD::SIGN_EXTEND)
4881 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4884 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4888 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4891 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4892 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4893 // transformation. Returns true if extension are possible and the above
4894 // mentioned transformation is profitable.
4895 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4897 SmallVectorImpl<SDNode *> &ExtendNodes,
4898 const TargetLowering &TLI) {
4899 bool HasCopyToRegUses = false;
4900 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4901 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4902 UE = N0.getNode()->use_end();
4907 if (UI.getUse().getResNo() != N0.getResNo())
4909 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4910 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4911 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4912 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4913 // Sign bits will be lost after a zext.
4916 for (unsigned i = 0; i != 2; ++i) {
4917 SDValue UseOp = User->getOperand(i);
4920 if (!isa<ConstantSDNode>(UseOp))
4925 ExtendNodes.push_back(User);
4928 // If truncates aren't free and there are users we can't
4929 // extend, it isn't worthwhile.
4932 // Remember if this value is live-out.
4933 if (User->getOpcode() == ISD::CopyToReg)
4934 HasCopyToRegUses = true;
4937 if (HasCopyToRegUses) {
4938 bool BothLiveOut = false;
4939 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4941 SDUse &Use = UI.getUse();
4942 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4948 // Both unextended and extended values are live out. There had better be
4949 // a good reason for the transformation.
4950 return ExtendNodes.size();
4955 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4956 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4957 ISD::NodeType ExtType) {
4958 // Extend SetCC uses if necessary.
4959 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4960 SDNode *SetCC = SetCCs[i];
4961 SmallVector<SDValue, 4> Ops;
4963 for (unsigned j = 0; j != 2; ++j) {
4964 SDValue SOp = SetCC->getOperand(j);
4966 Ops.push_back(ExtLoad);
4968 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4971 Ops.push_back(SetCC->getOperand(2));
4972 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4976 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4977 SDValue N0 = N->getOperand(0);
4978 EVT VT = N->getValueType(0);
4980 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4982 return SDValue(Res, 0);
4984 // fold (sext (sext x)) -> (sext x)
4985 // fold (sext (aext x)) -> (sext x)
4986 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4987 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4990 if (N0.getOpcode() == ISD::TRUNCATE) {
4991 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4992 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4993 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4994 if (NarrowLoad.getNode()) {
4995 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4996 if (NarrowLoad.getNode() != N0.getNode()) {
4997 CombineTo(N0.getNode(), NarrowLoad);
4998 // CombineTo deleted the truncate, if needed, but not what's under it.
5001 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5004 // See if the value being truncated is already sign extended. If so, just
5005 // eliminate the trunc/sext pair.
5006 SDValue Op = N0.getOperand(0);
5007 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5008 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5009 unsigned DestBits = VT.getScalarType().getSizeInBits();
5010 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5012 if (OpBits == DestBits) {
5013 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5014 // bits, it is already ready.
5015 if (NumSignBits > DestBits-MidBits)
5017 } else if (OpBits < DestBits) {
5018 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5019 // bits, just sext from i32.
5020 if (NumSignBits > OpBits-MidBits)
5021 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5023 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5024 // bits, just truncate to i32.
5025 if (NumSignBits > OpBits-MidBits)
5026 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5029 // fold (sext (truncate x)) -> (sextinreg x).
5030 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5031 N0.getValueType())) {
5032 if (OpBits < DestBits)
5033 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5034 else if (OpBits > DestBits)
5035 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5036 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5037 DAG.getValueType(N0.getValueType()));
5041 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5042 // None of the supported targets knows how to perform load and sign extend
5043 // on vectors in one instruction. We only perform this transformation on
5045 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5046 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5047 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5048 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5049 bool DoXform = true;
5050 SmallVector<SDNode*, 4> SetCCs;
5051 if (!N0.hasOneUse())
5052 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5054 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5055 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5057 LN0->getBasePtr(), N0.getValueType(),
5058 LN0->getMemOperand());
5059 CombineTo(N, ExtLoad);
5060 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5061 N0.getValueType(), ExtLoad);
5062 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5063 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5065 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5069 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5070 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5071 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5072 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5073 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5074 EVT MemVT = LN0->getMemoryVT();
5075 if ((!LegalOperations && !LN0->isVolatile()) ||
5076 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5077 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5079 LN0->getBasePtr(), MemVT,
5080 LN0->getMemOperand());
5081 CombineTo(N, ExtLoad);
5082 CombineTo(N0.getNode(),
5083 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5084 N0.getValueType(), ExtLoad),
5085 ExtLoad.getValue(1));
5086 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5090 // fold (sext (and/or/xor (load x), cst)) ->
5091 // (and/or/xor (sextload x), (sext cst))
5092 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5093 N0.getOpcode() == ISD::XOR) &&
5094 isa<LoadSDNode>(N0.getOperand(0)) &&
5095 N0.getOperand(1).getOpcode() == ISD::Constant &&
5096 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5097 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5098 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5099 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5100 bool DoXform = true;
5101 SmallVector<SDNode*, 4> SetCCs;
5102 if (!N0.hasOneUse())
5103 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5106 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5107 LN0->getChain(), LN0->getBasePtr(),
5109 LN0->getMemOperand());
5110 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5111 Mask = Mask.sext(VT.getSizeInBits());
5112 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5113 ExtLoad, DAG.getConstant(Mask, VT));
5114 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5115 SDLoc(N0.getOperand(0)),
5116 N0.getOperand(0).getValueType(), ExtLoad);
5118 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5119 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5121 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5126 if (N0.getOpcode() == ISD::SETCC) {
5127 EVT N0VT = N0.getOperand(0).getValueType();
5128 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5129 // Only do this before legalize for now.
5130 if (VT.isVector() && !LegalOperations &&
5131 TLI.getBooleanContents(N0VT) ==
5132 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5133 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5134 // of the same size as the compared operands. Only optimize sext(setcc())
5135 // if this is the case.
5136 EVT SVT = getSetCCResultType(N0VT);
5138 // We know that the # elements of the results is the same as the
5139 // # elements of the compare (and the # elements of the compare result
5140 // for that matter). Check to see that they are the same size. If so,
5141 // we know that the element size of the sext'd result matches the
5142 // element size of the compare operands.
5143 if (VT.getSizeInBits() == SVT.getSizeInBits())
5144 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5146 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5148 // If the desired elements are smaller or larger than the source
5149 // elements we can use a matching integer vector type and then
5150 // truncate/sign extend
5151 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5152 if (SVT == MatchingVectorType) {
5153 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5154 N0.getOperand(0), N0.getOperand(1),
5155 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5156 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5160 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5161 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5163 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5165 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5166 NegOne, DAG.getConstant(0, VT),
5167 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5168 if (SCC.getNode()) return SCC;
5170 if (!VT.isVector()) {
5171 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5172 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5174 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5175 SDValue SetCC = DAG.getSetCC(DL,
5177 N0.getOperand(0), N0.getOperand(1), CC);
5178 EVT SelectVT = getSetCCResultType(VT);
5179 return DAG.getSelect(DL, VT,
5180 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5181 NegOne, DAG.getConstant(0, VT));
5187 // fold (sext x) -> (zext x) if the sign bit is known zero.
5188 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5189 DAG.SignBitIsZero(N0))
5190 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5195 // isTruncateOf - If N is a truncate of some other value, return true, record
5196 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5197 // This function computes KnownZero to avoid a duplicated call to
5198 // computeKnownBits in the caller.
5199 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5202 if (N->getOpcode() == ISD::TRUNCATE) {
5203 Op = N->getOperand(0);
5204 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5208 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5209 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5212 SDValue Op0 = N->getOperand(0);
5213 SDValue Op1 = N->getOperand(1);
5214 assert(Op0.getValueType() == Op1.getValueType());
5216 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5217 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5218 if (COp0 && COp0->isNullValue())
5220 else if (COp1 && COp1->isNullValue())
5225 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5227 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5233 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5234 SDValue N0 = N->getOperand(0);
5235 EVT VT = N->getValueType(0);
5237 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5239 return SDValue(Res, 0);
5241 // fold (zext (zext x)) -> (zext x)
5242 // fold (zext (aext x)) -> (zext x)
5243 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5244 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5247 // fold (zext (truncate x)) -> (zext x) or
5248 // (zext (truncate x)) -> (truncate x)
5249 // This is valid when the truncated bits of x are already zero.
5250 // FIXME: We should extend this to work for vectors too.
5253 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5254 APInt TruncatedBits =
5255 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5256 APInt(Op.getValueSizeInBits(), 0) :
5257 APInt::getBitsSet(Op.getValueSizeInBits(),
5258 N0.getValueSizeInBits(),
5259 std::min(Op.getValueSizeInBits(),
5260 VT.getSizeInBits()));
5261 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5262 if (VT.bitsGT(Op.getValueType()))
5263 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5264 if (VT.bitsLT(Op.getValueType()))
5265 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5271 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5272 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5273 if (N0.getOpcode() == ISD::TRUNCATE) {
5274 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5275 if (NarrowLoad.getNode()) {
5276 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5277 if (NarrowLoad.getNode() != N0.getNode()) {
5278 CombineTo(N0.getNode(), NarrowLoad);
5279 // CombineTo deleted the truncate, if needed, but not what's under it.
5282 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5286 // fold (zext (truncate x)) -> (and x, mask)
5287 if (N0.getOpcode() == ISD::TRUNCATE &&
5288 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5290 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5291 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5292 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5293 if (NarrowLoad.getNode()) {
5294 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5295 if (NarrowLoad.getNode() != N0.getNode()) {
5296 CombineTo(N0.getNode(), NarrowLoad);
5297 // CombineTo deleted the truncate, if needed, but not what's under it.
5300 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5303 SDValue Op = N0.getOperand(0);
5304 if (Op.getValueType().bitsLT(VT)) {
5305 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5306 AddToWorklist(Op.getNode());
5307 } else if (Op.getValueType().bitsGT(VT)) {
5308 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5309 AddToWorklist(Op.getNode());
5311 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5312 N0.getValueType().getScalarType());
5315 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5316 // if either of the casts is not free.
5317 if (N0.getOpcode() == ISD::AND &&
5318 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5319 N0.getOperand(1).getOpcode() == ISD::Constant &&
5320 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5321 N0.getValueType()) ||
5322 !TLI.isZExtFree(N0.getValueType(), VT))) {
5323 SDValue X = N0.getOperand(0).getOperand(0);
5324 if (X.getValueType().bitsLT(VT)) {
5325 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5326 } else if (X.getValueType().bitsGT(VT)) {
5327 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5329 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5330 Mask = Mask.zext(VT.getSizeInBits());
5331 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5332 X, DAG.getConstant(Mask, VT));
5335 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5336 // None of the supported targets knows how to perform load and vector_zext
5337 // on vectors in one instruction. We only perform this transformation on
5339 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5340 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5341 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5342 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5343 bool DoXform = true;
5344 SmallVector<SDNode*, 4> SetCCs;
5345 if (!N0.hasOneUse())
5346 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5348 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5349 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5351 LN0->getBasePtr(), N0.getValueType(),
5352 LN0->getMemOperand());
5353 CombineTo(N, ExtLoad);
5354 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5355 N0.getValueType(), ExtLoad);
5356 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5358 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5360 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5364 // fold (zext (and/or/xor (load x), cst)) ->
5365 // (and/or/xor (zextload x), (zext cst))
5366 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5367 N0.getOpcode() == ISD::XOR) &&
5368 isa<LoadSDNode>(N0.getOperand(0)) &&
5369 N0.getOperand(1).getOpcode() == ISD::Constant &&
5370 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5371 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5372 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5373 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5374 bool DoXform = true;
5375 SmallVector<SDNode*, 4> SetCCs;
5376 if (!N0.hasOneUse())
5377 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5380 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5381 LN0->getChain(), LN0->getBasePtr(),
5383 LN0->getMemOperand());
5384 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5385 Mask = Mask.zext(VT.getSizeInBits());
5386 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5387 ExtLoad, DAG.getConstant(Mask, VT));
5388 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5389 SDLoc(N0.getOperand(0)),
5390 N0.getOperand(0).getValueType(), ExtLoad);
5392 CombineTo(N0.getOperand(0).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!
5400 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5401 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5402 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5403 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5404 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5405 EVT MemVT = LN0->getMemoryVT();
5406 if ((!LegalOperations && !LN0->isVolatile()) ||
5407 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5408 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5410 LN0->getBasePtr(), MemVT,
5411 LN0->getMemOperand());
5412 CombineTo(N, ExtLoad);
5413 CombineTo(N0.getNode(),
5414 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5416 ExtLoad.getValue(1));
5417 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5421 if (N0.getOpcode() == ISD::SETCC) {
5422 if (!LegalOperations && VT.isVector() &&
5423 N0.getValueType().getVectorElementType() == MVT::i1) {
5424 EVT N0VT = N0.getOperand(0).getValueType();
5425 if (getSetCCResultType(N0VT) == N0.getValueType())
5428 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5429 // Only do this before legalize for now.
5430 EVT EltVT = VT.getVectorElementType();
5431 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5432 DAG.getConstant(1, EltVT));
5433 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5434 // We know that the # elements of the results is the same as the
5435 // # elements of the compare (and the # elements of the compare result
5436 // for that matter). Check to see that they are the same size. If so,
5437 // we know that the element size of the sext'd result matches the
5438 // element size of the compare operands.
5439 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5440 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5442 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5443 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5446 // If the desired elements are smaller or larger than the source
5447 // elements we can use a matching integer vector type and then
5448 // truncate/sign extend
5449 EVT MatchingElementType =
5450 EVT::getIntegerVT(*DAG.getContext(),
5451 N0VT.getScalarType().getSizeInBits());
5452 EVT MatchingVectorType =
5453 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5454 N0VT.getVectorNumElements());
5456 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5458 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5459 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5460 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5461 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5464 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5466 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5467 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5468 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5469 if (SCC.getNode()) return SCC;
5472 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5473 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5474 isa<ConstantSDNode>(N0.getOperand(1)) &&
5475 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5477 SDValue ShAmt = N0.getOperand(1);
5478 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5479 if (N0.getOpcode() == ISD::SHL) {
5480 SDValue InnerZExt = N0.getOperand(0);
5481 // If the original shl may be shifting out bits, do not perform this
5483 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5484 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5485 if (ShAmtVal > KnownZeroBits)
5491 // Ensure that the shift amount is wide enough for the shifted value.
5492 if (VT.getSizeInBits() >= 256)
5493 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5495 return DAG.getNode(N0.getOpcode(), DL, VT,
5496 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5503 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5504 SDValue N0 = N->getOperand(0);
5505 EVT VT = N->getValueType(0);
5507 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5509 return SDValue(Res, 0);
5511 // fold (aext (aext x)) -> (aext x)
5512 // fold (aext (zext x)) -> (zext x)
5513 // fold (aext (sext x)) -> (sext x)
5514 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5515 N0.getOpcode() == ISD::ZERO_EXTEND ||
5516 N0.getOpcode() == ISD::SIGN_EXTEND)
5517 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5519 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5520 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5521 if (N0.getOpcode() == ISD::TRUNCATE) {
5522 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5523 if (NarrowLoad.getNode()) {
5524 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5525 if (NarrowLoad.getNode() != N0.getNode()) {
5526 CombineTo(N0.getNode(), NarrowLoad);
5527 // CombineTo deleted the truncate, if needed, but not what's under it.
5530 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5534 // fold (aext (truncate x))
5535 if (N0.getOpcode() == ISD::TRUNCATE) {
5536 SDValue TruncOp = N0.getOperand(0);
5537 if (TruncOp.getValueType() == VT)
5538 return TruncOp; // x iff x size == zext size.
5539 if (TruncOp.getValueType().bitsGT(VT))
5540 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5541 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5544 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5545 // if the trunc is not free.
5546 if (N0.getOpcode() == ISD::AND &&
5547 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5548 N0.getOperand(1).getOpcode() == ISD::Constant &&
5549 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5550 N0.getValueType())) {
5551 SDValue X = N0.getOperand(0).getOperand(0);
5552 if (X.getValueType().bitsLT(VT)) {
5553 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5554 } else if (X.getValueType().bitsGT(VT)) {
5555 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5557 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5558 Mask = Mask.zext(VT.getSizeInBits());
5559 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5560 X, DAG.getConstant(Mask, VT));
5563 // fold (aext (load x)) -> (aext (truncate (extload x)))
5564 // None of the supported targets knows how to perform load and any_ext
5565 // on vectors in one instruction. We only perform this transformation on
5567 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5568 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5569 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5570 bool DoXform = true;
5571 SmallVector<SDNode*, 4> SetCCs;
5572 if (!N0.hasOneUse())
5573 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5575 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5576 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5578 LN0->getBasePtr(), N0.getValueType(),
5579 LN0->getMemOperand());
5580 CombineTo(N, ExtLoad);
5581 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5582 N0.getValueType(), ExtLoad);
5583 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5584 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5586 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5590 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5591 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5592 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5593 if (N0.getOpcode() == ISD::LOAD &&
5594 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5596 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5597 ISD::LoadExtType ExtType = LN0->getExtensionType();
5598 EVT MemVT = LN0->getMemoryVT();
5599 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5600 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5601 VT, LN0->getChain(), LN0->getBasePtr(),
5602 MemVT, LN0->getMemOperand());
5603 CombineTo(N, ExtLoad);
5604 CombineTo(N0.getNode(),
5605 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5606 N0.getValueType(), ExtLoad),
5607 ExtLoad.getValue(1));
5608 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5612 if (N0.getOpcode() == ISD::SETCC) {
5614 // aext(setcc) -> vsetcc
5615 // aext(setcc) -> truncate(vsetcc)
5616 // aext(setcc) -> aext(vsetcc)
5617 // Only do this before legalize for now.
5618 if (VT.isVector() && !LegalOperations) {
5619 EVT N0VT = N0.getOperand(0).getValueType();
5620 // We know that the # elements of the results is the same as the
5621 // # elements of the compare (and the # elements of the compare result
5622 // for that matter). Check to see that they are the same size. If so,
5623 // we know that the element size of the sext'd result matches the
5624 // element size of the compare operands.
5625 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5626 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5628 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5629 // If the desired elements are smaller or larger than the source
5630 // elements we can use a matching integer vector type and then
5631 // truncate/any extend
5633 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5635 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5637 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5638 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5642 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5644 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5645 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5646 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5654 /// GetDemandedBits - See if the specified operand can be simplified with the
5655 /// knowledge that only the bits specified by Mask are used. If so, return the
5656 /// simpler operand, otherwise return a null SDValue.
5657 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5658 switch (V.getOpcode()) {
5660 case ISD::Constant: {
5661 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5662 assert(CV && "Const value should be ConstSDNode.");
5663 const APInt &CVal = CV->getAPIntValue();
5664 APInt NewVal = CVal & Mask;
5666 return DAG.getConstant(NewVal, V.getValueType());
5671 // If the LHS or RHS don't contribute bits to the or, drop them.
5672 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5673 return V.getOperand(1);
5674 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5675 return V.getOperand(0);
5678 // Only look at single-use SRLs.
5679 if (!V.getNode()->hasOneUse())
5681 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5682 // See if we can recursively simplify the LHS.
5683 unsigned Amt = RHSC->getZExtValue();
5685 // Watch out for shift count overflow though.
5686 if (Amt >= Mask.getBitWidth()) break;
5687 APInt NewMask = Mask << Amt;
5688 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5689 if (SimplifyLHS.getNode())
5690 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5691 SimplifyLHS, V.getOperand(1));
5697 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5698 /// bits and then truncated to a narrower type and where N is a multiple
5699 /// of number of bits of the narrower type, transform it to a narrower load
5700 /// from address + N / num of bits of new type. If the result is to be
5701 /// extended, also fold the extension to form a extending load.
5702 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5703 unsigned Opc = N->getOpcode();
5705 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5706 SDValue N0 = N->getOperand(0);
5707 EVT VT = N->getValueType(0);
5710 // This transformation isn't valid for vector loads.
5714 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5716 if (Opc == ISD::SIGN_EXTEND_INREG) {
5717 ExtType = ISD::SEXTLOAD;
5718 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5719 } else if (Opc == ISD::SRL) {
5720 // Another special-case: SRL is basically zero-extending a narrower value.
5721 ExtType = ISD::ZEXTLOAD;
5723 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5724 if (!N01) return SDValue();
5725 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5726 VT.getSizeInBits() - N01->getZExtValue());
5728 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5731 unsigned EVTBits = ExtVT.getSizeInBits();
5733 // Do not generate loads of non-round integer types since these can
5734 // be expensive (and would be wrong if the type is not byte sized).
5735 if (!ExtVT.isRound())
5739 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5740 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5741 ShAmt = N01->getZExtValue();
5742 // Is the shift amount a multiple of size of VT?
5743 if ((ShAmt & (EVTBits-1)) == 0) {
5744 N0 = N0.getOperand(0);
5745 // Is the load width a multiple of size of VT?
5746 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5750 // At this point, we must have a load or else we can't do the transform.
5751 if (!isa<LoadSDNode>(N0)) return SDValue();
5753 // Because a SRL must be assumed to *need* to zero-extend the high bits
5754 // (as opposed to anyext the high bits), we can't combine the zextload
5755 // lowering of SRL and an sextload.
5756 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5759 // If the shift amount is larger than the input type then we're not
5760 // accessing any of the loaded bytes. If the load was a zextload/extload
5761 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5762 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5767 // If the load is shifted left (and the result isn't shifted back right),
5768 // we can fold the truncate through the shift.
5769 unsigned ShLeftAmt = 0;
5770 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5771 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5772 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5773 ShLeftAmt = N01->getZExtValue();
5774 N0 = N0.getOperand(0);
5778 // If we haven't found a load, we can't narrow it. Don't transform one with
5779 // multiple uses, this would require adding a new load.
5780 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5783 // Don't change the width of a volatile load.
5784 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5785 if (LN0->isVolatile())
5788 // Verify that we are actually reducing a load width here.
5789 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5792 // For the transform to be legal, the load must produce only two values
5793 // (the value loaded and the chain). Don't transform a pre-increment
5794 // load, for example, which produces an extra value. Otherwise the
5795 // transformation is not equivalent, and the downstream logic to replace
5796 // uses gets things wrong.
5797 if (LN0->getNumValues() > 2)
5800 // If the load that we're shrinking is an extload and we're not just
5801 // discarding the extension we can't simply shrink the load. Bail.
5802 // TODO: It would be possible to merge the extensions in some cases.
5803 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5804 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5807 EVT PtrType = N0.getOperand(1).getValueType();
5809 if (PtrType == MVT::Untyped || PtrType.isExtended())
5810 // It's not possible to generate a constant of extended or untyped type.
5813 // For big endian targets, we need to adjust the offset to the pointer to
5814 // load the correct bytes.
5815 if (TLI.isBigEndian()) {
5816 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5817 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5818 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5821 uint64_t PtrOff = ShAmt / 8;
5822 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5823 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5824 PtrType, LN0->getBasePtr(),
5825 DAG.getConstant(PtrOff, PtrType));
5826 AddToWorklist(NewPtr.getNode());
5829 if (ExtType == ISD::NON_EXTLOAD)
5830 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5831 LN0->getPointerInfo().getWithOffset(PtrOff),
5832 LN0->isVolatile(), LN0->isNonTemporal(),
5833 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5835 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5836 LN0->getPointerInfo().getWithOffset(PtrOff),
5837 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5838 NewAlign, LN0->getAAInfo());
5840 // Replace the old load's chain with the new load's chain.
5841 WorklistRemover DeadNodes(*this);
5842 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5844 // Shift the result left, if we've swallowed a left shift.
5845 SDValue Result = Load;
5846 if (ShLeftAmt != 0) {
5847 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5848 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5850 // If the shift amount is as large as the result size (but, presumably,
5851 // no larger than the source) then the useful bits of the result are
5852 // zero; we can't simply return the shortened shift, because the result
5853 // of that operation is undefined.
5854 if (ShLeftAmt >= VT.getSizeInBits())
5855 Result = DAG.getConstant(0, VT);
5857 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5858 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5861 // Return the new loaded value.
5865 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5866 SDValue N0 = N->getOperand(0);
5867 SDValue N1 = N->getOperand(1);
5868 EVT VT = N->getValueType(0);
5869 EVT EVT = cast<VTSDNode>(N1)->getVT();
5870 unsigned VTBits = VT.getScalarType().getSizeInBits();
5871 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5873 // fold (sext_in_reg c1) -> c1
5874 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5875 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5877 // If the input is already sign extended, just drop the extension.
5878 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5881 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5882 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5883 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5884 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5885 N0.getOperand(0), N1);
5887 // fold (sext_in_reg (sext x)) -> (sext x)
5888 // fold (sext_in_reg (aext x)) -> (sext x)
5889 // if x is small enough.
5890 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5891 SDValue N00 = N0.getOperand(0);
5892 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5893 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5894 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5897 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5898 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5899 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5901 // fold operands of sext_in_reg based on knowledge that the top bits are not
5903 if (SimplifyDemandedBits(SDValue(N, 0)))
5904 return SDValue(N, 0);
5906 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5907 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5908 SDValue NarrowLoad = ReduceLoadWidth(N);
5909 if (NarrowLoad.getNode())
5912 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5913 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5914 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5915 if (N0.getOpcode() == ISD::SRL) {
5916 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5917 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5918 // We can turn this into an SRA iff the input to the SRL is already sign
5920 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5921 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5922 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5923 N0.getOperand(0), N0.getOperand(1));
5927 // fold (sext_inreg (extload x)) -> (sextload x)
5928 if (ISD::isEXTLoad(N0.getNode()) &&
5929 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5930 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5931 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5932 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5933 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5934 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5936 LN0->getBasePtr(), EVT,
5937 LN0->getMemOperand());
5938 CombineTo(N, ExtLoad);
5939 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5940 AddToWorklist(ExtLoad.getNode());
5941 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5943 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5944 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5946 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5947 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5948 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5949 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5950 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5952 LN0->getBasePtr(), EVT,
5953 LN0->getMemOperand());
5954 CombineTo(N, ExtLoad);
5955 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5956 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5959 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5960 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5961 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5962 N0.getOperand(1), false);
5963 if (BSwap.getNode())
5964 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5968 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5969 // into a build_vector.
5970 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5971 SmallVector<SDValue, 8> Elts;
5972 unsigned NumElts = N0->getNumOperands();
5973 unsigned ShAmt = VTBits - EVTBits;
5975 for (unsigned i = 0; i != NumElts; ++i) {
5976 SDValue Op = N0->getOperand(i);
5977 if (Op->getOpcode() == ISD::UNDEF) {
5982 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5983 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5984 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5985 Op.getValueType()));
5988 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5994 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5995 SDValue N0 = N->getOperand(0);
5996 EVT VT = N->getValueType(0);
5997 bool isLE = TLI.isLittleEndian();
6000 if (N0.getValueType() == N->getValueType(0))
6002 // fold (truncate c1) -> c1
6003 if (isa<ConstantSDNode>(N0))
6004 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6005 // fold (truncate (truncate x)) -> (truncate x)
6006 if (N0.getOpcode() == ISD::TRUNCATE)
6007 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6008 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6009 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6010 N0.getOpcode() == ISD::SIGN_EXTEND ||
6011 N0.getOpcode() == ISD::ANY_EXTEND) {
6012 if (N0.getOperand(0).getValueType().bitsLT(VT))
6013 // if the source is smaller than the dest, we still need an extend
6014 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6016 if (N0.getOperand(0).getValueType().bitsGT(VT))
6017 // if the source is larger than the dest, than we just need the truncate
6018 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6019 // if the source and dest are the same type, we can drop both the extend
6020 // and the truncate.
6021 return N0.getOperand(0);
6024 // Fold extract-and-trunc into a narrow extract. For example:
6025 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6026 // i32 y = TRUNCATE(i64 x)
6028 // v16i8 b = BITCAST (v2i64 val)
6029 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6031 // Note: We only run this optimization after type legalization (which often
6032 // creates this pattern) and before operation legalization after which
6033 // we need to be more careful about the vector instructions that we generate.
6034 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6035 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6037 EVT VecTy = N0.getOperand(0).getValueType();
6038 EVT ExTy = N0.getValueType();
6039 EVT TrTy = N->getValueType(0);
6041 unsigned NumElem = VecTy.getVectorNumElements();
6042 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6044 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6045 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6047 SDValue EltNo = N0->getOperand(1);
6048 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6049 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6050 EVT IndexTy = TLI.getVectorIdxTy();
6051 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6053 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6054 NVT, N0.getOperand(0));
6056 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6058 DAG.getConstant(Index, IndexTy));
6062 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6063 if (N0.getOpcode() == ISD::SELECT) {
6064 EVT SrcVT = N0.getValueType();
6065 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6066 TLI.isTruncateFree(SrcVT, VT)) {
6068 SDValue Cond = N0.getOperand(0);
6069 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6070 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6071 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6075 // Fold a series of buildvector, bitcast, and truncate if possible.
6077 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6078 // (2xi32 (buildvector x, y)).
6079 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6080 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6081 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6082 N0.getOperand(0).hasOneUse()) {
6084 SDValue BuildVect = N0.getOperand(0);
6085 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6086 EVT TruncVecEltTy = VT.getVectorElementType();
6088 // Check that the element types match.
6089 if (BuildVectEltTy == TruncVecEltTy) {
6090 // Now we only need to compute the offset of the truncated elements.
6091 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6092 unsigned TruncVecNumElts = VT.getVectorNumElements();
6093 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6095 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6096 "Invalid number of elements");
6098 SmallVector<SDValue, 8> Opnds;
6099 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6100 Opnds.push_back(BuildVect.getOperand(i));
6102 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6106 // See if we can simplify the input to this truncate through knowledge that
6107 // only the low bits are being used.
6108 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6109 // Currently we only perform this optimization on scalars because vectors
6110 // may have different active low bits.
6111 if (!VT.isVector()) {
6113 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6114 VT.getSizeInBits()));
6115 if (Shorter.getNode())
6116 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6118 // fold (truncate (load x)) -> (smaller load x)
6119 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6120 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6121 SDValue Reduced = ReduceLoadWidth(N);
6122 if (Reduced.getNode())
6124 // Handle the case where the load remains an extending load even
6125 // after truncation.
6126 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6127 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6128 if (!LN0->isVolatile() &&
6129 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6130 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6131 VT, LN0->getChain(), LN0->getBasePtr(),
6133 LN0->getMemOperand());
6134 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6139 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6140 // where ... are all 'undef'.
6141 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6142 SmallVector<EVT, 8> VTs;
6145 unsigned NumDefs = 0;
6147 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6148 SDValue X = N0.getOperand(i);
6149 if (X.getOpcode() != ISD::UNDEF) {
6154 // Stop if more than one members are non-undef.
6157 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6158 VT.getVectorElementType(),
6159 X.getValueType().getVectorNumElements()));
6163 return DAG.getUNDEF(VT);
6166 assert(V.getNode() && "The single defined operand is empty!");
6167 SmallVector<SDValue, 8> Opnds;
6168 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6170 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6173 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6174 AddToWorklist(NV.getNode());
6175 Opnds.push_back(NV);
6177 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6181 // Simplify the operands using demanded-bits information.
6182 if (!VT.isVector() &&
6183 SimplifyDemandedBits(SDValue(N, 0)))
6184 return SDValue(N, 0);
6189 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6190 SDValue Elt = N->getOperand(i);
6191 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6192 return Elt.getNode();
6193 return Elt.getOperand(Elt.getResNo()).getNode();
6196 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6197 /// if load locations are consecutive.
6198 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6199 assert(N->getOpcode() == ISD::BUILD_PAIR);
6201 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6202 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6203 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6204 LD1->getAddressSpace() != LD2->getAddressSpace())
6206 EVT LD1VT = LD1->getValueType(0);
6208 if (ISD::isNON_EXTLoad(LD2) &&
6210 // If both are volatile this would reduce the number of volatile loads.
6211 // If one is volatile it might be ok, but play conservative and bail out.
6212 !LD1->isVolatile() &&
6213 !LD2->isVolatile() &&
6214 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6215 unsigned Align = LD1->getAlignment();
6216 unsigned NewAlign = TLI.getDataLayout()->
6217 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6219 if (NewAlign <= Align &&
6220 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6221 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6222 LD1->getBasePtr(), LD1->getPointerInfo(),
6223 false, false, false, Align);
6229 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6230 SDValue N0 = N->getOperand(0);
6231 EVT VT = N->getValueType(0);
6233 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6234 // Only do this before legalize, since afterward the target may be depending
6235 // on the bitconvert.
6236 // First check to see if this is all constant.
6238 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6240 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6242 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6243 assert(!DestEltVT.isVector() &&
6244 "Element type of vector ValueType must not be vector!");
6246 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6249 // If the input is a constant, let getNode fold it.
6250 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6251 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6252 if (Res.getNode() != N) {
6253 if (!LegalOperations ||
6254 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6257 // Folding it resulted in an illegal node, and it's too late to
6258 // do that. Clean up the old node and forego the transformation.
6259 // Ideally this won't happen very often, because instcombine
6260 // and the earlier dagcombine runs (where illegal nodes are
6261 // permitted) should have folded most of them already.
6262 DAG.DeleteNode(Res.getNode());
6266 // (conv (conv x, t1), t2) -> (conv x, t2)
6267 if (N0.getOpcode() == ISD::BITCAST)
6268 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6271 // fold (conv (load x)) -> (load (conv*)x)
6272 // If the resultant load doesn't need a higher alignment than the original!
6273 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6274 // Do not change the width of a volatile load.
6275 !cast<LoadSDNode>(N0)->isVolatile() &&
6276 // Do not remove the cast if the types differ in endian layout.
6277 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6278 TLI.hasBigEndianPartOrdering(VT) &&
6279 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6280 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6281 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6282 unsigned Align = TLI.getDataLayout()->
6283 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6284 unsigned OrigAlign = LN0->getAlignment();
6286 if (Align <= OrigAlign) {
6287 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6288 LN0->getBasePtr(), LN0->getPointerInfo(),
6289 LN0->isVolatile(), LN0->isNonTemporal(),
6290 LN0->isInvariant(), OrigAlign,
6293 CombineTo(N0.getNode(),
6294 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6295 N0.getValueType(), Load),
6301 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6302 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6303 // This often reduces constant pool loads.
6304 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6305 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6306 N0.getNode()->hasOneUse() && VT.isInteger() &&
6307 !VT.isVector() && !N0.getValueType().isVector()) {
6308 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6310 AddToWorklist(NewConv.getNode());
6312 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6313 if (N0.getOpcode() == ISD::FNEG)
6314 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6315 NewConv, DAG.getConstant(SignBit, VT));
6316 assert(N0.getOpcode() == ISD::FABS);
6317 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6318 NewConv, DAG.getConstant(~SignBit, VT));
6321 // fold (bitconvert (fcopysign cst, x)) ->
6322 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6323 // Note that we don't handle (copysign x, cst) because this can always be
6324 // folded to an fneg or fabs.
6325 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6326 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6327 VT.isInteger() && !VT.isVector()) {
6328 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6329 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6330 if (isTypeLegal(IntXVT)) {
6331 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6332 IntXVT, N0.getOperand(1));
6333 AddToWorklist(X.getNode());
6335 // If X has a different width than the result/lhs, sext it or truncate it.
6336 unsigned VTWidth = VT.getSizeInBits();
6337 if (OrigXWidth < VTWidth) {
6338 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6339 AddToWorklist(X.getNode());
6340 } else if (OrigXWidth > VTWidth) {
6341 // To get the sign bit in the right place, we have to shift it right
6342 // before truncating.
6343 X = DAG.getNode(ISD::SRL, SDLoc(X),
6344 X.getValueType(), X,
6345 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6346 AddToWorklist(X.getNode());
6347 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6348 AddToWorklist(X.getNode());
6351 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6352 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6353 X, DAG.getConstant(SignBit, VT));
6354 AddToWorklist(X.getNode());
6356 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6357 VT, N0.getOperand(0));
6358 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6359 Cst, DAG.getConstant(~SignBit, VT));
6360 AddToWorklist(Cst.getNode());
6362 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6366 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6367 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6368 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6369 if (CombineLD.getNode())
6376 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6377 EVT VT = N->getValueType(0);
6378 return CombineConsecutiveLoads(N, VT);
6381 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6382 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6383 /// destination element value type.
6384 SDValue DAGCombiner::
6385 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6386 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6388 // If this is already the right type, we're done.
6389 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6391 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6392 unsigned DstBitSize = DstEltVT.getSizeInBits();
6394 // If this is a conversion of N elements of one type to N elements of another
6395 // type, convert each element. This handles FP<->INT cases.
6396 if (SrcBitSize == DstBitSize) {
6397 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6398 BV->getValueType(0).getVectorNumElements());
6400 // Due to the FP element handling below calling this routine recursively,
6401 // we can end up with a scalar-to-vector node here.
6402 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6403 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6404 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6405 DstEltVT, BV->getOperand(0)));
6407 SmallVector<SDValue, 8> Ops;
6408 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6409 SDValue Op = BV->getOperand(i);
6410 // If the vector element type is not legal, the BUILD_VECTOR operands
6411 // are promoted and implicitly truncated. Make that explicit here.
6412 if (Op.getValueType() != SrcEltVT)
6413 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6414 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6416 AddToWorklist(Ops.back().getNode());
6418 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6421 // Otherwise, we're growing or shrinking the elements. To avoid having to
6422 // handle annoying details of growing/shrinking FP values, we convert them to
6424 if (SrcEltVT.isFloatingPoint()) {
6425 // Convert the input float vector to a int vector where the elements are the
6427 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6428 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6429 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6433 // Now we know the input is an integer vector. If the output is a FP type,
6434 // convert to integer first, then to FP of the right size.
6435 if (DstEltVT.isFloatingPoint()) {
6436 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6437 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6438 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6440 // Next, convert to FP elements of the same size.
6441 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6444 // Okay, we know the src/dst types are both integers of differing types.
6445 // Handling growing first.
6446 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6447 if (SrcBitSize < DstBitSize) {
6448 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6450 SmallVector<SDValue, 8> Ops;
6451 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6452 i += NumInputsPerOutput) {
6453 bool isLE = TLI.isLittleEndian();
6454 APInt NewBits = APInt(DstBitSize, 0);
6455 bool EltIsUndef = true;
6456 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6457 // Shift the previously computed bits over.
6458 NewBits <<= SrcBitSize;
6459 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6460 if (Op.getOpcode() == ISD::UNDEF) continue;
6463 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6464 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6468 Ops.push_back(DAG.getUNDEF(DstEltVT));
6470 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6473 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6474 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6477 // Finally, this must be the case where we are shrinking elements: each input
6478 // turns into multiple outputs.
6479 bool isS2V = ISD::isScalarToVector(BV);
6480 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6481 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6482 NumOutputsPerInput*BV->getNumOperands());
6483 SmallVector<SDValue, 8> Ops;
6485 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6486 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6487 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6488 Ops.push_back(DAG.getUNDEF(DstEltVT));
6492 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6493 getAPIntValue().zextOrTrunc(SrcBitSize);
6495 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6496 APInt ThisVal = OpVal.trunc(DstBitSize);
6497 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6498 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6499 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6500 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6502 OpVal = OpVal.lshr(DstBitSize);
6505 // For big endian targets, swap the order of the pieces of each element.
6506 if (TLI.isBigEndian())
6507 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6510 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6513 SDValue DAGCombiner::visitFADD(SDNode *N) {
6514 SDValue N0 = N->getOperand(0);
6515 SDValue N1 = N->getOperand(1);
6516 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6517 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6518 EVT VT = N->getValueType(0);
6521 if (VT.isVector()) {
6522 SDValue FoldedVOp = SimplifyVBinOp(N);
6523 if (FoldedVOp.getNode()) return FoldedVOp;
6526 // fold (fadd c1, c2) -> c1 + c2
6528 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6529 // canonicalize constant to RHS
6530 if (N0CFP && !N1CFP)
6531 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6532 // fold (fadd A, 0) -> A
6533 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6534 N1CFP->getValueAPF().isZero())
6536 // fold (fadd A, (fneg B)) -> (fsub A, B)
6537 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6538 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6539 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6540 GetNegatedExpression(N1, DAG, LegalOperations));
6541 // fold (fadd (fneg A), B) -> (fsub B, A)
6542 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6543 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6544 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6545 GetNegatedExpression(N0, DAG, LegalOperations));
6547 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6548 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6549 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6550 isa<ConstantFPSDNode>(N0.getOperand(1)))
6551 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6552 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6553 N0.getOperand(1), N1));
6555 // No FP constant should be created after legalization as Instruction
6556 // Selection pass has hard time in dealing with FP constant.
6558 // We don't need test this condition for transformation like following, as
6559 // the DAG being transformed implies it is legal to take FP constant as
6562 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6564 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6566 // If allow, fold (fadd (fneg x), x) -> 0.0
6567 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6568 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6569 return DAG.getConstantFP(0.0, VT);
6571 // If allow, fold (fadd x, (fneg x)) -> 0.0
6572 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6573 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6574 return DAG.getConstantFP(0.0, VT);
6576 // In unsafe math mode, we can fold chains of FADD's of the same value
6577 // into multiplications. This transform is not safe in general because
6578 // we are reducing the number of rounding steps.
6579 if (DAG.getTarget().Options.UnsafeFPMath &&
6580 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6582 if (N0.getOpcode() == ISD::FMUL) {
6583 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6584 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6586 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6587 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6588 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6590 DAG.getConstantFP(1.0, VT));
6591 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6595 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6596 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6597 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6599 DAG.getConstantFP(1.0, VT));
6600 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6604 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6605 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6606 N1.getOperand(0) == N1.getOperand(1) &&
6607 N0.getOperand(1) == N1.getOperand(0)) {
6608 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6610 DAG.getConstantFP(2.0, VT));
6611 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6612 N0.getOperand(1), NewCFP);
6615 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6616 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6617 N1.getOperand(0) == N1.getOperand(1) &&
6618 N0.getOperand(0) == N1.getOperand(0)) {
6619 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6621 DAG.getConstantFP(2.0, VT));
6622 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6623 N0.getOperand(0), NewCFP);
6627 if (N1.getOpcode() == ISD::FMUL) {
6628 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6629 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6631 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6632 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6633 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6635 DAG.getConstantFP(1.0, VT));
6636 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6640 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6641 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6642 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6644 DAG.getConstantFP(1.0, VT));
6645 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6650 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6651 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6652 N0.getOperand(0) == N0.getOperand(1) &&
6653 N1.getOperand(1) == N0.getOperand(0)) {
6654 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6656 DAG.getConstantFP(2.0, VT));
6657 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6658 N1.getOperand(1), NewCFP);
6661 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6662 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6663 N0.getOperand(0) == N0.getOperand(1) &&
6664 N1.getOperand(0) == N0.getOperand(0)) {
6665 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6667 DAG.getConstantFP(2.0, VT));
6668 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6669 N1.getOperand(0), NewCFP);
6673 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6674 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6675 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6676 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6677 (N0.getOperand(0) == N1))
6678 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6679 N1, DAG.getConstantFP(3.0, VT));
6682 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6683 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6684 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6685 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6686 N1.getOperand(0) == N0)
6687 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6688 N0, DAG.getConstantFP(3.0, VT));
6691 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6692 if (AllowNewFpConst &&
6693 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6694 N0.getOperand(0) == N0.getOperand(1) &&
6695 N1.getOperand(0) == N1.getOperand(1) &&
6696 N0.getOperand(0) == N1.getOperand(0))
6697 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6699 DAG.getConstantFP(4.0, VT));
6702 // FADD -> FMA combines:
6703 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6704 DAG.getTarget().Options.UnsafeFPMath) &&
6705 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6706 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6708 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6709 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6710 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6711 N0.getOperand(0), N0.getOperand(1), N1);
6713 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6714 // Note: Commutes FADD operands.
6715 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6716 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6717 N1.getOperand(0), N1.getOperand(1), N0);
6723 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6724 SDValue N0 = N->getOperand(0);
6725 SDValue N1 = N->getOperand(1);
6726 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6727 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6728 EVT VT = N->getValueType(0);
6732 if (VT.isVector()) {
6733 SDValue FoldedVOp = SimplifyVBinOp(N);
6734 if (FoldedVOp.getNode()) return FoldedVOp;
6737 // fold (fsub c1, c2) -> c1-c2
6739 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6740 // fold (fsub A, 0) -> A
6741 if (DAG.getTarget().Options.UnsafeFPMath &&
6742 N1CFP && N1CFP->getValueAPF().isZero())
6744 // fold (fsub 0, B) -> -B
6745 if (DAG.getTarget().Options.UnsafeFPMath &&
6746 N0CFP && N0CFP->getValueAPF().isZero()) {
6747 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6748 return GetNegatedExpression(N1, DAG, LegalOperations);
6749 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6750 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6752 // fold (fsub A, (fneg B)) -> (fadd A, B)
6753 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6754 return DAG.getNode(ISD::FADD, dl, VT, N0,
6755 GetNegatedExpression(N1, DAG, LegalOperations));
6757 // If 'unsafe math' is enabled, fold
6758 // (fsub x, x) -> 0.0 &
6759 // (fsub x, (fadd x, y)) -> (fneg y) &
6760 // (fsub x, (fadd y, x)) -> (fneg y)
6761 if (DAG.getTarget().Options.UnsafeFPMath) {
6763 return DAG.getConstantFP(0.0f, VT);
6765 if (N1.getOpcode() == ISD::FADD) {
6766 SDValue N10 = N1->getOperand(0);
6767 SDValue N11 = N1->getOperand(1);
6769 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6770 &DAG.getTarget().Options))
6771 return GetNegatedExpression(N11, DAG, LegalOperations);
6773 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6774 &DAG.getTarget().Options))
6775 return GetNegatedExpression(N10, DAG, LegalOperations);
6779 // FSUB -> FMA combines:
6780 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6781 DAG.getTarget().Options.UnsafeFPMath) &&
6782 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6783 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6785 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6786 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6787 return DAG.getNode(ISD::FMA, dl, VT,
6788 N0.getOperand(0), N0.getOperand(1),
6789 DAG.getNode(ISD::FNEG, dl, VT, N1));
6791 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6792 // Note: Commutes FSUB operands.
6793 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6794 return DAG.getNode(ISD::FMA, dl, VT,
6795 DAG.getNode(ISD::FNEG, dl, VT,
6797 N1.getOperand(1), N0);
6799 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6800 if (N0.getOpcode() == ISD::FNEG &&
6801 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6802 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6803 SDValue N00 = N0.getOperand(0).getOperand(0);
6804 SDValue N01 = N0.getOperand(0).getOperand(1);
6805 return DAG.getNode(ISD::FMA, dl, VT,
6806 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6807 DAG.getNode(ISD::FNEG, dl, VT, N1));
6814 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6815 SDValue N0 = N->getOperand(0);
6816 SDValue N1 = N->getOperand(1);
6817 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6818 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6819 EVT VT = N->getValueType(0);
6820 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6823 if (VT.isVector()) {
6824 SDValue FoldedVOp = SimplifyVBinOp(N);
6825 if (FoldedVOp.getNode()) return FoldedVOp;
6828 // fold (fmul c1, c2) -> c1*c2
6830 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6831 // canonicalize constant to RHS
6832 if (N0CFP && !N1CFP)
6833 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6834 // fold (fmul A, 0) -> 0
6835 if (DAG.getTarget().Options.UnsafeFPMath &&
6836 N1CFP && N1CFP->getValueAPF().isZero())
6838 // fold (fmul A, 0) -> 0, vector edition.
6839 if (DAG.getTarget().Options.UnsafeFPMath &&
6840 ISD::isBuildVectorAllZeros(N1.getNode()))
6842 // fold (fmul A, 1.0) -> A
6843 if (N1CFP && N1CFP->isExactlyValue(1.0))
6845 // fold (fmul X, 2.0) -> (fadd X, X)
6846 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6847 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6848 // fold (fmul X, -1.0) -> (fneg X)
6849 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6850 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6851 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6853 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6854 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6855 &DAG.getTarget().Options)) {
6856 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6857 &DAG.getTarget().Options)) {
6858 // Both can be negated for free, check to see if at least one is cheaper
6860 if (LHSNeg == 2 || RHSNeg == 2)
6861 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6862 GetNegatedExpression(N0, DAG, LegalOperations),
6863 GetNegatedExpression(N1, DAG, LegalOperations));
6867 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6868 if (DAG.getTarget().Options.UnsafeFPMath &&
6869 N1CFP && N0.getOpcode() == ISD::FMUL &&
6870 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6871 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6872 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6873 N0.getOperand(1), N1));
6878 SDValue DAGCombiner::visitFMA(SDNode *N) {
6879 SDValue N0 = N->getOperand(0);
6880 SDValue N1 = N->getOperand(1);
6881 SDValue N2 = N->getOperand(2);
6882 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6883 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6884 EVT VT = N->getValueType(0);
6887 if (DAG.getTarget().Options.UnsafeFPMath) {
6888 if (N0CFP && N0CFP->isZero())
6890 if (N1CFP && N1CFP->isZero())
6893 if (N0CFP && N0CFP->isExactlyValue(1.0))
6894 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6895 if (N1CFP && N1CFP->isExactlyValue(1.0))
6896 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6898 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6899 if (N0CFP && !N1CFP)
6900 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6902 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6903 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6904 N2.getOpcode() == ISD::FMUL &&
6905 N0 == N2.getOperand(0) &&
6906 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6907 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6908 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6912 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6913 if (DAG.getTarget().Options.UnsafeFPMath &&
6914 N0.getOpcode() == ISD::FMUL && N1CFP &&
6915 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6916 return DAG.getNode(ISD::FMA, dl, VT,
6918 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6922 // (fma x, 1, y) -> (fadd x, y)
6923 // (fma x, -1, y) -> (fadd (fneg x), y)
6925 if (N1CFP->isExactlyValue(1.0))
6926 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6928 if (N1CFP->isExactlyValue(-1.0) &&
6929 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6930 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6931 AddToWorklist(RHSNeg.getNode());
6932 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6936 // (fma x, c, x) -> (fmul x, (c+1))
6937 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6938 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6939 DAG.getNode(ISD::FADD, dl, VT,
6940 N1, DAG.getConstantFP(1.0, VT)));
6942 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6943 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6944 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6945 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6946 DAG.getNode(ISD::FADD, dl, VT,
6947 N1, DAG.getConstantFP(-1.0, VT)));
6953 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6954 SDValue N0 = N->getOperand(0);
6955 SDValue N1 = N->getOperand(1);
6956 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6957 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6958 EVT VT = N->getValueType(0);
6959 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6962 if (VT.isVector()) {
6963 SDValue FoldedVOp = SimplifyVBinOp(N);
6964 if (FoldedVOp.getNode()) return FoldedVOp;
6967 // fold (fdiv c1, c2) -> c1/c2
6969 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6971 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6972 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6973 // Compute the reciprocal 1.0 / c2.
6974 APFloat N1APF = N1CFP->getValueAPF();
6975 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6976 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6977 // Only do the transform if the reciprocal is a legal fp immediate that
6978 // isn't too nasty (eg NaN, denormal, ...).
6979 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6980 (!LegalOperations ||
6981 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6982 // backend)... we should handle this gracefully after Legalize.
6983 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6984 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6985 TLI.isFPImmLegal(Recip, VT)))
6986 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6987 DAG.getConstantFP(Recip, VT));
6990 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6991 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6992 &DAG.getTarget().Options)) {
6993 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6994 &DAG.getTarget().Options)) {
6995 // Both can be negated for free, check to see if at least one is cheaper
6997 if (LHSNeg == 2 || RHSNeg == 2)
6998 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6999 GetNegatedExpression(N0, DAG, LegalOperations),
7000 GetNegatedExpression(N1, DAG, LegalOperations));
7007 SDValue DAGCombiner::visitFREM(SDNode *N) {
7008 SDValue N0 = N->getOperand(0);
7009 SDValue N1 = N->getOperand(1);
7010 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7011 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7012 EVT VT = N->getValueType(0);
7014 // fold (frem c1, c2) -> fmod(c1,c2)
7016 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7021 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7022 SDValue N0 = N->getOperand(0);
7023 SDValue N1 = N->getOperand(1);
7024 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7025 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7026 EVT VT = N->getValueType(0);
7028 if (N0CFP && N1CFP) // Constant fold
7029 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7032 const APFloat& V = N1CFP->getValueAPF();
7033 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7034 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7035 if (!V.isNegative()) {
7036 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7037 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7039 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7040 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7041 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7045 // copysign(fabs(x), y) -> copysign(x, y)
7046 // copysign(fneg(x), y) -> copysign(x, y)
7047 // copysign(copysign(x,z), y) -> copysign(x, y)
7048 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7049 N0.getOpcode() == ISD::FCOPYSIGN)
7050 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7051 N0.getOperand(0), N1);
7053 // copysign(x, abs(y)) -> abs(x)
7054 if (N1.getOpcode() == ISD::FABS)
7055 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7057 // copysign(x, copysign(y,z)) -> copysign(x, z)
7058 if (N1.getOpcode() == ISD::FCOPYSIGN)
7059 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7060 N0, N1.getOperand(1));
7062 // copysign(x, fp_extend(y)) -> copysign(x, y)
7063 // copysign(x, fp_round(y)) -> copysign(x, y)
7064 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7065 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7066 N0, N1.getOperand(0));
7071 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7072 SDValue N0 = N->getOperand(0);
7073 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7074 EVT VT = N->getValueType(0);
7075 EVT OpVT = N0.getValueType();
7077 // fold (sint_to_fp c1) -> c1fp
7079 // ...but only if the target supports immediate floating-point values
7080 (!LegalOperations ||
7081 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7082 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7084 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7085 // but UINT_TO_FP is legal on this target, try to convert.
7086 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7087 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7088 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7089 if (DAG.SignBitIsZero(N0))
7090 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7093 // The next optimizations are desirable only if SELECT_CC can be lowered.
7094 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7095 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7096 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7098 (!LegalOperations ||
7099 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7101 { N0.getOperand(0), N0.getOperand(1),
7102 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7104 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7107 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7108 // (select_cc x, y, 1.0, 0.0,, cc)
7109 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7110 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7111 (!LegalOperations ||
7112 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7114 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7115 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7116 N0.getOperand(0).getOperand(2) };
7117 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7124 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7125 SDValue N0 = N->getOperand(0);
7126 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7127 EVT VT = N->getValueType(0);
7128 EVT OpVT = N0.getValueType();
7130 // fold (uint_to_fp c1) -> c1fp
7132 // ...but only if the target supports immediate floating-point values
7133 (!LegalOperations ||
7134 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7135 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7137 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7138 // but SINT_TO_FP is legal on this target, try to convert.
7139 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7140 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7141 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7142 if (DAG.SignBitIsZero(N0))
7143 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7146 // The next optimizations are desirable only if SELECT_CC can be lowered.
7147 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7148 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7150 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7151 (!LegalOperations ||
7152 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7154 { N0.getOperand(0), N0.getOperand(1),
7155 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7157 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7164 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7165 SDValue N0 = N->getOperand(0);
7166 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7167 EVT VT = N->getValueType(0);
7169 // fold (fp_to_sint c1fp) -> c1
7171 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7176 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7177 SDValue N0 = N->getOperand(0);
7178 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7179 EVT VT = N->getValueType(0);
7181 // fold (fp_to_uint c1fp) -> c1
7183 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7188 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7189 SDValue N0 = N->getOperand(0);
7190 SDValue N1 = N->getOperand(1);
7191 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7192 EVT VT = N->getValueType(0);
7194 // fold (fp_round c1fp) -> c1fp
7196 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7198 // fold (fp_round (fp_extend x)) -> x
7199 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7200 return N0.getOperand(0);
7202 // fold (fp_round (fp_round x)) -> (fp_round x)
7203 if (N0.getOpcode() == ISD::FP_ROUND) {
7204 // This is a value preserving truncation if both round's are.
7205 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7206 N0.getNode()->getConstantOperandVal(1) == 1;
7207 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7208 DAG.getIntPtrConstant(IsTrunc));
7211 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7212 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7213 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7214 N0.getOperand(0), N1);
7215 AddToWorklist(Tmp.getNode());
7216 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7217 Tmp, N0.getOperand(1));
7223 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7224 SDValue N0 = N->getOperand(0);
7225 EVT VT = N->getValueType(0);
7226 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7227 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7229 // fold (fp_round_inreg c1fp) -> c1fp
7230 if (N0CFP && isTypeLegal(EVT)) {
7231 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7232 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7238 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7239 SDValue N0 = N->getOperand(0);
7240 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7241 EVT VT = N->getValueType(0);
7243 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7244 if (N->hasOneUse() &&
7245 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7248 // fold (fp_extend c1fp) -> c1fp
7250 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7252 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7254 if (N0.getOpcode() == ISD::FP_ROUND
7255 && N0.getNode()->getConstantOperandVal(1) == 1) {
7256 SDValue In = N0.getOperand(0);
7257 if (In.getValueType() == VT) return In;
7258 if (VT.bitsLT(In.getValueType()))
7259 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7260 In, N0.getOperand(1));
7261 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7264 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7265 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7266 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7267 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7268 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7270 LN0->getBasePtr(), N0.getValueType(),
7271 LN0->getMemOperand());
7272 CombineTo(N, ExtLoad);
7273 CombineTo(N0.getNode(),
7274 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7275 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7276 ExtLoad.getValue(1));
7277 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7283 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7284 SDValue N0 = N->getOperand(0);
7285 EVT VT = N->getValueType(0);
7287 if (VT.isVector()) {
7288 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7289 if (FoldedVOp.getNode()) return FoldedVOp;
7292 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7293 &DAG.getTarget().Options))
7294 return GetNegatedExpression(N0, DAG, LegalOperations);
7296 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7297 // constant pool values.
7298 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7300 N0.getNode()->hasOneUse() &&
7301 N0.getOperand(0).getValueType().isInteger()) {
7302 SDValue Int = N0.getOperand(0);
7303 EVT IntVT = Int.getValueType();
7304 if (IntVT.isInteger() && !IntVT.isVector()) {
7305 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7306 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7307 AddToWorklist(Int.getNode());
7308 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7313 // (fneg (fmul c, x)) -> (fmul -c, x)
7314 if (N0.getOpcode() == ISD::FMUL) {
7315 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7317 APFloat CVal = CFP1->getValueAPF();
7319 if (Level >= AfterLegalizeDAG &&
7320 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7321 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7323 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7324 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7331 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7332 SDValue N0 = N->getOperand(0);
7333 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7334 EVT VT = N->getValueType(0);
7336 // fold (fceil c1) -> fceil(c1)
7338 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7343 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7344 SDValue N0 = N->getOperand(0);
7345 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7346 EVT VT = N->getValueType(0);
7348 // fold (ftrunc c1) -> ftrunc(c1)
7350 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7355 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7356 SDValue N0 = N->getOperand(0);
7357 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7358 EVT VT = N->getValueType(0);
7360 // fold (ffloor c1) -> ffloor(c1)
7362 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7367 SDValue DAGCombiner::visitFABS(SDNode *N) {
7368 SDValue N0 = N->getOperand(0);
7369 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7370 EVT VT = N->getValueType(0);
7372 if (VT.isVector()) {
7373 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7374 if (FoldedVOp.getNode()) return FoldedVOp;
7377 // fold (fabs c1) -> fabs(c1)
7379 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7380 // fold (fabs (fabs x)) -> (fabs x)
7381 if (N0.getOpcode() == ISD::FABS)
7382 return N->getOperand(0);
7383 // fold (fabs (fneg x)) -> (fabs x)
7384 // fold (fabs (fcopysign x, y)) -> (fabs x)
7385 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7386 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7388 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7389 // constant pool values.
7390 if (!TLI.isFAbsFree(VT) &&
7391 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7392 N0.getOperand(0).getValueType().isInteger() &&
7393 !N0.getOperand(0).getValueType().isVector()) {
7394 SDValue Int = N0.getOperand(0);
7395 EVT IntVT = Int.getValueType();
7396 if (IntVT.isInteger() && !IntVT.isVector()) {
7397 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7398 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7399 AddToWorklist(Int.getNode());
7400 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7401 N->getValueType(0), Int);
7408 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7409 SDValue Chain = N->getOperand(0);
7410 SDValue N1 = N->getOperand(1);
7411 SDValue N2 = N->getOperand(2);
7413 // If N is a constant we could fold this into a fallthrough or unconditional
7414 // branch. However that doesn't happen very often in normal code, because
7415 // Instcombine/SimplifyCFG should have handled the available opportunities.
7416 // If we did this folding here, it would be necessary to update the
7417 // MachineBasicBlock CFG, which is awkward.
7419 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7421 if (N1.getOpcode() == ISD::SETCC &&
7422 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7423 N1.getOperand(0).getValueType())) {
7424 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7425 Chain, N1.getOperand(2),
7426 N1.getOperand(0), N1.getOperand(1), N2);
7429 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7430 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7431 (N1.getOperand(0).hasOneUse() &&
7432 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7433 SDNode *Trunc = nullptr;
7434 if (N1.getOpcode() == ISD::TRUNCATE) {
7435 // Look pass the truncate.
7436 Trunc = N1.getNode();
7437 N1 = N1.getOperand(0);
7440 // Match this pattern so that we can generate simpler code:
7443 // %b = and i32 %a, 2
7444 // %c = srl i32 %b, 1
7445 // brcond i32 %c ...
7450 // %b = and i32 %a, 2
7451 // %c = setcc eq %b, 0
7454 // This applies only when the AND constant value has one bit set and the
7455 // SRL constant is equal to the log2 of the AND constant. The back-end is
7456 // smart enough to convert the result into a TEST/JMP sequence.
7457 SDValue Op0 = N1.getOperand(0);
7458 SDValue Op1 = N1.getOperand(1);
7460 if (Op0.getOpcode() == ISD::AND &&
7461 Op1.getOpcode() == ISD::Constant) {
7462 SDValue AndOp1 = Op0.getOperand(1);
7464 if (AndOp1.getOpcode() == ISD::Constant) {
7465 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7467 if (AndConst.isPowerOf2() &&
7468 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7470 DAG.getSetCC(SDLoc(N),
7471 getSetCCResultType(Op0.getValueType()),
7472 Op0, DAG.getConstant(0, Op0.getValueType()),
7475 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7476 MVT::Other, Chain, SetCC, N2);
7477 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7478 // will convert it back to (X & C1) >> C2.
7479 CombineTo(N, NewBRCond, false);
7480 // Truncate is dead.
7482 removeFromWorklist(Trunc);
7483 DAG.DeleteNode(Trunc);
7485 // Replace the uses of SRL with SETCC
7486 WorklistRemover DeadNodes(*this);
7487 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7488 removeFromWorklist(N1.getNode());
7489 DAG.DeleteNode(N1.getNode());
7490 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7496 // Restore N1 if the above transformation doesn't match.
7497 N1 = N->getOperand(1);
7500 // Transform br(xor(x, y)) -> br(x != y)
7501 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7502 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7503 SDNode *TheXor = N1.getNode();
7504 SDValue Op0 = TheXor->getOperand(0);
7505 SDValue Op1 = TheXor->getOperand(1);
7506 if (Op0.getOpcode() == Op1.getOpcode()) {
7507 // Avoid missing important xor optimizations.
7508 SDValue Tmp = visitXOR(TheXor);
7509 if (Tmp.getNode()) {
7510 if (Tmp.getNode() != TheXor) {
7511 DEBUG(dbgs() << "\nReplacing.8 ";
7513 dbgs() << "\nWith: ";
7514 Tmp.getNode()->dump(&DAG);
7516 WorklistRemover DeadNodes(*this);
7517 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7518 removeFromWorklist(TheXor);
7519 DAG.DeleteNode(TheXor);
7520 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7521 MVT::Other, Chain, Tmp, N2);
7524 // visitXOR has changed XOR's operands or replaced the XOR completely,
7526 return SDValue(N, 0);
7530 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7532 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7533 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7534 Op0.getOpcode() == ISD::XOR) {
7535 TheXor = Op0.getNode();
7539 EVT SetCCVT = N1.getValueType();
7541 SetCCVT = getSetCCResultType(SetCCVT);
7542 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7545 Equal ? ISD::SETEQ : ISD::SETNE);
7546 // Replace the uses of XOR with SETCC
7547 WorklistRemover DeadNodes(*this);
7548 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7549 removeFromWorklist(N1.getNode());
7550 DAG.DeleteNode(N1.getNode());
7551 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7552 MVT::Other, Chain, SetCC, N2);
7559 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7561 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7562 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7563 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7565 // If N is a constant we could fold this into a fallthrough or unconditional
7566 // branch. However that doesn't happen very often in normal code, because
7567 // Instcombine/SimplifyCFG should have handled the available opportunities.
7568 // If we did this folding here, it would be necessary to update the
7569 // MachineBasicBlock CFG, which is awkward.
7571 // Use SimplifySetCC to simplify SETCC's.
7572 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7573 CondLHS, CondRHS, CC->get(), SDLoc(N),
7575 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7577 // fold to a simpler setcc
7578 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7579 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7580 N->getOperand(0), Simp.getOperand(2),
7581 Simp.getOperand(0), Simp.getOperand(1),
7587 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7588 /// uses N as its base pointer and that N may be folded in the load / store
7589 /// addressing mode.
7590 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7592 const TargetLowering &TLI) {
7594 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7595 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7597 VT = Use->getValueType(0);
7598 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7599 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7601 VT = ST->getValue().getValueType();
7605 TargetLowering::AddrMode AM;
7606 if (N->getOpcode() == ISD::ADD) {
7607 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7610 AM.BaseOffs = Offset->getSExtValue();
7614 } else if (N->getOpcode() == ISD::SUB) {
7615 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7618 AM.BaseOffs = -Offset->getSExtValue();
7625 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7628 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7629 /// pre-indexed load / store when the base pointer is an add or subtract
7630 /// and it has other uses besides the load / store. After the
7631 /// transformation, the new indexed load / store has effectively folded
7632 /// the add / subtract in and all of its other uses are redirected to the
7633 /// new load / store.
7634 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7635 if (Level < AfterLegalizeDAG)
7641 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7642 if (LD->isIndexed())
7644 VT = LD->getMemoryVT();
7645 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7646 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7648 Ptr = LD->getBasePtr();
7649 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7650 if (ST->isIndexed())
7652 VT = ST->getMemoryVT();
7653 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7654 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7656 Ptr = ST->getBasePtr();
7662 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7663 // out. There is no reason to make this a preinc/predec.
7664 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7665 Ptr.getNode()->hasOneUse())
7668 // Ask the target to do addressing mode selection.
7671 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7672 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7675 // Backends without true r+i pre-indexed forms may need to pass a
7676 // constant base with a variable offset so that constant coercion
7677 // will work with the patterns in canonical form.
7678 bool Swapped = false;
7679 if (isa<ConstantSDNode>(BasePtr)) {
7680 std::swap(BasePtr, Offset);
7684 // Don't create a indexed load / store with zero offset.
7685 if (isa<ConstantSDNode>(Offset) &&
7686 cast<ConstantSDNode>(Offset)->isNullValue())
7689 // Try turning it into a pre-indexed load / store except when:
7690 // 1) The new base ptr is a frame index.
7691 // 2) If N is a store and the new base ptr is either the same as or is a
7692 // predecessor of the value being stored.
7693 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7694 // that would create a cycle.
7695 // 4) All uses are load / store ops that use it as old base ptr.
7697 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7698 // (plus the implicit offset) to a register to preinc anyway.
7699 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7704 SDValue Val = cast<StoreSDNode>(N)->getValue();
7705 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7709 // If the offset is a constant, there may be other adds of constants that
7710 // can be folded with this one. We should do this to avoid having to keep
7711 // a copy of the original base pointer.
7712 SmallVector<SDNode *, 16> OtherUses;
7713 if (isa<ConstantSDNode>(Offset))
7714 for (SDNode *Use : BasePtr.getNode()->uses()) {
7715 if (Use == Ptr.getNode())
7718 if (Use->isPredecessorOf(N))
7721 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7726 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7727 if (Op1.getNode() == BasePtr.getNode())
7728 std::swap(Op0, Op1);
7729 assert(Op0.getNode() == BasePtr.getNode() &&
7730 "Use of ADD/SUB but not an operand");
7732 if (!isa<ConstantSDNode>(Op1)) {
7737 // FIXME: In some cases, we can be smarter about this.
7738 if (Op1.getValueType() != Offset.getValueType()) {
7743 OtherUses.push_back(Use);
7747 std::swap(BasePtr, Offset);
7749 // Now check for #3 and #4.
7750 bool RealUse = false;
7752 // Caches for hasPredecessorHelper
7753 SmallPtrSet<const SDNode *, 32> Visited;
7754 SmallVector<const SDNode *, 16> Worklist;
7756 for (SDNode *Use : Ptr.getNode()->uses()) {
7759 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7762 // If Ptr may be folded in addressing mode of other use, then it's
7763 // not profitable to do this transformation.
7764 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7773 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7774 BasePtr, Offset, AM);
7776 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7777 BasePtr, Offset, AM);
7780 DEBUG(dbgs() << "\nReplacing.4 ";
7782 dbgs() << "\nWith: ";
7783 Result.getNode()->dump(&DAG);
7785 WorklistRemover DeadNodes(*this);
7787 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7788 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7790 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7793 // Finally, since the node is now dead, remove it from the graph.
7797 std::swap(BasePtr, Offset);
7799 // Replace other uses of BasePtr that can be updated to use Ptr
7800 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7801 unsigned OffsetIdx = 1;
7802 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7804 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7805 BasePtr.getNode() && "Expected BasePtr operand");
7807 // We need to replace ptr0 in the following expression:
7808 // x0 * offset0 + y0 * ptr0 = t0
7810 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7812 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7813 // indexed load/store and the expresion that needs to be re-written.
7815 // Therefore, we have:
7816 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7818 ConstantSDNode *CN =
7819 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7821 APInt Offset0 = CN->getAPIntValue();
7822 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7824 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7825 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7826 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7827 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7829 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7831 APInt CNV = Offset0;
7832 if (X0 < 0) CNV = -CNV;
7833 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7834 else CNV = CNV - Offset1;
7836 // We can now generate the new expression.
7837 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7838 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7840 SDValue NewUse = DAG.getNode(Opcode,
7841 SDLoc(OtherUses[i]),
7842 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7843 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7844 removeFromWorklist(OtherUses[i]);
7845 DAG.DeleteNode(OtherUses[i]);
7848 // Replace the uses of Ptr with uses of the updated base value.
7849 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7850 removeFromWorklist(Ptr.getNode());
7851 DAG.DeleteNode(Ptr.getNode());
7856 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7857 /// add / sub of the base pointer node into a post-indexed load / store.
7858 /// The transformation folded the add / subtract into the new indexed
7859 /// load / store effectively and all of its uses are redirected to the
7860 /// new load / store.
7861 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7862 if (Level < AfterLegalizeDAG)
7868 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7869 if (LD->isIndexed())
7871 VT = LD->getMemoryVT();
7872 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7873 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7875 Ptr = LD->getBasePtr();
7876 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7877 if (ST->isIndexed())
7879 VT = ST->getMemoryVT();
7880 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7881 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7883 Ptr = ST->getBasePtr();
7889 if (Ptr.getNode()->hasOneUse())
7892 for (SDNode *Op : Ptr.getNode()->uses()) {
7894 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7899 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7900 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7901 // Don't create a indexed load / store with zero offset.
7902 if (isa<ConstantSDNode>(Offset) &&
7903 cast<ConstantSDNode>(Offset)->isNullValue())
7906 // Try turning it into a post-indexed load / store except when
7907 // 1) All uses are load / store ops that use it as base ptr (and
7908 // it may be folded as addressing mmode).
7909 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7910 // nor a successor of N. Otherwise, if Op is folded that would
7913 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7917 bool TryNext = false;
7918 for (SDNode *Use : BasePtr.getNode()->uses()) {
7919 if (Use == Ptr.getNode())
7922 // If all the uses are load / store addresses, then don't do the
7924 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7925 bool RealUse = false;
7926 for (SDNode *UseUse : Use->uses()) {
7927 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7942 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7943 SDValue Result = isLoad
7944 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7945 BasePtr, Offset, AM)
7946 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7947 BasePtr, Offset, AM);
7950 DEBUG(dbgs() << "\nReplacing.5 ";
7952 dbgs() << "\nWith: ";
7953 Result.getNode()->dump(&DAG);
7955 WorklistRemover DeadNodes(*this);
7957 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7958 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7960 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7963 // Finally, since the node is now dead, remove it from the graph.
7966 // Replace the uses of Use with uses of the updated base value.
7967 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7968 Result.getValue(isLoad ? 1 : 0));
7969 removeFromWorklist(Op);
7979 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7980 LoadSDNode *LD = cast<LoadSDNode>(N);
7981 SDValue Chain = LD->getChain();
7982 SDValue Ptr = LD->getBasePtr();
7984 // If load is not volatile and there are no uses of the loaded value (and
7985 // the updated indexed value in case of indexed loads), change uses of the
7986 // chain value into uses of the chain input (i.e. delete the dead load).
7987 if (!LD->isVolatile()) {
7988 if (N->getValueType(1) == MVT::Other) {
7990 if (!N->hasAnyUseOfValue(0)) {
7991 // It's not safe to use the two value CombineTo variant here. e.g.
7992 // v1, chain2 = load chain1, loc
7993 // v2, chain3 = load chain2, loc
7995 // Now we replace use of chain2 with chain1. This makes the second load
7996 // isomorphic to the one we are deleting, and thus makes this load live.
7997 DEBUG(dbgs() << "\nReplacing.6 ";
7999 dbgs() << "\nWith chain: ";
8000 Chain.getNode()->dump(&DAG);
8002 WorklistRemover DeadNodes(*this);
8003 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8005 if (N->use_empty()) {
8006 removeFromWorklist(N);
8010 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8014 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8015 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8016 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8017 DEBUG(dbgs() << "\nReplacing.7 ";
8019 dbgs() << "\nWith: ";
8020 Undef.getNode()->dump(&DAG);
8021 dbgs() << " and 2 other values\n");
8022 WorklistRemover DeadNodes(*this);
8023 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8024 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8025 DAG.getUNDEF(N->getValueType(1)));
8026 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8027 removeFromWorklist(N);
8029 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8034 // If this load is directly stored, replace the load value with the stored
8036 // TODO: Handle store large -> read small portion.
8037 // TODO: Handle TRUNCSTORE/LOADEXT
8038 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8039 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8040 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8041 if (PrevST->getBasePtr() == Ptr &&
8042 PrevST->getValue().getValueType() == N->getValueType(0))
8043 return CombineTo(N, Chain.getOperand(1), Chain);
8047 // Try to infer better alignment information than the load already has.
8048 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8049 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8050 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8052 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8053 LD->getValueType(0),
8054 Chain, Ptr, LD->getPointerInfo(),
8056 LD->isVolatile(), LD->isNonTemporal(), Align,
8058 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8063 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8064 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8066 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8067 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8070 if (UseAA && LD->isUnindexed()) {
8071 // Walk up chain skipping non-aliasing memory nodes.
8072 SDValue BetterChain = FindBetterChain(N, Chain);
8074 // If there is a better chain.
8075 if (Chain != BetterChain) {
8078 // Replace the chain to void dependency.
8079 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8080 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8081 BetterChain, Ptr, LD->getMemOperand());
8083 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8084 LD->getValueType(0),
8085 BetterChain, Ptr, LD->getMemoryVT(),
8086 LD->getMemOperand());
8089 // Create token factor to keep old chain connected.
8090 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8091 MVT::Other, Chain, ReplLoad.getValue(1));
8093 // Make sure the new and old chains are cleaned up.
8094 AddToWorklist(Token.getNode());
8096 // Replace uses with load result and token factor. Don't add users
8098 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8102 // Try transforming N to an indexed load.
8103 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8104 return SDValue(N, 0);
8106 // Try to slice up N to more direct loads if the slices are mapped to
8107 // different register banks or pairing can take place.
8109 return SDValue(N, 0);
8115 /// \brief Helper structure used to slice a load in smaller loads.
8116 /// Basically a slice is obtained from the following sequence:
8117 /// Origin = load Ty1, Base
8118 /// Shift = srl Ty1 Origin, CstTy Amount
8119 /// Inst = trunc Shift to Ty2
8121 /// Then, it will be rewriten into:
8122 /// Slice = load SliceTy, Base + SliceOffset
8123 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8125 /// SliceTy is deduced from the number of bits that are actually used to
8127 struct LoadedSlice {
8128 /// \brief Helper structure used to compute the cost of a slice.
8130 /// Are we optimizing for code size.
8135 unsigned CrossRegisterBanksCopies;
8139 Cost(bool ForCodeSize = false)
8140 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8141 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8143 /// \brief Get the cost of one isolated slice.
8144 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8145 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8146 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8147 EVT TruncType = LS.Inst->getValueType(0);
8148 EVT LoadedType = LS.getLoadedType();
8149 if (TruncType != LoadedType &&
8150 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8154 /// \brief Account for slicing gain in the current cost.
8155 /// Slicing provide a few gains like removing a shift or a
8156 /// truncate. This method allows to grow the cost of the original
8157 /// load with the gain from this slice.
8158 void addSliceGain(const LoadedSlice &LS) {
8159 // Each slice saves a truncate.
8160 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8161 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8162 LS.Inst->getOperand(0).getValueType()))
8164 // If there is a shift amount, this slice gets rid of it.
8167 // If this slice can merge a cross register bank copy, account for it.
8168 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8169 ++CrossRegisterBanksCopies;
8172 Cost &operator+=(const Cost &RHS) {
8174 Truncates += RHS.Truncates;
8175 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8181 bool operator==(const Cost &RHS) const {
8182 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8183 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8184 ZExts == RHS.ZExts && Shift == RHS.Shift;
8187 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8189 bool operator<(const Cost &RHS) const {
8190 // Assume cross register banks copies are as expensive as loads.
8191 // FIXME: Do we want some more target hooks?
8192 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8193 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8194 // Unless we are optimizing for code size, consider the
8195 // expensive operation first.
8196 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8197 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8198 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8199 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8202 bool operator>(const Cost &RHS) const { return RHS < *this; }
8204 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8206 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8208 // The last instruction that represent the slice. This should be a
8209 // truncate instruction.
8211 // The original load instruction.
8213 // The right shift amount in bits from the original load.
8215 // The DAG from which Origin came from.
8216 // This is used to get some contextual information about legal types, etc.
8219 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8220 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8221 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8223 LoadedSlice(const LoadedSlice &LS)
8224 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8226 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8227 /// \return Result is \p BitWidth and has used bits set to 1 and
8228 /// not used bits set to 0.
8229 APInt getUsedBits() const {
8230 // Reproduce the trunc(lshr) sequence:
8231 // - Start from the truncated value.
8232 // - Zero extend to the desired bit width.
8234 assert(Origin && "No original load to compare against.");
8235 unsigned BitWidth = Origin->getValueSizeInBits(0);
8236 assert(Inst && "This slice is not bound to an instruction");
8237 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8238 "Extracted slice is bigger than the whole type!");
8239 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8240 UsedBits.setAllBits();
8241 UsedBits = UsedBits.zext(BitWidth);
8246 /// \brief Get the size of the slice to be loaded in bytes.
8247 unsigned getLoadedSize() const {
8248 unsigned SliceSize = getUsedBits().countPopulation();
8249 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8250 return SliceSize / 8;
8253 /// \brief Get the type that will be loaded for this slice.
8254 /// Note: This may not be the final type for the slice.
8255 EVT getLoadedType() const {
8256 assert(DAG && "Missing context");
8257 LLVMContext &Ctxt = *DAG->getContext();
8258 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8261 /// \brief Get the alignment of the load used for this slice.
8262 unsigned getAlignment() const {
8263 unsigned Alignment = Origin->getAlignment();
8264 unsigned Offset = getOffsetFromBase();
8266 Alignment = MinAlign(Alignment, Alignment + Offset);
8270 /// \brief Check if this slice can be rewritten with legal operations.
8271 bool isLegal() const {
8272 // An invalid slice is not legal.
8273 if (!Origin || !Inst || !DAG)
8276 // Offsets are for indexed load only, we do not handle that.
8277 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8280 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8282 // Check that the type is legal.
8283 EVT SliceType = getLoadedType();
8284 if (!TLI.isTypeLegal(SliceType))
8287 // Check that the load is legal for this type.
8288 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8291 // Check that the offset can be computed.
8292 // 1. Check its type.
8293 EVT PtrType = Origin->getBasePtr().getValueType();
8294 if (PtrType == MVT::Untyped || PtrType.isExtended())
8297 // 2. Check that it fits in the immediate.
8298 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8301 // 3. Check that the computation is legal.
8302 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8305 // Check that the zext is legal if it needs one.
8306 EVT TruncateType = Inst->getValueType(0);
8307 if (TruncateType != SliceType &&
8308 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8314 /// \brief Get the offset in bytes of this slice in the original chunk of
8316 /// \pre DAG != nullptr.
8317 uint64_t getOffsetFromBase() const {
8318 assert(DAG && "Missing context.");
8320 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8321 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8322 uint64_t Offset = Shift / 8;
8323 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8324 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8325 "The size of the original loaded type is not a multiple of a"
8327 // If Offset is bigger than TySizeInBytes, it means we are loading all
8328 // zeros. This should have been optimized before in the process.
8329 assert(TySizeInBytes > Offset &&
8330 "Invalid shift amount for given loaded size");
8332 Offset = TySizeInBytes - Offset - getLoadedSize();
8336 /// \brief Generate the sequence of instructions to load the slice
8337 /// represented by this object and redirect the uses of this slice to
8338 /// this new sequence of instructions.
8339 /// \pre this->Inst && this->Origin are valid Instructions and this
8340 /// object passed the legal check: LoadedSlice::isLegal returned true.
8341 /// \return The last instruction of the sequence used to load the slice.
8342 SDValue loadSlice() const {
8343 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8344 const SDValue &OldBaseAddr = Origin->getBasePtr();
8345 SDValue BaseAddr = OldBaseAddr;
8346 // Get the offset in that chunk of bytes w.r.t. the endianess.
8347 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8348 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8350 // BaseAddr = BaseAddr + Offset.
8351 EVT ArithType = BaseAddr.getValueType();
8352 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8353 DAG->getConstant(Offset, ArithType));
8356 // Create the type of the loaded slice according to its size.
8357 EVT SliceType = getLoadedType();
8359 // Create the load for the slice.
8360 SDValue LastInst = DAG->getLoad(
8361 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8362 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8363 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8364 // If the final type is not the same as the loaded type, this means that
8365 // we have to pad with zero. Create a zero extend for that.
8366 EVT FinalType = Inst->getValueType(0);
8367 if (SliceType != FinalType)
8369 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8373 /// \brief Check if this slice can be merged with an expensive cross register
8374 /// bank copy. E.g.,
8376 /// f = bitcast i32 i to float
8377 bool canMergeExpensiveCrossRegisterBankCopy() const {
8378 if (!Inst || !Inst->hasOneUse())
8380 SDNode *Use = *Inst->use_begin();
8381 if (Use->getOpcode() != ISD::BITCAST)
8383 assert(DAG && "Missing context");
8384 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8385 EVT ResVT = Use->getValueType(0);
8386 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8387 const TargetRegisterClass *ArgRC =
8388 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8389 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8392 // At this point, we know that we perform a cross-register-bank copy.
8393 // Check if it is expensive.
8394 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8395 // Assume bitcasts are cheap, unless both register classes do not
8396 // explicitly share a common sub class.
8397 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8400 // Check if it will be merged with the load.
8401 // 1. Check the alignment constraint.
8402 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8403 ResVT.getTypeForEVT(*DAG->getContext()));
8405 if (RequiredAlignment > getAlignment())
8408 // 2. Check that the load is a legal operation for that type.
8409 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8412 // 3. Check that we do not have a zext in the way.
8413 if (Inst->getValueType(0) != getLoadedType())
8421 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8422 /// \p UsedBits looks like 0..0 1..1 0..0.
8423 static bool areUsedBitsDense(const APInt &UsedBits) {
8424 // If all the bits are one, this is dense!
8425 if (UsedBits.isAllOnesValue())
8428 // Get rid of the unused bits on the right.
8429 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8430 // Get rid of the unused bits on the left.
8431 if (NarrowedUsedBits.countLeadingZeros())
8432 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8433 // Check that the chunk of bits is completely used.
8434 return NarrowedUsedBits.isAllOnesValue();
8437 /// \brief Check whether or not \p First and \p Second are next to each other
8438 /// in memory. This means that there is no hole between the bits loaded
8439 /// by \p First and the bits loaded by \p Second.
8440 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8441 const LoadedSlice &Second) {
8442 assert(First.Origin == Second.Origin && First.Origin &&
8443 "Unable to match different memory origins.");
8444 APInt UsedBits = First.getUsedBits();
8445 assert((UsedBits & Second.getUsedBits()) == 0 &&
8446 "Slices are not supposed to overlap.");
8447 UsedBits |= Second.getUsedBits();
8448 return areUsedBitsDense(UsedBits);
8451 /// \brief Adjust the \p GlobalLSCost according to the target
8452 /// paring capabilities and the layout of the slices.
8453 /// \pre \p GlobalLSCost should account for at least as many loads as
8454 /// there is in the slices in \p LoadedSlices.
8455 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8456 LoadedSlice::Cost &GlobalLSCost) {
8457 unsigned NumberOfSlices = LoadedSlices.size();
8458 // If there is less than 2 elements, no pairing is possible.
8459 if (NumberOfSlices < 2)
8462 // Sort the slices so that elements that are likely to be next to each
8463 // other in memory are next to each other in the list.
8464 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8465 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8466 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8467 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8469 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8470 // First (resp. Second) is the first (resp. Second) potentially candidate
8471 // to be placed in a paired load.
8472 const LoadedSlice *First = nullptr;
8473 const LoadedSlice *Second = nullptr;
8474 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8475 // Set the beginning of the pair.
8478 Second = &LoadedSlices[CurrSlice];
8480 // If First is NULL, it means we start a new pair.
8481 // Get to the next slice.
8485 EVT LoadedType = First->getLoadedType();
8487 // If the types of the slices are different, we cannot pair them.
8488 if (LoadedType != Second->getLoadedType())
8491 // Check if the target supplies paired loads for this type.
8492 unsigned RequiredAlignment = 0;
8493 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8494 // move to the next pair, this type is hopeless.
8498 // Check if we meet the alignment requirement.
8499 if (RequiredAlignment > First->getAlignment())
8502 // Check that both loads are next to each other in memory.
8503 if (!areSlicesNextToEachOther(*First, *Second))
8506 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8507 --GlobalLSCost.Loads;
8508 // Move to the next pair.
8513 /// \brief Check the profitability of all involved LoadedSlice.
8514 /// Currently, it is considered profitable if there is exactly two
8515 /// involved slices (1) which are (2) next to each other in memory, and
8516 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8518 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8519 /// the elements themselves.
8521 /// FIXME: When the cost model will be mature enough, we can relax
8522 /// constraints (1) and (2).
8523 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8524 const APInt &UsedBits, bool ForCodeSize) {
8525 unsigned NumberOfSlices = LoadedSlices.size();
8526 if (StressLoadSlicing)
8527 return NumberOfSlices > 1;
8530 if (NumberOfSlices != 2)
8534 if (!areUsedBitsDense(UsedBits))
8538 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8539 // The original code has one big load.
8541 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8542 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8543 // Accumulate the cost of all the slices.
8544 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8545 GlobalSlicingCost += SliceCost;
8547 // Account as cost in the original configuration the gain obtained
8548 // with the current slices.
8549 OrigCost.addSliceGain(LS);
8552 // If the target supports paired load, adjust the cost accordingly.
8553 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8554 return OrigCost > GlobalSlicingCost;
8557 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8558 /// operations, split it in the various pieces being extracted.
8560 /// This sort of thing is introduced by SROA.
8561 /// This slicing takes care not to insert overlapping loads.
8562 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8563 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8564 if (Level < AfterLegalizeDAG)
8567 LoadSDNode *LD = cast<LoadSDNode>(N);
8568 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8569 !LD->getValueType(0).isInteger())
8572 // Keep track of already used bits to detect overlapping values.
8573 // In that case, we will just abort the transformation.
8574 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8576 SmallVector<LoadedSlice, 4> LoadedSlices;
8578 // Check if this load is used as several smaller chunks of bits.
8579 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8580 // of computation for each trunc.
8581 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8582 UI != UIEnd; ++UI) {
8583 // Skip the uses of the chain.
8584 if (UI.getUse().getResNo() != 0)
8590 // Check if this is a trunc(lshr).
8591 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8592 isa<ConstantSDNode>(User->getOperand(1))) {
8593 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8594 User = *User->use_begin();
8597 // At this point, User is a Truncate, iff we encountered, trunc or
8599 if (User->getOpcode() != ISD::TRUNCATE)
8602 // The width of the type must be a power of 2 and greater than 8-bits.
8603 // Otherwise the load cannot be represented in LLVM IR.
8604 // Moreover, if we shifted with a non-8-bits multiple, the slice
8605 // will be across several bytes. We do not support that.
8606 unsigned Width = User->getValueSizeInBits(0);
8607 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8610 // Build the slice for this chain of computations.
8611 LoadedSlice LS(User, LD, Shift, &DAG);
8612 APInt CurrentUsedBits = LS.getUsedBits();
8614 // Check if this slice overlaps with another.
8615 if ((CurrentUsedBits & UsedBits) != 0)
8617 // Update the bits used globally.
8618 UsedBits |= CurrentUsedBits;
8620 // Check if the new slice would be legal.
8624 // Record the slice.
8625 LoadedSlices.push_back(LS);
8628 // Abort slicing if it does not seem to be profitable.
8629 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8634 // Rewrite each chain to use an independent load.
8635 // By construction, each chain can be represented by a unique load.
8637 // Prepare the argument for the new token factor for all the slices.
8638 SmallVector<SDValue, 8> ArgChains;
8639 for (SmallVectorImpl<LoadedSlice>::const_iterator
8640 LSIt = LoadedSlices.begin(),
8641 LSItEnd = LoadedSlices.end();
8642 LSIt != LSItEnd; ++LSIt) {
8643 SDValue SliceInst = LSIt->loadSlice();
8644 CombineTo(LSIt->Inst, SliceInst, true);
8645 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8646 SliceInst = SliceInst.getOperand(0);
8647 assert(SliceInst->getOpcode() == ISD::LOAD &&
8648 "It takes more than a zext to get to the loaded slice!!");
8649 ArgChains.push_back(SliceInst.getValue(1));
8652 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8654 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8658 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8659 /// load is having specific bytes cleared out. If so, return the byte size
8660 /// being masked out and the shift amount.
8661 static std::pair<unsigned, unsigned>
8662 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8663 std::pair<unsigned, unsigned> Result(0, 0);
8665 // Check for the structure we're looking for.
8666 if (V->getOpcode() != ISD::AND ||
8667 !isa<ConstantSDNode>(V->getOperand(1)) ||
8668 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8671 // Check the chain and pointer.
8672 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8673 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8675 // The store should be chained directly to the load or be an operand of a
8677 if (LD == Chain.getNode())
8679 else if (Chain->getOpcode() != ISD::TokenFactor)
8680 return Result; // Fail.
8683 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8684 if (Chain->getOperand(i).getNode() == LD) {
8688 if (!isOk) return Result;
8691 // This only handles simple types.
8692 if (V.getValueType() != MVT::i16 &&
8693 V.getValueType() != MVT::i32 &&
8694 V.getValueType() != MVT::i64)
8697 // Check the constant mask. Invert it so that the bits being masked out are
8698 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8699 // follow the sign bit for uniformity.
8700 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8701 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8702 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8703 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8704 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8705 if (NotMaskLZ == 64) return Result; // All zero mask.
8707 // See if we have a continuous run of bits. If so, we have 0*1+0*
8708 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8711 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8712 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8713 NotMaskLZ -= 64-V.getValueSizeInBits();
8715 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8716 switch (MaskedBytes) {
8720 default: return Result; // All one mask, or 5-byte mask.
8723 // Verify that the first bit starts at a multiple of mask so that the access
8724 // is aligned the same as the access width.
8725 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8727 Result.first = MaskedBytes;
8728 Result.second = NotMaskTZ/8;
8733 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8734 /// provides a value as specified by MaskInfo. If so, replace the specified
8735 /// store with a narrower store of truncated IVal.
8737 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8738 SDValue IVal, StoreSDNode *St,
8740 unsigned NumBytes = MaskInfo.first;
8741 unsigned ByteShift = MaskInfo.second;
8742 SelectionDAG &DAG = DC->getDAG();
8744 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8745 // that uses this. If not, this is not a replacement.
8746 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8747 ByteShift*8, (ByteShift+NumBytes)*8);
8748 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8750 // Check that it is legal on the target to do this. It is legal if the new
8751 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8753 MVT VT = MVT::getIntegerVT(NumBytes*8);
8754 if (!DC->isTypeLegal(VT))
8757 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8758 // shifted by ByteShift and truncated down to NumBytes.
8760 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8761 DAG.getConstant(ByteShift*8,
8762 DC->getShiftAmountTy(IVal.getValueType())));
8764 // Figure out the offset for the store and the alignment of the access.
8766 unsigned NewAlign = St->getAlignment();
8768 if (DAG.getTargetLoweringInfo().isLittleEndian())
8769 StOffset = ByteShift;
8771 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8773 SDValue Ptr = St->getBasePtr();
8775 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8776 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8777 NewAlign = MinAlign(NewAlign, StOffset);
8780 // Truncate down to the new size.
8781 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8784 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8785 St->getPointerInfo().getWithOffset(StOffset),
8786 false, false, NewAlign).getNode();
8790 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8791 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8792 /// of the loaded bits, try narrowing the load and store if it would end up
8793 /// being a win for performance or code size.
8794 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8795 StoreSDNode *ST = cast<StoreSDNode>(N);
8796 if (ST->isVolatile())
8799 SDValue Chain = ST->getChain();
8800 SDValue Value = ST->getValue();
8801 SDValue Ptr = ST->getBasePtr();
8802 EVT VT = Value.getValueType();
8804 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8807 unsigned Opc = Value.getOpcode();
8809 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8810 // is a byte mask indicating a consecutive number of bytes, check to see if
8811 // Y is known to provide just those bytes. If so, we try to replace the
8812 // load + replace + store sequence with a single (narrower) store, which makes
8814 if (Opc == ISD::OR) {
8815 std::pair<unsigned, unsigned> MaskedLoad;
8816 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8817 if (MaskedLoad.first)
8818 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8819 Value.getOperand(1), ST,this))
8820 return SDValue(NewST, 0);
8822 // Or is commutative, so try swapping X and Y.
8823 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8824 if (MaskedLoad.first)
8825 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8826 Value.getOperand(0), ST,this))
8827 return SDValue(NewST, 0);
8830 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8831 Value.getOperand(1).getOpcode() != ISD::Constant)
8834 SDValue N0 = Value.getOperand(0);
8835 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8836 Chain == SDValue(N0.getNode(), 1)) {
8837 LoadSDNode *LD = cast<LoadSDNode>(N0);
8838 if (LD->getBasePtr() != Ptr ||
8839 LD->getPointerInfo().getAddrSpace() !=
8840 ST->getPointerInfo().getAddrSpace())
8843 // Find the type to narrow it the load / op / store to.
8844 SDValue N1 = Value.getOperand(1);
8845 unsigned BitWidth = N1.getValueSizeInBits();
8846 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8847 if (Opc == ISD::AND)
8848 Imm ^= APInt::getAllOnesValue(BitWidth);
8849 if (Imm == 0 || Imm.isAllOnesValue())
8851 unsigned ShAmt = Imm.countTrailingZeros();
8852 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8853 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8854 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8855 while (NewBW < BitWidth &&
8856 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8857 TLI.isNarrowingProfitable(VT, NewVT))) {
8858 NewBW = NextPowerOf2(NewBW);
8859 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8861 if (NewBW >= BitWidth)
8864 // If the lsb changed does not start at the type bitwidth boundary,
8865 // start at the previous one.
8867 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8868 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8869 std::min(BitWidth, ShAmt + NewBW));
8870 if ((Imm & Mask) == Imm) {
8871 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8872 if (Opc == ISD::AND)
8873 NewImm ^= APInt::getAllOnesValue(NewBW);
8874 uint64_t PtrOff = ShAmt / 8;
8875 // For big endian targets, we need to adjust the offset to the pointer to
8876 // load the correct bytes.
8877 if (TLI.isBigEndian())
8878 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8880 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8881 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8882 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8885 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8886 Ptr.getValueType(), Ptr,
8887 DAG.getConstant(PtrOff, Ptr.getValueType()));
8888 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8889 LD->getChain(), NewPtr,
8890 LD->getPointerInfo().getWithOffset(PtrOff),
8891 LD->isVolatile(), LD->isNonTemporal(),
8892 LD->isInvariant(), NewAlign,
8894 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8895 DAG.getConstant(NewImm, NewVT));
8896 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8898 ST->getPointerInfo().getWithOffset(PtrOff),
8899 false, false, NewAlign);
8901 AddToWorklist(NewPtr.getNode());
8902 AddToWorklist(NewLD.getNode());
8903 AddToWorklist(NewVal.getNode());
8904 WorklistRemover DeadNodes(*this);
8905 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8914 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8915 /// if the load value isn't used by any other operations, then consider
8916 /// transforming the pair to integer load / store operations if the target
8917 /// deems the transformation profitable.
8918 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8919 StoreSDNode *ST = cast<StoreSDNode>(N);
8920 SDValue Chain = ST->getChain();
8921 SDValue Value = ST->getValue();
8922 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8923 Value.hasOneUse() &&
8924 Chain == SDValue(Value.getNode(), 1)) {
8925 LoadSDNode *LD = cast<LoadSDNode>(Value);
8926 EVT VT = LD->getMemoryVT();
8927 if (!VT.isFloatingPoint() ||
8928 VT != ST->getMemoryVT() ||
8929 LD->isNonTemporal() ||
8930 ST->isNonTemporal() ||
8931 LD->getPointerInfo().getAddrSpace() != 0 ||
8932 ST->getPointerInfo().getAddrSpace() != 0)
8935 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8936 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8937 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8938 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8939 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8942 unsigned LDAlign = LD->getAlignment();
8943 unsigned STAlign = ST->getAlignment();
8944 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8945 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8946 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8949 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8950 LD->getChain(), LD->getBasePtr(),
8951 LD->getPointerInfo(),
8952 false, false, false, LDAlign);
8954 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8955 NewLD, ST->getBasePtr(),
8956 ST->getPointerInfo(),
8957 false, false, STAlign);
8959 AddToWorklist(NewLD.getNode());
8960 AddToWorklist(NewST.getNode());
8961 WorklistRemover DeadNodes(*this);
8962 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8970 /// Helper struct to parse and store a memory address as base + index + offset.
8971 /// We ignore sign extensions when it is safe to do so.
8972 /// The following two expressions are not equivalent. To differentiate we need
8973 /// to store whether there was a sign extension involved in the index
8975 /// (load (i64 add (i64 copyfromreg %c)
8976 /// (i64 signextend (add (i8 load %index)
8980 /// (load (i64 add (i64 copyfromreg %c)
8981 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8983 struct BaseIndexOffset {
8987 bool IsIndexSignExt;
8989 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8991 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8992 bool IsIndexSignExt) :
8993 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8995 bool equalBaseIndex(const BaseIndexOffset &Other) {
8996 return Other.Base == Base && Other.Index == Index &&
8997 Other.IsIndexSignExt == IsIndexSignExt;
9000 /// Parses tree in Ptr for base, index, offset addresses.
9001 static BaseIndexOffset match(SDValue Ptr) {
9002 bool IsIndexSignExt = false;
9004 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9005 // instruction, then it could be just the BASE or everything else we don't
9006 // know how to handle. Just use Ptr as BASE and give up.
9007 if (Ptr->getOpcode() != ISD::ADD)
9008 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9010 // We know that we have at least an ADD instruction. Try to pattern match
9011 // the simple case of BASE + OFFSET.
9012 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9013 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9014 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9018 // Inside a loop the current BASE pointer is calculated using an ADD and a
9019 // MUL instruction. In this case Ptr is the actual BASE pointer.
9020 // (i64 add (i64 %array_ptr)
9021 // (i64 mul (i64 %induction_var)
9022 // (i64 %element_size)))
9023 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9024 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9026 // Look at Base + Index + Offset cases.
9027 SDValue Base = Ptr->getOperand(0);
9028 SDValue IndexOffset = Ptr->getOperand(1);
9030 // Skip signextends.
9031 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9032 IndexOffset = IndexOffset->getOperand(0);
9033 IsIndexSignExt = true;
9036 // Either the case of Base + Index (no offset) or something else.
9037 if (IndexOffset->getOpcode() != ISD::ADD)
9038 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9040 // Now we have the case of Base + Index + offset.
9041 SDValue Index = IndexOffset->getOperand(0);
9042 SDValue Offset = IndexOffset->getOperand(1);
9044 if (!isa<ConstantSDNode>(Offset))
9045 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9047 // Ignore signextends.
9048 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9049 Index = Index->getOperand(0);
9050 IsIndexSignExt = true;
9051 } else IsIndexSignExt = false;
9053 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9054 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9058 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9059 /// is located in a sequence of memory operations connected by a chain.
9061 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9062 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9063 // Ptr to the mem node.
9064 LSBaseSDNode *MemNode;
9065 // Offset from the base ptr.
9066 int64_t OffsetFromBase;
9067 // What is the sequence number of this mem node.
9068 // Lowest mem operand in the DAG starts at zero.
9069 unsigned SequenceNum;
9072 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9073 EVT MemVT = St->getMemoryVT();
9074 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9075 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9076 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9078 // Don't merge vectors into wider inputs.
9079 if (MemVT.isVector() || !MemVT.isSimple())
9082 // Perform an early exit check. Do not bother looking at stored values that
9083 // are not constants or loads.
9084 SDValue StoredVal = St->getValue();
9085 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9086 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9090 // Only look at ends of store sequences.
9091 SDValue Chain = SDValue(St, 0);
9092 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9095 // This holds the base pointer, index, and the offset in bytes from the base
9097 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9099 // We must have a base and an offset.
9100 if (!BasePtr.Base.getNode())
9103 // Do not handle stores to undef base pointers.
9104 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9107 // Save the LoadSDNodes that we find in the chain.
9108 // We need to make sure that these nodes do not interfere with
9109 // any of the store nodes.
9110 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9112 // Save the StoreSDNodes that we find in the chain.
9113 SmallVector<MemOpLink, 8> StoreNodes;
9115 // Walk up the chain and look for nodes with offsets from the same
9116 // base pointer. Stop when reaching an instruction with a different kind
9117 // or instruction which has a different base pointer.
9119 StoreSDNode *Index = St;
9121 // If the chain has more than one use, then we can't reorder the mem ops.
9122 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9125 // Find the base pointer and offset for this memory node.
9126 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9128 // Check that the base pointer is the same as the original one.
9129 if (!Ptr.equalBaseIndex(BasePtr))
9132 // Check that the alignment is the same.
9133 if (Index->getAlignment() != St->getAlignment())
9136 // The memory operands must not be volatile.
9137 if (Index->isVolatile() || Index->isIndexed())
9141 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9142 if (St->isTruncatingStore())
9145 // The stored memory type must be the same.
9146 if (Index->getMemoryVT() != MemVT)
9149 // We do not allow unaligned stores because we want to prevent overriding
9151 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9154 // We found a potential memory operand to merge.
9155 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9157 // Find the next memory operand in the chain. If the next operand in the
9158 // chain is a store then move up and continue the scan with the next
9159 // memory operand. If the next operand is a load save it and use alias
9160 // information to check if it interferes with anything.
9161 SDNode *NextInChain = Index->getChain().getNode();
9163 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9164 // We found a store node. Use it for the next iteration.
9167 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9168 if (Ldn->isVolatile()) {
9173 // Save the load node for later. Continue the scan.
9174 AliasLoadNodes.push_back(Ldn);
9175 NextInChain = Ldn->getChain().getNode();
9184 // Check if there is anything to merge.
9185 if (StoreNodes.size() < 2)
9188 // Sort the memory operands according to their distance from the base pointer.
9189 std::sort(StoreNodes.begin(), StoreNodes.end(),
9190 [](MemOpLink LHS, MemOpLink RHS) {
9191 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9192 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9193 LHS.SequenceNum > RHS.SequenceNum);
9196 // Scan the memory operations on the chain and find the first non-consecutive
9197 // store memory address.
9198 unsigned LastConsecutiveStore = 0;
9199 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9200 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9202 // Check that the addresses are consecutive starting from the second
9203 // element in the list of stores.
9205 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9206 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9211 // Check if this store interferes with any of the loads that we found.
9212 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9213 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9217 // We found a load that alias with this store. Stop the sequence.
9221 // Mark this node as useful.
9222 LastConsecutiveStore = i;
9225 // The node with the lowest store address.
9226 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9228 // Store the constants into memory as one consecutive store.
9230 unsigned LastLegalType = 0;
9231 unsigned LastLegalVectorType = 0;
9232 bool NonZero = false;
9233 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9234 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9235 SDValue StoredVal = St->getValue();
9237 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9238 NonZero |= !C->isNullValue();
9239 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9240 NonZero |= !C->getConstantFPValue()->isNullValue();
9246 // Find a legal type for the constant store.
9247 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9248 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9249 if (TLI.isTypeLegal(StoreTy))
9250 LastLegalType = i+1;
9251 // Or check whether a truncstore is legal.
9252 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9253 TargetLowering::TypePromoteInteger) {
9254 EVT LegalizedStoredValueTy =
9255 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9256 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9257 LastLegalType = i+1;
9260 // Find a legal type for the vector store.
9261 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9262 if (TLI.isTypeLegal(Ty))
9263 LastLegalVectorType = i + 1;
9266 // We only use vectors if the constant is known to be zero and the
9267 // function is not marked with the noimplicitfloat attribute.
9268 if (NonZero || NoVectors)
9269 LastLegalVectorType = 0;
9271 // Check if we found a legal integer type to store.
9272 if (LastLegalType == 0 && LastLegalVectorType == 0)
9275 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9276 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9278 // Make sure we have something to merge.
9282 unsigned EarliestNodeUsed = 0;
9283 for (unsigned i=0; i < NumElem; ++i) {
9284 // Find a chain for the new wide-store operand. Notice that some
9285 // of the store nodes that we found may not be selected for inclusion
9286 // in the wide store. The chain we use needs to be the chain of the
9287 // earliest store node which is *used* and replaced by the wide store.
9288 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9289 EarliestNodeUsed = i;
9292 // The earliest Node in the DAG.
9293 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9294 SDLoc DL(StoreNodes[0].MemNode);
9298 // Find a legal type for the vector store.
9299 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9300 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9301 StoredVal = DAG.getConstant(0, Ty);
9303 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9304 APInt StoreInt(StoreBW, 0);
9306 // Construct a single integer constant which is made of the smaller
9308 bool IsLE = TLI.isLittleEndian();
9309 for (unsigned i = 0; i < NumElem ; ++i) {
9310 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9311 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9312 SDValue Val = St->getValue();
9313 StoreInt<<=ElementSizeBytes*8;
9314 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9315 StoreInt|=C->getAPIntValue().zext(StoreBW);
9316 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9317 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9319 assert(false && "Invalid constant element type");
9323 // Create the new Load and Store operations.
9324 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9325 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9328 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9329 FirstInChain->getBasePtr(),
9330 FirstInChain->getPointerInfo(),
9332 FirstInChain->getAlignment());
9334 // Replace the first store with the new store
9335 CombineTo(EarliestOp, NewStore);
9336 // Erase all other stores.
9337 for (unsigned i = 0; i < NumElem ; ++i) {
9338 if (StoreNodes[i].MemNode == EarliestOp)
9340 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9341 // ReplaceAllUsesWith will replace all uses that existed when it was
9342 // called, but graph optimizations may cause new ones to appear. For
9343 // example, the case in pr14333 looks like
9345 // St's chain -> St -> another store -> X
9347 // And the only difference from St to the other store is the chain.
9348 // When we change it's chain to be St's chain they become identical,
9349 // get CSEed and the net result is that X is now a use of St.
9350 // Since we know that St is redundant, just iterate.
9351 while (!St->use_empty())
9352 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9353 removeFromWorklist(St);
9360 // Below we handle the case of multiple consecutive stores that
9361 // come from multiple consecutive loads. We merge them into a single
9362 // wide load and a single wide store.
9364 // Look for load nodes which are used by the stored values.
9365 SmallVector<MemOpLink, 8> LoadNodes;
9367 // Find acceptable loads. Loads need to have the same chain (token factor),
9368 // must not be zext, volatile, indexed, and they must be consecutive.
9369 BaseIndexOffset LdBasePtr;
9370 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9371 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9372 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9375 // Loads must only have one use.
9376 if (!Ld->hasNUsesOfValue(1, 0))
9379 // Check that the alignment is the same as the stores.
9380 if (Ld->getAlignment() != St->getAlignment())
9383 // The memory operands must not be volatile.
9384 if (Ld->isVolatile() || Ld->isIndexed())
9387 // We do not accept ext loads.
9388 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9391 // The stored memory type must be the same.
9392 if (Ld->getMemoryVT() != MemVT)
9395 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9396 // If this is not the first ptr that we check.
9397 if (LdBasePtr.Base.getNode()) {
9398 // The base ptr must be the same.
9399 if (!LdPtr.equalBaseIndex(LdBasePtr))
9402 // Check that all other base pointers are the same as this one.
9406 // We found a potential memory operand to merge.
9407 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9410 if (LoadNodes.size() < 2)
9413 // Scan the memory operations on the chain and find the first non-consecutive
9414 // load memory address. These variables hold the index in the store node
9416 unsigned LastConsecutiveLoad = 0;
9417 // This variable refers to the size and not index in the array.
9418 unsigned LastLegalVectorType = 0;
9419 unsigned LastLegalIntegerType = 0;
9420 StartAddress = LoadNodes[0].OffsetFromBase;
9421 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9422 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9423 // All loads much share the same chain.
9424 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9427 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9428 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9430 LastConsecutiveLoad = i;
9432 // Find a legal type for the vector store.
9433 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9434 if (TLI.isTypeLegal(StoreTy))
9435 LastLegalVectorType = i + 1;
9437 // Find a legal type for the integer store.
9438 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9439 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9440 if (TLI.isTypeLegal(StoreTy))
9441 LastLegalIntegerType = i + 1;
9442 // Or check whether a truncstore and extload is legal.
9443 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9444 TargetLowering::TypePromoteInteger) {
9445 EVT LegalizedStoredValueTy =
9446 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9447 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9448 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9449 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9450 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9451 LastLegalIntegerType = i+1;
9455 // Only use vector types if the vector type is larger than the integer type.
9456 // If they are the same, use integers.
9457 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9458 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9460 // We add +1 here because the LastXXX variables refer to location while
9461 // the NumElem refers to array/index size.
9462 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9463 NumElem = std::min(LastLegalType, NumElem);
9468 // The earliest Node in the DAG.
9469 unsigned EarliestNodeUsed = 0;
9470 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9471 for (unsigned i=1; i<NumElem; ++i) {
9472 // Find a chain for the new wide-store operand. Notice that some
9473 // of the store nodes that we found may not be selected for inclusion
9474 // in the wide store. The chain we use needs to be the chain of the
9475 // earliest store node which is *used* and replaced by the wide store.
9476 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9477 EarliestNodeUsed = i;
9480 // Find if it is better to use vectors or integers to load and store
9484 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9486 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9487 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9490 SDLoc LoadDL(LoadNodes[0].MemNode);
9491 SDLoc StoreDL(StoreNodes[0].MemNode);
9493 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9494 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9495 FirstLoad->getChain(),
9496 FirstLoad->getBasePtr(),
9497 FirstLoad->getPointerInfo(),
9498 false, false, false,
9499 FirstLoad->getAlignment());
9501 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9502 FirstInChain->getBasePtr(),
9503 FirstInChain->getPointerInfo(), false, false,
9504 FirstInChain->getAlignment());
9506 // Replace one of the loads with the new load.
9507 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9508 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9509 SDValue(NewLoad.getNode(), 1));
9511 // Remove the rest of the load chains.
9512 for (unsigned i = 1; i < NumElem ; ++i) {
9513 // Replace all chain users of the old load nodes with the chain of the new
9515 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9516 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9519 // Replace the first store with the new store.
9520 CombineTo(EarliestOp, NewStore);
9521 // Erase all other stores.
9522 for (unsigned i = 0; i < NumElem ; ++i) {
9523 // Remove all Store nodes.
9524 if (StoreNodes[i].MemNode == EarliestOp)
9526 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9527 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9528 removeFromWorklist(St);
9535 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9536 StoreSDNode *ST = cast<StoreSDNode>(N);
9537 SDValue Chain = ST->getChain();
9538 SDValue Value = ST->getValue();
9539 SDValue Ptr = ST->getBasePtr();
9541 // If this is a store of a bit convert, store the input value if the
9542 // resultant store does not need a higher alignment than the original.
9543 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9544 ST->isUnindexed()) {
9545 unsigned OrigAlign = ST->getAlignment();
9546 EVT SVT = Value.getOperand(0).getValueType();
9547 unsigned Align = TLI.getDataLayout()->
9548 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9549 if (Align <= OrigAlign &&
9550 ((!LegalOperations && !ST->isVolatile()) ||
9551 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9552 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9553 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9554 ST->isNonTemporal(), OrigAlign,
9558 // Turn 'store undef, Ptr' -> nothing.
9559 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9562 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9563 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9564 // NOTE: If the original store is volatile, this transform must not increase
9565 // the number of stores. For example, on x86-32 an f64 can be stored in one
9566 // processor operation but an i64 (which is not legal) requires two. So the
9567 // transform should not be done in this case.
9568 if (Value.getOpcode() != ISD::TargetConstantFP) {
9570 switch (CFP->getSimpleValueType(0).SimpleTy) {
9571 default: llvm_unreachable("Unknown FP type");
9572 case MVT::f16: // We don't do this for these yet.
9578 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9579 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9580 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9581 bitcastToAPInt().getZExtValue(), MVT::i32);
9582 return DAG.getStore(Chain, SDLoc(N), Tmp,
9583 Ptr, ST->getMemOperand());
9587 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9588 !ST->isVolatile()) ||
9589 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9590 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9591 getZExtValue(), MVT::i64);
9592 return DAG.getStore(Chain, SDLoc(N), Tmp,
9593 Ptr, ST->getMemOperand());
9596 if (!ST->isVolatile() &&
9597 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9598 // Many FP stores are not made apparent until after legalize, e.g. for
9599 // argument passing. Since this is so common, custom legalize the
9600 // 64-bit integer store into two 32-bit stores.
9601 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9602 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9603 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9604 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9606 unsigned Alignment = ST->getAlignment();
9607 bool isVolatile = ST->isVolatile();
9608 bool isNonTemporal = ST->isNonTemporal();
9609 AAMDNodes AAInfo = ST->getAAInfo();
9611 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9612 Ptr, ST->getPointerInfo(),
9613 isVolatile, isNonTemporal,
9614 ST->getAlignment(), AAInfo);
9615 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9616 DAG.getConstant(4, Ptr.getValueType()));
9617 Alignment = MinAlign(Alignment, 4U);
9618 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9619 Ptr, ST->getPointerInfo().getWithOffset(4),
9620 isVolatile, isNonTemporal,
9622 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9631 // Try to infer better alignment information than the store already has.
9632 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9633 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9634 if (Align > ST->getAlignment())
9635 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9636 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9637 ST->isVolatile(), ST->isNonTemporal(), Align,
9642 // Try transforming a pair floating point load / store ops to integer
9643 // load / store ops.
9644 SDValue NewST = TransformFPLoadStorePair(N);
9645 if (NewST.getNode())
9648 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9649 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9651 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9652 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9655 if (UseAA && ST->isUnindexed()) {
9656 // Walk up chain skipping non-aliasing memory nodes.
9657 SDValue BetterChain = FindBetterChain(N, Chain);
9659 // If there is a better chain.
9660 if (Chain != BetterChain) {
9663 // Replace the chain to avoid dependency.
9664 if (ST->isTruncatingStore()) {
9665 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9666 ST->getMemoryVT(), ST->getMemOperand());
9668 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9669 ST->getMemOperand());
9672 // Create token to keep both nodes around.
9673 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9674 MVT::Other, Chain, ReplStore);
9676 // Make sure the new and old chains are cleaned up.
9677 AddToWorklist(Token.getNode());
9679 // Don't add users to work list.
9680 return CombineTo(N, Token, false);
9684 // Try transforming N to an indexed store.
9685 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9686 return SDValue(N, 0);
9688 // FIXME: is there such a thing as a truncating indexed store?
9689 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9690 Value.getValueType().isInteger()) {
9691 // See if we can simplify the input to this truncstore with knowledge that
9692 // only the low bits are being used. For example:
9693 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9695 GetDemandedBits(Value,
9696 APInt::getLowBitsSet(
9697 Value.getValueType().getScalarType().getSizeInBits(),
9698 ST->getMemoryVT().getScalarType().getSizeInBits()));
9699 AddToWorklist(Value.getNode());
9700 if (Shorter.getNode())
9701 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9702 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9704 // Otherwise, see if we can simplify the operation with
9705 // SimplifyDemandedBits, which only works if the value has a single use.
9706 if (SimplifyDemandedBits(Value,
9707 APInt::getLowBitsSet(
9708 Value.getValueType().getScalarType().getSizeInBits(),
9709 ST->getMemoryVT().getScalarType().getSizeInBits())))
9710 return SDValue(N, 0);
9713 // If this is a load followed by a store to the same location, then the store
9715 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9716 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9717 ST->isUnindexed() && !ST->isVolatile() &&
9718 // There can't be any side effects between the load and store, such as
9720 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9721 // The store is dead, remove it.
9726 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9727 // truncating store. We can do this even if this is already a truncstore.
9728 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9729 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9730 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9731 ST->getMemoryVT())) {
9732 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9733 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9736 // Only perform this optimization before the types are legal, because we
9737 // don't want to perform this optimization on every DAGCombine invocation.
9739 bool EverChanged = false;
9742 // There can be multiple store sequences on the same chain.
9743 // Keep trying to merge store sequences until we are unable to do so
9744 // or until we merge the last store on the chain.
9745 bool Changed = MergeConsecutiveStores(ST);
9746 EverChanged |= Changed;
9747 if (!Changed) break;
9748 } while (ST->getOpcode() != ISD::DELETED_NODE);
9751 return SDValue(N, 0);
9754 return ReduceLoadOpStoreWidth(N);
9757 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9758 SDValue InVec = N->getOperand(0);
9759 SDValue InVal = N->getOperand(1);
9760 SDValue EltNo = N->getOperand(2);
9763 // If the inserted element is an UNDEF, just use the input vector.
9764 if (InVal.getOpcode() == ISD::UNDEF)
9767 EVT VT = InVec.getValueType();
9769 // If we can't generate a legal BUILD_VECTOR, exit
9770 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9773 // Check that we know which element is being inserted
9774 if (!isa<ConstantSDNode>(EltNo))
9776 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9778 // Canonicalize insert_vector_elt dag nodes.
9780 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9781 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9783 // Do this only if the child insert_vector node has one use; also
9784 // do this only if indices are both constants and Idx1 < Idx0.
9785 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9786 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9788 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9789 if (Elt < OtherElt) {
9791 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9792 InVec.getOperand(0), InVal, EltNo);
9793 AddToWorklist(NewOp.getNode());
9794 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9795 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9799 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9800 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9802 SmallVector<SDValue, 8> Ops;
9803 // Do not combine these two vectors if the output vector will not replace
9804 // the input vector.
9805 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9806 Ops.append(InVec.getNode()->op_begin(),
9807 InVec.getNode()->op_end());
9808 } else if (InVec.getOpcode() == ISD::UNDEF) {
9809 unsigned NElts = VT.getVectorNumElements();
9810 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9815 // Insert the element
9816 if (Elt < Ops.size()) {
9817 // All the operands of BUILD_VECTOR must have the same type;
9818 // we enforce that here.
9819 EVT OpVT = Ops[0].getValueType();
9820 if (InVal.getValueType() != OpVT)
9821 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9822 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9823 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9827 // Return the new vector
9828 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9831 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9832 // (vextract (scalar_to_vector val, 0) -> val
9833 SDValue InVec = N->getOperand(0);
9834 EVT VT = InVec.getValueType();
9835 EVT NVT = N->getValueType(0);
9837 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9838 // Check if the result type doesn't match the inserted element type. A
9839 // SCALAR_TO_VECTOR may truncate the inserted element and the
9840 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9841 SDValue InOp = InVec.getOperand(0);
9842 if (InOp.getValueType() != NVT) {
9843 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9844 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9849 SDValue EltNo = N->getOperand(1);
9850 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9852 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9853 // We only perform this optimization before the op legalization phase because
9854 // we may introduce new vector instructions which are not backed by TD
9855 // patterns. For example on AVX, extracting elements from a wide vector
9856 // without using extract_subvector. However, if we can find an underlying
9857 // scalar value, then we can always use that.
9858 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9860 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9861 int NumElem = VT.getVectorNumElements();
9862 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9863 // Find the new index to extract from.
9864 int OrigElt = SVOp->getMaskElt(Elt);
9866 // Extracting an undef index is undef.
9868 return DAG.getUNDEF(NVT);
9870 // Select the right vector half to extract from.
9872 if (OrigElt < NumElem) {
9873 SVInVec = InVec->getOperand(0);
9875 SVInVec = InVec->getOperand(1);
9879 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9880 SDValue InOp = SVInVec.getOperand(OrigElt);
9881 if (InOp.getValueType() != NVT) {
9882 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9883 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9889 // FIXME: We should handle recursing on other vector shuffles and
9890 // scalar_to_vector here as well.
9892 if (!LegalOperations) {
9893 EVT IndexTy = TLI.getVectorIdxTy();
9894 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9895 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9899 // Perform only after legalization to ensure build_vector / vector_shuffle
9900 // optimizations have already been done.
9901 if (!LegalOperations) return SDValue();
9903 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9904 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9905 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9908 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9909 bool NewLoad = false;
9910 bool BCNumEltsChanged = false;
9911 EVT ExtVT = VT.getVectorElementType();
9914 // If the result of load has to be truncated, then it's not necessarily
9916 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9919 if (InVec.getOpcode() == ISD::BITCAST) {
9920 // Don't duplicate a load with other uses.
9921 if (!InVec.hasOneUse())
9924 EVT BCVT = InVec.getOperand(0).getValueType();
9925 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9927 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9928 BCNumEltsChanged = true;
9929 InVec = InVec.getOperand(0);
9930 ExtVT = BCVT.getVectorElementType();
9934 LoadSDNode *LN0 = nullptr;
9935 const ShuffleVectorSDNode *SVN = nullptr;
9936 if (ISD::isNormalLoad(InVec.getNode())) {
9937 LN0 = cast<LoadSDNode>(InVec);
9938 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9939 InVec.getOperand(0).getValueType() == ExtVT &&
9940 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9941 // Don't duplicate a load with other uses.
9942 if (!InVec.hasOneUse())
9945 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9946 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9947 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9949 // (load $addr+1*size)
9951 // Don't duplicate a load with other uses.
9952 if (!InVec.hasOneUse())
9955 // If the bit convert changed the number of elements, it is unsafe
9956 // to examine the mask.
9957 if (BCNumEltsChanged)
9960 // Select the input vector, guarding against out of range extract vector.
9961 unsigned NumElems = VT.getVectorNumElements();
9962 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9963 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9965 if (InVec.getOpcode() == ISD::BITCAST) {
9966 // Don't duplicate a load with other uses.
9967 if (!InVec.hasOneUse())
9970 InVec = InVec.getOperand(0);
9972 if (ISD::isNormalLoad(InVec.getNode())) {
9973 LN0 = cast<LoadSDNode>(InVec);
9974 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9978 // Make sure we found a non-volatile load and the extractelement is
9980 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9983 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9985 return DAG.getUNDEF(LVT);
9987 unsigned Align = LN0->getAlignment();
9989 // Check the resultant load doesn't need a higher alignment than the
9993 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9995 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
10001 SDValue NewPtr = LN0->getBasePtr();
10002 unsigned PtrOff = 0;
10005 PtrOff = LVT.getSizeInBits() * Elt / 8;
10006 EVT PtrType = NewPtr.getValueType();
10007 if (TLI.isBigEndian())
10008 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
10009 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
10010 DAG.getConstant(PtrOff, PtrType));
10013 // The replacement we need to do here is a little tricky: we need to
10014 // replace an extractelement of a load with a load.
10015 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10016 // Note that this replacement assumes that the extractvalue is the only
10017 // use of the load; that's okay because we don't want to perform this
10018 // transformation in other cases anyway.
10021 if (NVT.bitsGT(LVT)) {
10022 // If the result type of vextract is wider than the load, then issue an
10023 // extending load instead.
10024 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
10025 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
10026 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
10027 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
10028 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
10029 Align, LN0->getAAInfo());
10030 Chain = Load.getValue(1);
10032 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
10033 LN0->getPointerInfo().getWithOffset(PtrOff),
10034 LN0->isVolatile(), LN0->isNonTemporal(),
10035 LN0->isInvariant(), Align, LN0->getAAInfo());
10036 Chain = Load.getValue(1);
10037 if (NVT.bitsLT(LVT))
10038 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
10040 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10042 WorklistRemover DeadNodes(*this);
10043 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10044 SDValue To[] = { Load, Chain };
10045 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10046 // Since we're explcitly calling ReplaceAllUses, add the new node to the
10047 // worklist explicitly as well.
10048 AddToWorklist(Load.getNode());
10049 AddUsersToWorklist(Load.getNode()); // Add users too
10050 // Make sure to revisit this node to clean it up; it will usually be dead.
10052 return SDValue(N, 0);
10058 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10059 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10060 // We perform this optimization post type-legalization because
10061 // the type-legalizer often scalarizes integer-promoted vectors.
10062 // Performing this optimization before may create bit-casts which
10063 // will be type-legalized to complex code sequences.
10064 // We perform this optimization only before the operation legalizer because we
10065 // may introduce illegal operations.
10066 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10069 unsigned NumInScalars = N->getNumOperands();
10071 EVT VT = N->getValueType(0);
10073 // Check to see if this is a BUILD_VECTOR of a bunch of values
10074 // which come from any_extend or zero_extend nodes. If so, we can create
10075 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10076 // optimizations. We do not handle sign-extend because we can't fill the sign
10078 EVT SourceType = MVT::Other;
10079 bool AllAnyExt = true;
10081 for (unsigned i = 0; i != NumInScalars; ++i) {
10082 SDValue In = N->getOperand(i);
10083 // Ignore undef inputs.
10084 if (In.getOpcode() == ISD::UNDEF) continue;
10086 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10087 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10089 // Abort if the element is not an extension.
10090 if (!ZeroExt && !AnyExt) {
10091 SourceType = MVT::Other;
10095 // The input is a ZeroExt or AnyExt. Check the original type.
10096 EVT InTy = In.getOperand(0).getValueType();
10098 // Check that all of the widened source types are the same.
10099 if (SourceType == MVT::Other)
10102 else if (InTy != SourceType) {
10103 // Multiple income types. Abort.
10104 SourceType = MVT::Other;
10108 // Check if all of the extends are ANY_EXTENDs.
10109 AllAnyExt &= AnyExt;
10112 // In order to have valid types, all of the inputs must be extended from the
10113 // same source type and all of the inputs must be any or zero extend.
10114 // Scalar sizes must be a power of two.
10115 EVT OutScalarTy = VT.getScalarType();
10116 bool ValidTypes = SourceType != MVT::Other &&
10117 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10118 isPowerOf2_32(SourceType.getSizeInBits());
10120 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10121 // turn into a single shuffle instruction.
10125 bool isLE = TLI.isLittleEndian();
10126 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10127 assert(ElemRatio > 1 && "Invalid element size ratio");
10128 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10129 DAG.getConstant(0, SourceType);
10131 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10132 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10134 // Populate the new build_vector
10135 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10136 SDValue Cast = N->getOperand(i);
10137 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10138 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10139 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10141 if (Cast.getOpcode() == ISD::UNDEF)
10142 In = DAG.getUNDEF(SourceType);
10144 In = Cast->getOperand(0);
10145 unsigned Index = isLE ? (i * ElemRatio) :
10146 (i * ElemRatio + (ElemRatio - 1));
10148 assert(Index < Ops.size() && "Invalid index");
10152 // The type of the new BUILD_VECTOR node.
10153 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10154 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10155 "Invalid vector size");
10156 // Check if the new vector type is legal.
10157 if (!isTypeLegal(VecVT)) return SDValue();
10159 // Make the new BUILD_VECTOR.
10160 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10162 // The new BUILD_VECTOR node has the potential to be further optimized.
10163 AddToWorklist(BV.getNode());
10164 // Bitcast to the desired type.
10165 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10168 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10169 EVT VT = N->getValueType(0);
10171 unsigned NumInScalars = N->getNumOperands();
10174 EVT SrcVT = MVT::Other;
10175 unsigned Opcode = ISD::DELETED_NODE;
10176 unsigned NumDefs = 0;
10178 for (unsigned i = 0; i != NumInScalars; ++i) {
10179 SDValue In = N->getOperand(i);
10180 unsigned Opc = In.getOpcode();
10182 if (Opc == ISD::UNDEF)
10185 // If all scalar values are floats and converted from integers.
10186 if (Opcode == ISD::DELETED_NODE &&
10187 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10194 EVT InVT = In.getOperand(0).getValueType();
10196 // If all scalar values are typed differently, bail out. It's chosen to
10197 // simplify BUILD_VECTOR of integer types.
10198 if (SrcVT == MVT::Other)
10205 // If the vector has just one element defined, it's not worth to fold it into
10206 // a vectorized one.
10210 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10211 && "Should only handle conversion from integer to float.");
10212 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10214 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10216 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10219 SmallVector<SDValue, 8> Opnds;
10220 for (unsigned i = 0; i != NumInScalars; ++i) {
10221 SDValue In = N->getOperand(i);
10223 if (In.getOpcode() == ISD::UNDEF)
10224 Opnds.push_back(DAG.getUNDEF(SrcVT));
10226 Opnds.push_back(In.getOperand(0));
10228 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10229 AddToWorklist(BV.getNode());
10231 return DAG.getNode(Opcode, dl, VT, BV);
10234 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10235 unsigned NumInScalars = N->getNumOperands();
10237 EVT VT = N->getValueType(0);
10239 // A vector built entirely of undefs is undef.
10240 if (ISD::allOperandsUndef(N))
10241 return DAG.getUNDEF(VT);
10243 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10247 V = reduceBuildVecConvertToConvertBuildVec(N);
10251 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10252 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10253 // at most two distinct vectors, turn this into a shuffle node.
10255 // May only combine to shuffle after legalize if shuffle is legal.
10256 if (LegalOperations &&
10257 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10260 SDValue VecIn1, VecIn2;
10261 for (unsigned i = 0; i != NumInScalars; ++i) {
10262 // Ignore undef inputs.
10263 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10265 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10266 // constant index, bail out.
10267 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10268 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10269 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10273 // We allow up to two distinct input vectors.
10274 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10275 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10278 if (!VecIn1.getNode()) {
10279 VecIn1 = ExtractedFromVec;
10280 } else if (!VecIn2.getNode()) {
10281 VecIn2 = ExtractedFromVec;
10283 // Too many inputs.
10284 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10289 // If everything is good, we can make a shuffle operation.
10290 if (VecIn1.getNode()) {
10291 SmallVector<int, 8> Mask;
10292 for (unsigned i = 0; i != NumInScalars; ++i) {
10293 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10294 Mask.push_back(-1);
10298 // If extracting from the first vector, just use the index directly.
10299 SDValue Extract = N->getOperand(i);
10300 SDValue ExtVal = Extract.getOperand(1);
10301 if (Extract.getOperand(0) == VecIn1) {
10302 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10303 if (ExtIndex > VT.getVectorNumElements())
10306 Mask.push_back(ExtIndex);
10310 // Otherwise, use InIdx + VecSize
10311 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10312 Mask.push_back(Idx+NumInScalars);
10315 // We can't generate a shuffle node with mismatched input and output types.
10316 // Attempt to transform a single input vector to the correct type.
10317 if ((VT != VecIn1.getValueType())) {
10318 // We don't support shuffeling between TWO values of different types.
10319 if (VecIn2.getNode())
10322 // We only support widening of vectors which are half the size of the
10323 // output registers. For example XMM->YMM widening on X86 with AVX.
10324 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10327 // If the input vector type has a different base type to the output
10328 // vector type, bail out.
10329 if (VecIn1.getValueType().getVectorElementType() !=
10330 VT.getVectorElementType())
10333 // Widen the input vector by adding undef values.
10334 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10335 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10338 // If VecIn2 is unused then change it to undef.
10339 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10341 // Check that we were able to transform all incoming values to the same
10343 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10344 VecIn1.getValueType() != VT)
10347 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10348 if (!isTypeLegal(VT))
10351 // Return the new VECTOR_SHUFFLE node.
10355 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10361 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10362 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10363 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10364 // inputs come from at most two distinct vectors, turn this into a shuffle
10367 // If we only have one input vector, we don't need to do any concatenation.
10368 if (N->getNumOperands() == 1)
10369 return N->getOperand(0);
10371 // Check if all of the operands are undefs.
10372 EVT VT = N->getValueType(0);
10373 if (ISD::allOperandsUndef(N))
10374 return DAG.getUNDEF(VT);
10376 // Optimize concat_vectors where one of the vectors is undef.
10377 if (N->getNumOperands() == 2 &&
10378 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10379 SDValue In = N->getOperand(0);
10380 assert(In.getValueType().isVector() && "Must concat vectors");
10382 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10383 if (In->getOpcode() == ISD::BITCAST &&
10384 !In->getOperand(0)->getValueType(0).isVector()) {
10385 SDValue Scalar = In->getOperand(0);
10386 EVT SclTy = Scalar->getValueType(0);
10388 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10391 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10392 VT.getSizeInBits() / SclTy.getSizeInBits());
10393 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10396 SDLoc dl = SDLoc(N);
10397 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10398 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10402 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10403 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10404 if (N->getNumOperands() == 2 &&
10405 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10406 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10407 EVT VT = N->getValueType(0);
10408 SDValue N0 = N->getOperand(0);
10409 SDValue N1 = N->getOperand(1);
10410 SmallVector<SDValue, 8> Opnds;
10411 unsigned BuildVecNumElts = N0.getNumOperands();
10413 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10414 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10415 if (SclTy0.isFloatingPoint()) {
10416 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10417 Opnds.push_back(N0.getOperand(i));
10418 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10419 Opnds.push_back(N1.getOperand(i));
10421 // If BUILD_VECTOR are from built from integer, they may have different
10422 // operand types. Get the smaller type and truncate all operands to it.
10423 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10424 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10425 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10426 N0.getOperand(i)));
10427 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10428 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10429 N1.getOperand(i)));
10432 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10435 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10436 // nodes often generate nop CONCAT_VECTOR nodes.
10437 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10438 // place the incoming vectors at the exact same location.
10439 SDValue SingleSource = SDValue();
10440 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10442 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10443 SDValue Op = N->getOperand(i);
10445 if (Op.getOpcode() == ISD::UNDEF)
10448 // Check if this is the identity extract:
10449 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10452 // Find the single incoming vector for the extract_subvector.
10453 if (SingleSource.getNode()) {
10454 if (Op.getOperand(0) != SingleSource)
10457 SingleSource = Op.getOperand(0);
10459 // Check the source type is the same as the type of the result.
10460 // If not, this concat may extend the vector, so we can not
10461 // optimize it away.
10462 if (SingleSource.getValueType() != N->getValueType(0))
10466 unsigned IdentityIndex = i * PartNumElem;
10467 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10468 // The extract index must be constant.
10472 // Check that we are reading from the identity index.
10473 if (CS->getZExtValue() != IdentityIndex)
10477 if (SingleSource.getNode())
10478 return SingleSource;
10483 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10484 EVT NVT = N->getValueType(0);
10485 SDValue V = N->getOperand(0);
10487 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10489 // (extract_subvec (concat V1, V2, ...), i)
10492 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10494 if (V->getOperand(0).getValueType() != NVT)
10496 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10497 unsigned NumElems = NVT.getVectorNumElements();
10498 assert((Idx % NumElems) == 0 &&
10499 "IDX in concat is not a multiple of the result vector length.");
10500 return V->getOperand(Idx / NumElems);
10504 if (V->getOpcode() == ISD::BITCAST)
10505 V = V.getOperand(0);
10507 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10509 // Handle only simple case where vector being inserted and vector
10510 // being extracted are of same type, and are half size of larger vectors.
10511 EVT BigVT = V->getOperand(0).getValueType();
10512 EVT SmallVT = V->getOperand(1).getValueType();
10513 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10516 // Only handle cases where both indexes are constants with the same type.
10517 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10518 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10520 if (InsIdx && ExtIdx &&
10521 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10522 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10524 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10526 // indices are equal or bit offsets are equal => V1
10527 // otherwise => (extract_subvec V1, ExtIdx)
10528 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10529 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10530 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10531 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10532 DAG.getNode(ISD::BITCAST, dl,
10533 N->getOperand(0).getValueType(),
10534 V->getOperand(0)), N->getOperand(1));
10541 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10542 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10543 EVT VT = N->getValueType(0);
10544 unsigned NumElts = VT.getVectorNumElements();
10546 SDValue N0 = N->getOperand(0);
10547 SDValue N1 = N->getOperand(1);
10548 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10550 SmallVector<SDValue, 4> Ops;
10551 EVT ConcatVT = N0.getOperand(0).getValueType();
10552 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10553 unsigned NumConcats = NumElts / NumElemsPerConcat;
10555 // Look at every vector that's inserted. We're looking for exact
10556 // subvector-sized copies from a concatenated vector
10557 for (unsigned I = 0; I != NumConcats; ++I) {
10558 // Make sure we're dealing with a copy.
10559 unsigned Begin = I * NumElemsPerConcat;
10560 bool AllUndef = true, NoUndef = true;
10561 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10562 if (SVN->getMaskElt(J) >= 0)
10569 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10572 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10573 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10576 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10577 if (FirstElt < N0.getNumOperands())
10578 Ops.push_back(N0.getOperand(FirstElt));
10580 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10582 } else if (AllUndef) {
10583 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10584 } else { // Mixed with general masks and undefs, can't do optimization.
10589 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10592 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10593 EVT VT = N->getValueType(0);
10594 unsigned NumElts = VT.getVectorNumElements();
10596 SDValue N0 = N->getOperand(0);
10597 SDValue N1 = N->getOperand(1);
10599 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10601 // Canonicalize shuffle undef, undef -> undef
10602 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10603 return DAG.getUNDEF(VT);
10605 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10607 // Canonicalize shuffle v, v -> v, undef
10609 SmallVector<int, 8> NewMask;
10610 for (unsigned i = 0; i != NumElts; ++i) {
10611 int Idx = SVN->getMaskElt(i);
10612 if (Idx >= (int)NumElts) Idx -= NumElts;
10613 NewMask.push_back(Idx);
10615 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10619 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10620 if (N0.getOpcode() == ISD::UNDEF) {
10621 SmallVector<int, 8> NewMask;
10622 for (unsigned i = 0; i != NumElts; ++i) {
10623 int Idx = SVN->getMaskElt(i);
10625 if (Idx >= (int)NumElts)
10628 Idx = -1; // remove reference to lhs
10630 NewMask.push_back(Idx);
10632 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10636 // Remove references to rhs if it is undef
10637 if (N1.getOpcode() == ISD::UNDEF) {
10638 bool Changed = false;
10639 SmallVector<int, 8> NewMask;
10640 for (unsigned i = 0; i != NumElts; ++i) {
10641 int Idx = SVN->getMaskElt(i);
10642 if (Idx >= (int)NumElts) {
10646 NewMask.push_back(Idx);
10649 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10652 // If it is a splat, check if the argument vector is another splat or a
10653 // build_vector with all scalar elements the same.
10654 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10655 SDNode *V = N0.getNode();
10657 // If this is a bit convert that changes the element type of the vector but
10658 // not the number of vector elements, look through it. Be careful not to
10659 // look though conversions that change things like v4f32 to v2f64.
10660 if (V->getOpcode() == ISD::BITCAST) {
10661 SDValue ConvInput = V->getOperand(0);
10662 if (ConvInput.getValueType().isVector() &&
10663 ConvInput.getValueType().getVectorNumElements() == NumElts)
10664 V = ConvInput.getNode();
10667 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10668 assert(V->getNumOperands() == NumElts &&
10669 "BUILD_VECTOR has wrong number of operands");
10671 bool AllSame = true;
10672 for (unsigned i = 0; i != NumElts; ++i) {
10673 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10674 Base = V->getOperand(i);
10678 // Splat of <u, u, u, u>, return <u, u, u, u>
10679 if (!Base.getNode())
10681 for (unsigned i = 0; i != NumElts; ++i) {
10682 if (V->getOperand(i) != Base) {
10687 // Splat of <x, x, x, x>, return <x, x, x, x>
10693 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10694 Level < AfterLegalizeVectorOps &&
10695 (N1.getOpcode() == ISD::UNDEF ||
10696 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10697 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10698 SDValue V = partitionShuffleOfConcats(N, DAG);
10704 // If this shuffle node is simply a swizzle of another shuffle node,
10705 // then try to simplify it.
10706 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10707 N1.getOpcode() == ISD::UNDEF) {
10709 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10711 // The incoming shuffle must be of the same type as the result of the
10712 // current shuffle.
10713 assert(OtherSV->getOperand(0).getValueType() == VT &&
10714 "Shuffle types don't match");
10716 SmallVector<int, 4> Mask;
10717 // Compute the combined shuffle mask.
10718 for (unsigned i = 0; i != NumElts; ++i) {
10719 int Idx = SVN->getMaskElt(i);
10720 assert(Idx < (int)NumElts && "Index references undef operand");
10721 // Next, this index comes from the first value, which is the incoming
10722 // shuffle. Adopt the incoming index.
10724 Idx = OtherSV->getMaskElt(Idx);
10725 Mask.push_back(Idx);
10728 bool CommuteOperands = false;
10729 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10730 // To be valid, the combine shuffle mask should only reference elements
10731 // from one of the two vectors in input to the inner shufflevector.
10732 bool IsValidMask = true;
10733 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10734 // See if the combined mask only reference undefs or elements coming
10735 // from the first shufflevector operand.
10736 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10738 if (!IsValidMask) {
10739 IsValidMask = true;
10740 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10741 // Check that all the elements come from the second shuffle operand.
10742 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10743 CommuteOperands = IsValidMask;
10746 // Early exit if the combined shuffle mask is not valid.
10751 // See if this pair of shuffles can be safely folded according to either
10752 // of the following rules:
10753 // shuffle(shuffle(x, y), undef) -> x
10754 // shuffle(shuffle(x, undef), undef) -> x
10755 // shuffle(shuffle(x, y), undef) -> y
10756 bool IsIdentityMask = true;
10757 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10758 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10763 // The combined shuffle must map each index to itself.
10764 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10767 if (IsIdentityMask) {
10768 if (CommuteOperands)
10769 // optimize shuffle(shuffle(x, y), undef) -> y.
10770 return OtherSV->getOperand(1);
10772 // optimize shuffle(shuffle(x, undef), undef) -> x
10773 // optimize shuffle(shuffle(x, y), undef) -> x
10774 return OtherSV->getOperand(0);
10777 // It may still be beneficial to combine the two shuffles if the
10778 // resulting shuffle is legal.
10779 if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10780 if (!CommuteOperands)
10781 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10782 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10783 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10786 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10787 return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10792 // Canonicalize shuffles according to rules:
10793 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10794 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10795 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10796 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10797 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10798 TLI.isTypeLegal(VT)) {
10799 // The incoming shuffle must be of the same type as the result of the
10800 // current shuffle.
10801 assert(N1->getOperand(0).getValueType() == VT &&
10802 "Shuffle types don't match");
10804 SDValue SV0 = N1->getOperand(0);
10805 SDValue SV1 = N1->getOperand(1);
10806 bool HasSameOp0 = N0 == SV0;
10807 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10808 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10809 // Commute the operands of this shuffle so that next rule
10811 return DAG.getCommutedVectorShuffle(*SVN);
10814 // Try to fold according to rules:
10815 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10816 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10817 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10818 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10819 // Don't try to fold shuffles with illegal type.
10820 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10821 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10822 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10824 // The incoming shuffle must be of the same type as the result of the
10825 // current shuffle.
10826 assert(OtherSV->getOperand(0).getValueType() == VT &&
10827 "Shuffle types don't match");
10829 SDValue SV0 = OtherSV->getOperand(0);
10830 SDValue SV1 = OtherSV->getOperand(1);
10831 bool HasSameOp0 = N1 == SV0;
10832 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10833 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10837 SmallVector<int, 4> Mask;
10838 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10839 // operand, and SV1 as the second operand.
10840 for (unsigned i = 0; i != NumElts; ++i) {
10841 int Idx = SVN->getMaskElt(i);
10843 // Propagate Undef.
10844 Mask.push_back(Idx);
10848 if (Idx < (int)NumElts) {
10849 Idx = OtherSV->getMaskElt(Idx);
10850 if (IsSV1Undef && Idx >= (int) NumElts)
10851 Idx = -1; // Propagate Undef.
10853 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10855 Mask.push_back(Idx);
10858 // Avoid introducing shuffles with illegal mask.
10859 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10861 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10862 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10863 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10864 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10871 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10872 SDValue N0 = N->getOperand(0);
10873 SDValue N2 = N->getOperand(2);
10875 // If the input vector is a concatenation, and the insert replaces
10876 // one of the halves, we can optimize into a single concat_vectors.
10877 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10878 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10879 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10880 EVT VT = N->getValueType(0);
10882 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10883 // (concat_vectors Z, Y)
10885 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10886 N->getOperand(1), N0.getOperand(1));
10888 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10889 // (concat_vectors X, Z)
10890 if (InsIdx == VT.getVectorNumElements()/2)
10891 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10892 N0.getOperand(0), N->getOperand(1));
10898 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10899 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10900 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10901 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10902 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10903 EVT VT = N->getValueType(0);
10905 SDValue LHS = N->getOperand(0);
10906 SDValue RHS = N->getOperand(1);
10907 if (N->getOpcode() == ISD::AND) {
10908 if (RHS.getOpcode() == ISD::BITCAST)
10909 RHS = RHS.getOperand(0);
10910 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10911 SmallVector<int, 8> Indices;
10912 unsigned NumElts = RHS.getNumOperands();
10913 for (unsigned i = 0; i != NumElts; ++i) {
10914 SDValue Elt = RHS.getOperand(i);
10915 if (!isa<ConstantSDNode>(Elt))
10918 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10919 Indices.push_back(i);
10920 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10921 Indices.push_back(NumElts);
10926 // Let's see if the target supports this vector_shuffle.
10927 EVT RVT = RHS.getValueType();
10928 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10931 // Return the new VECTOR_SHUFFLE node.
10932 EVT EltVT = RVT.getVectorElementType();
10933 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10934 DAG.getConstant(0, EltVT));
10935 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10936 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10937 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10938 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10945 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10946 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10947 assert(N->getValueType(0).isVector() &&
10948 "SimplifyVBinOp only works on vectors!");
10950 SDValue LHS = N->getOperand(0);
10951 SDValue RHS = N->getOperand(1);
10952 SDValue Shuffle = XformToShuffleWithZero(N);
10953 if (Shuffle.getNode()) return Shuffle;
10955 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10957 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10958 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10959 // Check if both vectors are constants. If not bail out.
10960 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10961 cast<BuildVectorSDNode>(RHS)->isConstant()))
10964 SmallVector<SDValue, 8> Ops;
10965 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10966 SDValue LHSOp = LHS.getOperand(i);
10967 SDValue RHSOp = RHS.getOperand(i);
10969 // Can't fold divide by zero.
10970 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10971 N->getOpcode() == ISD::FDIV) {
10972 if ((RHSOp.getOpcode() == ISD::Constant &&
10973 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10974 (RHSOp.getOpcode() == ISD::ConstantFP &&
10975 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10979 EVT VT = LHSOp.getValueType();
10980 EVT RVT = RHSOp.getValueType();
10982 // Integer BUILD_VECTOR operands may have types larger than the element
10983 // size (e.g., when the element type is not legal). Prior to type
10984 // legalization, the types may not match between the two BUILD_VECTORS.
10985 // Truncate one of the operands to make them match.
10986 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10987 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10989 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10993 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10995 if (FoldOp.getOpcode() != ISD::UNDEF &&
10996 FoldOp.getOpcode() != ISD::Constant &&
10997 FoldOp.getOpcode() != ISD::ConstantFP)
10999 Ops.push_back(FoldOp);
11000 AddToWorklist(FoldOp.getNode());
11003 if (Ops.size() == LHS.getNumOperands())
11004 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11007 // Type legalization might introduce new shuffles in the DAG.
11008 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11009 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11010 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11011 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11012 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11013 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11014 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11015 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11017 if (SVN0->getMask().equals(SVN1->getMask())) {
11018 EVT VT = N->getValueType(0);
11019 SDValue UndefVector = LHS.getOperand(1);
11020 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11021 LHS.getOperand(0), RHS.getOperand(0));
11022 AddUsersToWorklist(N);
11023 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11024 &SVN0->getMask()[0]);
11031 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11032 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11033 assert(N->getValueType(0).isVector() &&
11034 "SimplifyVUnaryOp only works on vectors!");
11036 SDValue N0 = N->getOperand(0);
11038 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11041 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11042 SmallVector<SDValue, 8> Ops;
11043 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11044 SDValue Op = N0.getOperand(i);
11045 if (Op.getOpcode() != ISD::UNDEF &&
11046 Op.getOpcode() != ISD::ConstantFP)
11048 EVT EltVT = Op.getValueType();
11049 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11050 if (FoldOp.getOpcode() != ISD::UNDEF &&
11051 FoldOp.getOpcode() != ISD::ConstantFP)
11053 Ops.push_back(FoldOp);
11054 AddToWorklist(FoldOp.getNode());
11057 if (Ops.size() != N0.getNumOperands())
11060 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11063 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11064 SDValue N1, SDValue N2){
11065 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11067 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11068 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11070 // If we got a simplified select_cc node back from SimplifySelectCC, then
11071 // break it down into a new SETCC node, and a new SELECT node, and then return
11072 // the SELECT node, since we were called with a SELECT node.
11073 if (SCC.getNode()) {
11074 // Check to see if we got a select_cc back (to turn into setcc/select).
11075 // Otherwise, just return whatever node we got back, like fabs.
11076 if (SCC.getOpcode() == ISD::SELECT_CC) {
11077 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11079 SCC.getOperand(0), SCC.getOperand(1),
11080 SCC.getOperand(4));
11081 AddToWorklist(SETCC.getNode());
11082 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11083 SCC.getOperand(2), SCC.getOperand(3), SETCC);
11091 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11092 /// are the two values being selected between, see if we can simplify the
11093 /// select. Callers of this should assume that TheSelect is deleted if this
11094 /// returns true. As such, they should return the appropriate thing (e.g. the
11095 /// node) back to the top-level of the DAG combiner loop to avoid it being
11097 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11100 // Cannot simplify select with vector condition
11101 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11103 // If this is a select from two identical things, try to pull the operation
11104 // through the select.
11105 if (LHS.getOpcode() != RHS.getOpcode() ||
11106 !LHS.hasOneUse() || !RHS.hasOneUse())
11109 // If this is a load and the token chain is identical, replace the select
11110 // of two loads with a load through a select of the address to load from.
11111 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11112 // constants have been dropped into the constant pool.
11113 if (LHS.getOpcode() == ISD::LOAD) {
11114 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11115 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11117 // Token chains must be identical.
11118 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11119 // Do not let this transformation reduce the number of volatile loads.
11120 LLD->isVolatile() || RLD->isVolatile() ||
11121 // If this is an EXTLOAD, the VT's must match.
11122 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11123 // If this is an EXTLOAD, the kind of extension must match.
11124 (LLD->getExtensionType() != RLD->getExtensionType() &&
11125 // The only exception is if one of the extensions is anyext.
11126 LLD->getExtensionType() != ISD::EXTLOAD &&
11127 RLD->getExtensionType() != ISD::EXTLOAD) ||
11128 // FIXME: this discards src value information. This is
11129 // over-conservative. It would be beneficial to be able to remember
11130 // both potential memory locations. Since we are discarding
11131 // src value info, don't do the transformation if the memory
11132 // locations are not in the default address space.
11133 LLD->getPointerInfo().getAddrSpace() != 0 ||
11134 RLD->getPointerInfo().getAddrSpace() != 0 ||
11135 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11136 LLD->getBasePtr().getValueType()))
11139 // Check that the select condition doesn't reach either load. If so,
11140 // folding this will induce a cycle into the DAG. If not, this is safe to
11141 // xform, so create a select of the addresses.
11143 if (TheSelect->getOpcode() == ISD::SELECT) {
11144 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11145 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11146 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11148 // The loads must not depend on one another.
11149 if (LLD->isPredecessorOf(RLD) ||
11150 RLD->isPredecessorOf(LLD))
11152 Addr = DAG.getSelect(SDLoc(TheSelect),
11153 LLD->getBasePtr().getValueType(),
11154 TheSelect->getOperand(0), LLD->getBasePtr(),
11155 RLD->getBasePtr());
11156 } else { // Otherwise SELECT_CC
11157 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11158 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11160 if ((LLD->hasAnyUseOfValue(1) &&
11161 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11162 (RLD->hasAnyUseOfValue(1) &&
11163 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11166 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11167 LLD->getBasePtr().getValueType(),
11168 TheSelect->getOperand(0),
11169 TheSelect->getOperand(1),
11170 LLD->getBasePtr(), RLD->getBasePtr(),
11171 TheSelect->getOperand(4));
11175 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11176 Load = DAG.getLoad(TheSelect->getValueType(0),
11178 // FIXME: Discards pointer and AA info.
11179 LLD->getChain(), Addr, MachinePointerInfo(),
11180 LLD->isVolatile(), LLD->isNonTemporal(),
11181 LLD->isInvariant(), LLD->getAlignment());
11183 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11184 RLD->getExtensionType() : LLD->getExtensionType(),
11186 TheSelect->getValueType(0),
11187 // FIXME: Discards pointer and AA info.
11188 LLD->getChain(), Addr, MachinePointerInfo(),
11189 LLD->getMemoryVT(), LLD->isVolatile(),
11190 LLD->isNonTemporal(), LLD->getAlignment());
11193 // Users of the select now use the result of the load.
11194 CombineTo(TheSelect, Load);
11196 // Users of the old loads now use the new load's chain. We know the
11197 // old-load value is dead now.
11198 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11199 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11206 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11207 /// where 'cond' is the comparison specified by CC.
11208 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11209 SDValue N2, SDValue N3,
11210 ISD::CondCode CC, bool NotExtCompare) {
11211 // (x ? y : y) -> y.
11212 if (N2 == N3) return N2;
11214 EVT VT = N2.getValueType();
11215 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11216 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11217 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11219 // Determine if the condition we're dealing with is constant
11220 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11221 N0, N1, CC, DL, false);
11222 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11223 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11225 // fold select_cc true, x, y -> x
11226 if (SCCC && !SCCC->isNullValue())
11228 // fold select_cc false, x, y -> y
11229 if (SCCC && SCCC->isNullValue())
11232 // Check to see if we can simplify the select into an fabs node
11233 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11234 // Allow either -0.0 or 0.0
11235 if (CFP->getValueAPF().isZero()) {
11236 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11237 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11238 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11239 N2 == N3.getOperand(0))
11240 return DAG.getNode(ISD::FABS, DL, VT, N0);
11242 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11243 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11244 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11245 N2.getOperand(0) == N3)
11246 return DAG.getNode(ISD::FABS, DL, VT, N3);
11250 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11251 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11252 // in it. This is a win when the constant is not otherwise available because
11253 // it replaces two constant pool loads with one. We only do this if the FP
11254 // type is known to be legal, because if it isn't, then we are before legalize
11255 // types an we want the other legalization to happen first (e.g. to avoid
11256 // messing with soft float) and if the ConstantFP is not legal, because if
11257 // it is legal, we may not need to store the FP constant in a constant pool.
11258 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11259 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11260 if (TLI.isTypeLegal(N2.getValueType()) &&
11261 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11262 TargetLowering::Legal &&
11263 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11264 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11265 // If both constants have multiple uses, then we won't need to do an
11266 // extra load, they are likely around in registers for other users.
11267 (TV->hasOneUse() || FV->hasOneUse())) {
11268 Constant *Elts[] = {
11269 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11270 const_cast<ConstantFP*>(TV->getConstantFPValue())
11272 Type *FPTy = Elts[0]->getType();
11273 const DataLayout &TD = *TLI.getDataLayout();
11275 // Create a ConstantArray of the two constants.
11276 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11277 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11278 TD.getPrefTypeAlignment(FPTy));
11279 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11281 // Get the offsets to the 0 and 1 element of the array so that we can
11282 // select between them.
11283 SDValue Zero = DAG.getIntPtrConstant(0);
11284 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11285 SDValue One = DAG.getIntPtrConstant(EltSize);
11287 SDValue Cond = DAG.getSetCC(DL,
11288 getSetCCResultType(N0.getValueType()),
11290 AddToWorklist(Cond.getNode());
11291 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11293 AddToWorklist(CstOffset.getNode());
11294 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11296 AddToWorklist(CPIdx.getNode());
11297 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11298 MachinePointerInfo::getConstantPool(), false,
11299 false, false, Alignment);
11304 // Check to see if we can perform the "gzip trick", transforming
11305 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11306 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11307 (N1C->isNullValue() || // (a < 0) ? b : 0
11308 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11309 EVT XType = N0.getValueType();
11310 EVT AType = N2.getValueType();
11311 if (XType.bitsGE(AType)) {
11312 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11313 // single-bit constant.
11314 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11315 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11316 ShCtV = XType.getSizeInBits()-ShCtV-1;
11317 SDValue ShCt = DAG.getConstant(ShCtV,
11318 getShiftAmountTy(N0.getValueType()));
11319 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11321 AddToWorklist(Shift.getNode());
11323 if (XType.bitsGT(AType)) {
11324 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11325 AddToWorklist(Shift.getNode());
11328 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11331 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11333 DAG.getConstant(XType.getSizeInBits()-1,
11334 getShiftAmountTy(N0.getValueType())));
11335 AddToWorklist(Shift.getNode());
11337 if (XType.bitsGT(AType)) {
11338 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11339 AddToWorklist(Shift.getNode());
11342 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11346 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11347 // where y is has a single bit set.
11348 // A plaintext description would be, we can turn the SELECT_CC into an AND
11349 // when the condition can be materialized as an all-ones register. Any
11350 // single bit-test can be materialized as an all-ones register with
11351 // shift-left and shift-right-arith.
11352 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11353 N0->getValueType(0) == VT &&
11354 N1C && N1C->isNullValue() &&
11355 N2C && N2C->isNullValue()) {
11356 SDValue AndLHS = N0->getOperand(0);
11357 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11358 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11359 // Shift the tested bit over the sign bit.
11360 APInt AndMask = ConstAndRHS->getAPIntValue();
11362 DAG.getConstant(AndMask.countLeadingZeros(),
11363 getShiftAmountTy(AndLHS.getValueType()));
11364 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11366 // Now arithmetic right shift it all the way over, so the result is either
11367 // all-ones, or zero.
11369 DAG.getConstant(AndMask.getBitWidth()-1,
11370 getShiftAmountTy(Shl.getValueType()));
11371 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11373 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11377 // fold select C, 16, 0 -> shl C, 4
11378 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11379 TLI.getBooleanContents(N0.getValueType()) ==
11380 TargetLowering::ZeroOrOneBooleanContent) {
11382 // If the caller doesn't want us to simplify this into a zext of a compare,
11384 if (NotExtCompare && N2C->getAPIntValue() == 1)
11387 // Get a SetCC of the condition
11388 // NOTE: Don't create a SETCC if it's not legal on this target.
11389 if (!LegalOperations ||
11390 TLI.isOperationLegal(ISD::SETCC,
11391 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11393 // cast from setcc result type to select result type
11395 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11397 if (N2.getValueType().bitsLT(SCC.getValueType()))
11398 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11399 N2.getValueType());
11401 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11402 N2.getValueType(), SCC);
11404 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11405 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11406 N2.getValueType(), SCC);
11409 AddToWorklist(SCC.getNode());
11410 AddToWorklist(Temp.getNode());
11412 if (N2C->getAPIntValue() == 1)
11415 // shl setcc result by log2 n2c
11416 return DAG.getNode(
11417 ISD::SHL, DL, N2.getValueType(), Temp,
11418 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11419 getShiftAmountTy(Temp.getValueType())));
11423 // Check to see if this is the equivalent of setcc
11424 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11425 // otherwise, go ahead with the folds.
11426 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11427 EVT XType = N0.getValueType();
11428 if (!LegalOperations ||
11429 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11430 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11431 if (Res.getValueType() != VT)
11432 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11436 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11437 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11438 (!LegalOperations ||
11439 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11440 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11441 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11442 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11443 getShiftAmountTy(Ctlz.getValueType())));
11445 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11446 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11447 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11448 XType, DAG.getConstant(0, XType), N0);
11449 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11450 return DAG.getNode(ISD::SRL, DL, XType,
11451 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11452 DAG.getConstant(XType.getSizeInBits()-1,
11453 getShiftAmountTy(XType)));
11455 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11456 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11457 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11458 DAG.getConstant(XType.getSizeInBits()-1,
11459 getShiftAmountTy(N0.getValueType())));
11460 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11464 // Check to see if this is an integer abs.
11465 // select_cc setg[te] X, 0, X, -X ->
11466 // select_cc setgt X, -1, X, -X ->
11467 // select_cc setl[te] X, 0, -X, X ->
11468 // select_cc setlt X, 1, -X, X ->
11469 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11471 ConstantSDNode *SubC = nullptr;
11472 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11473 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11474 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11475 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11476 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11477 (N1C->isOne() && CC == ISD::SETLT)) &&
11478 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11479 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11481 EVT XType = N0.getValueType();
11482 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11483 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11485 DAG.getConstant(XType.getSizeInBits()-1,
11486 getShiftAmountTy(N0.getValueType())));
11487 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11489 AddToWorklist(Shift.getNode());
11490 AddToWorklist(Add.getNode());
11491 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11498 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11499 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11500 SDValue N1, ISD::CondCode Cond,
11501 SDLoc DL, bool foldBooleans) {
11502 TargetLowering::DAGCombinerInfo
11503 DagCombineInfo(DAG, Level, false, this);
11504 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11507 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11508 /// a DAG expression to select that will generate the same value by multiplying
11509 /// by a magic number. See:
11510 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11511 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11512 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11516 // Avoid division by zero.
11517 if (!C->getAPIntValue())
11520 std::vector<SDNode*> Built;
11522 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11524 for (SDNode *N : Built)
11529 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11530 /// power of 2, return a DAG expression to select that will generate the same
11531 /// value by right shifting.
11532 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11533 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11537 // Avoid division by zero.
11538 if (!C->getAPIntValue())
11541 std::vector<SDNode *> Built;
11542 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11544 for (SDNode *N : Built)
11549 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11550 /// return a DAG expression to select that will generate the same value by
11551 /// multiplying by a magic number. See:
11552 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11553 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11554 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11558 // Avoid division by zero.
11559 if (!C->getAPIntValue())
11562 std::vector<SDNode*> Built;
11564 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11566 for (SDNode *N : Built)
11571 /// FindBaseOffset - Return true if base is a frame index, which is known not
11572 // to alias with anything but itself. Provides base object and offset as
11574 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11575 const GlobalValue *&GV, const void *&CV) {
11576 // Assume it is a primitive operation.
11577 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11579 // If it's an adding a simple constant then integrate the offset.
11580 if (Base.getOpcode() == ISD::ADD) {
11581 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11582 Base = Base.getOperand(0);
11583 Offset += C->getZExtValue();
11587 // Return the underlying GlobalValue, and update the Offset. Return false
11588 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11589 // by multiple nodes with different offsets.
11590 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11591 GV = G->getGlobal();
11592 Offset += G->getOffset();
11596 // Return the underlying Constant value, and update the Offset. Return false
11597 // for ConstantSDNodes since the same constant pool entry may be represented
11598 // by multiple nodes with different offsets.
11599 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11600 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11601 : (const void *)C->getConstVal();
11602 Offset += C->getOffset();
11605 // If it's any of the following then it can't alias with anything but itself.
11606 return isa<FrameIndexSDNode>(Base);
11609 /// isAlias - Return true if there is any possibility that the two addresses
11611 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11612 // If they are the same then they must be aliases.
11613 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11615 // If they are both volatile then they cannot be reordered.
11616 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11618 // Gather base node and offset information.
11619 SDValue Base1, Base2;
11620 int64_t Offset1, Offset2;
11621 const GlobalValue *GV1, *GV2;
11622 const void *CV1, *CV2;
11623 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11624 Base1, Offset1, GV1, CV1);
11625 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11626 Base2, Offset2, GV2, CV2);
11628 // If they have a same base address then check to see if they overlap.
11629 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11630 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11631 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11633 // It is possible for different frame indices to alias each other, mostly
11634 // when tail call optimization reuses return address slots for arguments.
11635 // To catch this case, look up the actual index of frame indices to compute
11636 // the real alias relationship.
11637 if (isFrameIndex1 && isFrameIndex2) {
11638 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11639 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11640 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11641 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11642 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11645 // Otherwise, if we know what the bases are, and they aren't identical, then
11646 // we know they cannot alias.
11647 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11650 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11651 // compared to the size and offset of the access, we may be able to prove they
11652 // do not alias. This check is conservative for now to catch cases created by
11653 // splitting vector types.
11654 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11655 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11656 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11657 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11658 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11659 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11660 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11662 // There is no overlap between these relatively aligned accesses of similar
11663 // size, return no alias.
11664 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11665 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11669 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11670 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11672 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11673 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11677 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11678 // Use alias analysis information.
11679 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11680 Op1->getSrcValueOffset());
11681 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11682 Op0->getSrcValueOffset() - MinOffset;
11683 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11684 Op1->getSrcValueOffset() - MinOffset;
11685 AliasAnalysis::AliasResult AAResult =
11686 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11688 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11689 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11691 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11692 if (AAResult == AliasAnalysis::NoAlias)
11696 // Otherwise we have to assume they alias.
11700 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11701 /// looking for aliasing nodes and adding them to the Aliases vector.
11702 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11703 SmallVectorImpl<SDValue> &Aliases) {
11704 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11705 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11707 // Get alias information for node.
11708 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11711 Chains.push_back(OriginalChain);
11712 unsigned Depth = 0;
11714 // Look at each chain and determine if it is an alias. If so, add it to the
11715 // aliases list. If not, then continue up the chain looking for the next
11717 while (!Chains.empty()) {
11718 SDValue Chain = Chains.back();
11721 // For TokenFactor nodes, look at each operand and only continue up the
11722 // chain until we find two aliases. If we've seen two aliases, assume we'll
11723 // find more and revert to original chain since the xform is unlikely to be
11726 // FIXME: The depth check could be made to return the last non-aliasing
11727 // chain we found before we hit a tokenfactor rather than the original
11729 if (Depth > 6 || Aliases.size() == 2) {
11731 Aliases.push_back(OriginalChain);
11735 // Don't bother if we've been before.
11736 if (!Visited.insert(Chain.getNode()))
11739 switch (Chain.getOpcode()) {
11740 case ISD::EntryToken:
11741 // Entry token is ideal chain operand, but handled in FindBetterChain.
11746 // Get alias information for Chain.
11747 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11748 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11750 // If chain is alias then stop here.
11751 if (!(IsLoad && IsOpLoad) &&
11752 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11753 Aliases.push_back(Chain);
11755 // Look further up the chain.
11756 Chains.push_back(Chain.getOperand(0));
11762 case ISD::TokenFactor:
11763 // We have to check each of the operands of the token factor for "small"
11764 // token factors, so we queue them up. Adding the operands to the queue
11765 // (stack) in reverse order maintains the original order and increases the
11766 // likelihood that getNode will find a matching token factor (CSE.)
11767 if (Chain.getNumOperands() > 16) {
11768 Aliases.push_back(Chain);
11771 for (unsigned n = Chain.getNumOperands(); n;)
11772 Chains.push_back(Chain.getOperand(--n));
11777 // For all other instructions we will just have to take what we can get.
11778 Aliases.push_back(Chain);
11783 // We need to be careful here to also search for aliases through the
11784 // value operand of a store, etc. Consider the following situation:
11786 // L1 = load Token1, %52
11787 // S1 = store Token1, L1, %51
11788 // L2 = load Token1, %52+8
11789 // S2 = store Token1, L2, %51+8
11790 // Token2 = Token(S1, S2)
11791 // L3 = load Token2, %53
11792 // S3 = store Token2, L3, %52
11793 // L4 = load Token2, %53+8
11794 // S4 = store Token2, L4, %52+8
11795 // If we search for aliases of S3 (which loads address %52), and we look
11796 // only through the chain, then we'll miss the trivial dependence on L1
11797 // (which also loads from %52). We then might change all loads and
11798 // stores to use Token1 as their chain operand, which could result in
11799 // copying %53 into %52 before copying %52 into %51 (which should
11802 // The problem is, however, that searching for such data dependencies
11803 // can become expensive, and the cost is not directly related to the
11804 // chain depth. Instead, we'll rule out such configurations here by
11805 // insisting that we've visited all chain users (except for users
11806 // of the original chain, which is not necessary). When doing this,
11807 // we need to look through nodes we don't care about (otherwise, things
11808 // like register copies will interfere with trivial cases).
11810 SmallVector<const SDNode *, 16> Worklist;
11811 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11812 IE = Visited.end(); I != IE; ++I)
11813 if (*I != OriginalChain.getNode())
11814 Worklist.push_back(*I);
11816 while (!Worklist.empty()) {
11817 const SDNode *M = Worklist.pop_back_val();
11819 // We have already visited M, and want to make sure we've visited any uses
11820 // of M that we care about. For uses that we've not visisted, and don't
11821 // care about, queue them to the worklist.
11823 for (SDNode::use_iterator UI = M->use_begin(),
11824 UIE = M->use_end(); UI != UIE; ++UI)
11825 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11826 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11827 // We've not visited this use, and we care about it (it could have an
11828 // ordering dependency with the original node).
11830 Aliases.push_back(OriginalChain);
11834 // We've not visited this use, but we don't care about it. Mark it as
11835 // visited and enqueue it to the worklist.
11836 Worklist.push_back(*UI);
11841 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11842 /// for a better chain (aliasing node.)
11843 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11844 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11846 // Accumulate all the aliases to this node.
11847 GatherAllAliases(N, OldChain, Aliases);
11849 // If no operands then chain to entry token.
11850 if (Aliases.size() == 0)
11851 return DAG.getEntryNode();
11853 // If a single operand then chain to it. We don't need to revisit it.
11854 if (Aliases.size() == 1)
11857 // Construct a custom tailored token factor.
11858 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11861 // SelectionDAG::Combine - This is the entry point for the file.
11863 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11864 CodeGenOpt::Level OptLevel) {
11865 /// run - This is the main entry point to this class.
11867 DAGCombiner(*this, AA, OptLevel).Run(Level);