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 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.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 STATISTIC(NodesCombined , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
52 CombinerAA("combiner-alias-analysis", cl::Hidden,
53 cl::desc("Enable DAG combiner alias-analysis heuristics"));
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57 cl::desc("Enable DAG combiner's use of IR alias analysis"));
60 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
61 cl::desc("Enable DAG combiner's use of TBAA"));
64 static cl::opt<std::string>
65 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
66 cl::desc("Only use DAG-combiner alias analysis in this"
70 /// Hidden option to stress test load slicing, i.e., when this option
71 /// is enabled, load slicing bypasses most of its profitability guards.
73 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
74 cl::desc("Bypass the profitability model of load "
78 //------------------------------ DAGCombiner ---------------------------------//
82 const TargetLowering &TLI;
84 CodeGenOpt::Level OptLevel;
89 // Worklist of all of the nodes that need to be simplified.
91 // This has the semantics that when adding to the worklist,
92 // the item added must be next to be processed. It should
93 // also only appear once. The naive approach to this takes
96 // To reduce the insert/remove time to logarithmic, we use
97 // a set and a vector to maintain our worklist.
99 // The set contains the items on the worklist, but does not
100 // maintain the order they should be visited.
102 // The vector maintains the order nodes should be visited, but may
103 // contain duplicate or removed nodes. When choosing a node to
104 // visit, we pop off the order stack until we find an item that is
105 // also in the contents set. All operations are O(log N).
106 SmallPtrSet<SDNode*, 64> WorkListContents;
107 SmallVector<SDNode*, 64> WorkListOrder;
109 // AA - Used for DAG load/store alias analysis.
112 /// AddUsersToWorkList - When an instruction is simplified, add all users of
113 /// the instruction to the work lists because they might get more simplified
116 void AddUsersToWorkList(SDNode *N) {
117 for (SDNode *Node : N->uses())
121 /// visit - call the node-specific routine that knows how to fold each
122 /// particular type of node.
123 SDValue visit(SDNode *N);
126 /// AddToWorkList - Add to the work list making sure its instance is at the
127 /// back (next to be processed.)
128 void AddToWorkList(SDNode *N) {
129 WorkListContents.insert(N);
130 WorkListOrder.push_back(N);
133 /// removeFromWorkList - remove all instances of N from the worklist.
135 void removeFromWorkList(SDNode *N) {
136 WorkListContents.erase(N);
139 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
142 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
143 return CombineTo(N, &Res, 1, AddTo);
146 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
148 SDValue To[] = { Res0, Res1 };
149 return CombineTo(N, To, 2, AddTo);
152 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
156 /// SimplifyDemandedBits - Check the specified integer node value to see if
157 /// it can be simplified or if things it uses can be simplified by bit
158 /// propagation. If so, return true.
159 bool SimplifyDemandedBits(SDValue Op) {
160 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
161 APInt Demanded = APInt::getAllOnesValue(BitWidth);
162 return SimplifyDemandedBits(Op, Demanded);
165 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
167 bool CombineToPreIndexedLoadStore(SDNode *N);
168 bool CombineToPostIndexedLoadStore(SDNode *N);
169 bool SliceUpLoad(SDNode *N);
171 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
172 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
173 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
174 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
175 SDValue PromoteIntBinOp(SDValue Op);
176 SDValue PromoteIntShiftOp(SDValue Op);
177 SDValue PromoteExtend(SDValue Op);
178 bool PromoteLoad(SDValue Op);
180 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
181 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
182 ISD::NodeType ExtType);
184 /// combine - call the node-specific routine that knows how to fold each
185 /// particular type of node. If that doesn't do anything, try the
186 /// target-specific DAG combines.
187 SDValue combine(SDNode *N);
189 // Visitation implementation - Implement dag node combining for different
190 // node types. The semantics are as follows:
192 // SDValue.getNode() == 0 - No change was made
193 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
194 // otherwise - N should be replaced by the returned Operand.
196 SDValue visitTokenFactor(SDNode *N);
197 SDValue visitMERGE_VALUES(SDNode *N);
198 SDValue visitADD(SDNode *N);
199 SDValue visitSUB(SDNode *N);
200 SDValue visitADDC(SDNode *N);
201 SDValue visitSUBC(SDNode *N);
202 SDValue visitADDE(SDNode *N);
203 SDValue visitSUBE(SDNode *N);
204 SDValue visitMUL(SDNode *N);
205 SDValue visitSDIV(SDNode *N);
206 SDValue visitUDIV(SDNode *N);
207 SDValue visitSREM(SDNode *N);
208 SDValue visitUREM(SDNode *N);
209 SDValue visitMULHU(SDNode *N);
210 SDValue visitMULHS(SDNode *N);
211 SDValue visitSMUL_LOHI(SDNode *N);
212 SDValue visitUMUL_LOHI(SDNode *N);
213 SDValue visitSMULO(SDNode *N);
214 SDValue visitUMULO(SDNode *N);
215 SDValue visitSDIVREM(SDNode *N);
216 SDValue visitUDIVREM(SDNode *N);
217 SDValue visitAND(SDNode *N);
218 SDValue visitOR(SDNode *N);
219 SDValue visitXOR(SDNode *N);
220 SDValue SimplifyVBinOp(SDNode *N);
221 SDValue SimplifyVUnaryOp(SDNode *N);
222 SDValue visitSHL(SDNode *N);
223 SDValue visitSRA(SDNode *N);
224 SDValue visitSRL(SDNode *N);
225 SDValue visitRotate(SDNode *N);
226 SDValue visitCTLZ(SDNode *N);
227 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
228 SDValue visitCTTZ(SDNode *N);
229 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
230 SDValue visitCTPOP(SDNode *N);
231 SDValue visitSELECT(SDNode *N);
232 SDValue visitVSELECT(SDNode *N);
233 SDValue visitSELECT_CC(SDNode *N);
234 SDValue visitSETCC(SDNode *N);
235 SDValue visitSIGN_EXTEND(SDNode *N);
236 SDValue visitZERO_EXTEND(SDNode *N);
237 SDValue visitANY_EXTEND(SDNode *N);
238 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
239 SDValue visitTRUNCATE(SDNode *N);
240 SDValue visitBITCAST(SDNode *N);
241 SDValue visitBUILD_PAIR(SDNode *N);
242 SDValue visitFADD(SDNode *N);
243 SDValue visitFSUB(SDNode *N);
244 SDValue visitFMUL(SDNode *N);
245 SDValue visitFMA(SDNode *N);
246 SDValue visitFDIV(SDNode *N);
247 SDValue visitFREM(SDNode *N);
248 SDValue visitFCOPYSIGN(SDNode *N);
249 SDValue visitSINT_TO_FP(SDNode *N);
250 SDValue visitUINT_TO_FP(SDNode *N);
251 SDValue visitFP_TO_SINT(SDNode *N);
252 SDValue visitFP_TO_UINT(SDNode *N);
253 SDValue visitFP_ROUND(SDNode *N);
254 SDValue visitFP_ROUND_INREG(SDNode *N);
255 SDValue visitFP_EXTEND(SDNode *N);
256 SDValue visitFNEG(SDNode *N);
257 SDValue visitFABS(SDNode *N);
258 SDValue visitFCEIL(SDNode *N);
259 SDValue visitFTRUNC(SDNode *N);
260 SDValue visitFFLOOR(SDNode *N);
261 SDValue visitBRCOND(SDNode *N);
262 SDValue visitBR_CC(SDNode *N);
263 SDValue visitLOAD(SDNode *N);
264 SDValue visitSTORE(SDNode *N);
265 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
266 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
267 SDValue visitBUILD_VECTOR(SDNode *N);
268 SDValue visitCONCAT_VECTORS(SDNode *N);
269 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
270 SDValue visitVECTOR_SHUFFLE(SDNode *N);
271 SDValue visitINSERT_SUBVECTOR(SDNode *N);
273 SDValue XformToShuffleWithZero(SDNode *N);
274 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
276 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
278 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
279 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
280 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
281 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
282 SDValue N3, ISD::CondCode CC,
283 bool NotExtCompare = false);
284 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
285 SDLoc DL, bool foldBooleans = true);
287 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
289 bool isOneUseSetCC(SDValue N) const;
291 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
293 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
294 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
295 SDValue BuildSDIV(SDNode *N);
296 SDValue BuildUDIV(SDNode *N);
297 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
298 bool DemandHighBits = true);
299 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
300 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
301 SDValue InnerPos, SDValue InnerNeg,
302 unsigned PosOpcode, unsigned NegOpcode,
304 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
305 SDValue ReduceLoadWidth(SDNode *N);
306 SDValue ReduceLoadOpStoreWidth(SDNode *N);
307 SDValue TransformFPLoadStorePair(SDNode *N);
308 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
309 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
311 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
313 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
314 /// looking for aliasing nodes and adding them to the Aliases vector.
315 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
316 SmallVectorImpl<SDValue> &Aliases);
318 /// isAlias - Return true if there is any possibility that the two addresses
320 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
322 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
323 /// looking for a better chain (aliasing node.)
324 SDValue FindBetterChain(SDNode *N, SDValue Chain);
326 /// Merge consecutive store operations into a wide store.
327 /// This optimization uses wide integers or vectors when possible.
328 /// \return True if some memory operations were changed.
329 bool MergeConsecutiveStores(StoreSDNode *N);
331 /// \brief Try to transform a truncation where C is a constant:
332 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
334 /// \p N needs to be a truncation and its first operand an AND. Other
335 /// requirements are checked by the function (e.g. that trunc is
336 /// single-use) and if missed an empty SDValue is returned.
337 SDValue distributeTruncateThroughAnd(SDNode *N);
340 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
341 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
342 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
343 AttributeSet FnAttrs =
344 DAG.getMachineFunction().getFunction()->getAttributes();
346 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
347 Attribute::OptimizeForSize) ||
348 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
351 /// Run - runs the dag combiner on all nodes in the work list
352 void Run(CombineLevel AtLevel);
354 SelectionDAG &getDAG() const { return DAG; }
356 /// getShiftAmountTy - Returns a type large enough to hold any valid
357 /// shift amount - before type legalization these can be huge.
358 EVT getShiftAmountTy(EVT LHSTy) {
359 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
360 if (LHSTy.isVector())
362 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
363 : TLI.getPointerTy();
366 /// isTypeLegal - This method returns true if we are running before type
367 /// legalization or if the specified VT is legal.
368 bool isTypeLegal(const EVT &VT) {
369 if (!LegalTypes) return true;
370 return TLI.isTypeLegal(VT);
373 /// getSetCCResultType - Convenience wrapper around
374 /// TargetLowering::getSetCCResultType
375 EVT getSetCCResultType(EVT VT) const {
376 return TLI.getSetCCResultType(*DAG.getContext(), VT);
383 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
384 /// nodes from the worklist.
385 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
388 explicit WorkListRemover(DAGCombiner &dc)
389 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
391 void NodeDeleted(SDNode *N, SDNode *E) override {
392 DC.removeFromWorkList(N);
397 //===----------------------------------------------------------------------===//
398 // TargetLowering::DAGCombinerInfo implementation
399 //===----------------------------------------------------------------------===//
401 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
402 ((DAGCombiner*)DC)->AddToWorkList(N);
405 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
406 ((DAGCombiner*)DC)->removeFromWorkList(N);
409 SDValue TargetLowering::DAGCombinerInfo::
410 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
411 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
414 SDValue TargetLowering::DAGCombinerInfo::
415 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
416 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
420 SDValue TargetLowering::DAGCombinerInfo::
421 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
422 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
425 void TargetLowering::DAGCombinerInfo::
426 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
427 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
430 //===----------------------------------------------------------------------===//
432 //===----------------------------------------------------------------------===//
434 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
435 /// specified expression for the same cost as the expression itself, or 2 if we
436 /// can compute the negated form more cheaply than the expression itself.
437 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
438 const TargetLowering &TLI,
439 const TargetOptions *Options,
440 unsigned Depth = 0) {
441 // fneg is removable even if it has multiple uses.
442 if (Op.getOpcode() == ISD::FNEG) return 2;
444 // Don't allow anything with multiple uses.
445 if (!Op.hasOneUse()) return 0;
447 // Don't recurse exponentially.
448 if (Depth > 6) return 0;
450 switch (Op.getOpcode()) {
451 default: return false;
452 case ISD::ConstantFP:
453 // Don't invert constant FP values after legalize. The negated constant
454 // isn't necessarily legal.
455 return LegalOperations ? 0 : 1;
457 // FIXME: determine better conditions for this xform.
458 if (!Options->UnsafeFPMath) return 0;
460 // After operation legalization, it might not be legal to create new FSUBs.
461 if (LegalOperations &&
462 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
465 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
466 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
469 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
470 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
473 // We can't turn -(A-B) into B-A when we honor signed zeros.
474 if (!Options->UnsafeFPMath) return 0;
476 // fold (fneg (fsub A, B)) -> (fsub B, A)
481 if (Options->HonorSignDependentRoundingFPMath()) return 0;
483 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
484 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
488 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
494 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
499 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
500 /// returns the newly negated expression.
501 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
502 bool LegalOperations, unsigned Depth = 0) {
503 // fneg is removable even if it has multiple uses.
504 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
506 // Don't allow anything with multiple uses.
507 assert(Op.hasOneUse() && "Unknown reuse!");
509 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
510 switch (Op.getOpcode()) {
511 default: llvm_unreachable("Unknown code");
512 case ISD::ConstantFP: {
513 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
515 return DAG.getConstantFP(V, Op.getValueType());
518 // FIXME: determine better conditions for this xform.
519 assert(DAG.getTarget().Options.UnsafeFPMath);
521 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
522 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
523 DAG.getTargetLoweringInfo(),
524 &DAG.getTarget().Options, Depth+1))
525 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
526 GetNegatedExpression(Op.getOperand(0), DAG,
527 LegalOperations, Depth+1),
529 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
530 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
531 GetNegatedExpression(Op.getOperand(1), DAG,
532 LegalOperations, Depth+1),
535 // We can't turn -(A-B) into B-A when we honor signed zeros.
536 assert(DAG.getTarget().Options.UnsafeFPMath);
538 // fold (fneg (fsub 0, B)) -> B
539 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
540 if (N0CFP->getValueAPF().isZero())
541 return Op.getOperand(1);
543 // fold (fneg (fsub A, B)) -> (fsub B, A)
544 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
545 Op.getOperand(1), Op.getOperand(0));
549 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
551 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
552 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
553 DAG.getTargetLoweringInfo(),
554 &DAG.getTarget().Options, Depth+1))
555 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
556 GetNegatedExpression(Op.getOperand(0), DAG,
557 LegalOperations, Depth+1),
560 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
561 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
563 GetNegatedExpression(Op.getOperand(1), DAG,
564 LegalOperations, Depth+1));
568 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
569 GetNegatedExpression(Op.getOperand(0), DAG,
570 LegalOperations, Depth+1));
572 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
573 GetNegatedExpression(Op.getOperand(0), DAG,
574 LegalOperations, Depth+1),
579 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
580 // that selects between the target values used for true and false, making it
581 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
582 // the appropriate nodes based on the type of node we are checking. This
583 // simplifies life a bit for the callers.
584 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
586 if (N.getOpcode() == ISD::SETCC) {
587 LHS = N.getOperand(0);
588 RHS = N.getOperand(1);
589 CC = N.getOperand(2);
593 if (N.getOpcode() != ISD::SELECT_CC ||
594 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
595 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
598 LHS = N.getOperand(0);
599 RHS = N.getOperand(1);
600 CC = N.getOperand(4);
604 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
605 // one use. If this is true, it allows the users to invert the operation for
606 // free when it is profitable to do so.
607 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
609 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
614 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
615 /// elements are all the same constant or undefined.
616 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
617 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
622 unsigned SplatBitSize;
624 EVT EltVT = N->getValueType(0).getVectorElementType();
625 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
627 EltVT.getSizeInBits() >= SplatBitSize);
630 // \brief Returns the SDNode if it is a constant BuildVector or constant.
631 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
632 if (isa<ConstantSDNode>(N))
634 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
635 if(BV && BV->isConstant())
640 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
642 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
643 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
646 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
647 return BV->getConstantSplatValue();
652 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
653 SDValue N0, SDValue N1) {
654 EVT VT = N0.getValueType();
655 if (N0.getOpcode() == Opc) {
656 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
657 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
658 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
659 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
660 if (!OpNode.getNode())
662 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
664 if (N0.hasOneUse()) {
665 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
667 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
668 if (!OpNode.getNode())
670 AddToWorkList(OpNode.getNode());
671 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
676 if (N1.getOpcode() == Opc) {
677 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
678 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
679 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
680 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
681 if (!OpNode.getNode())
683 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
685 if (N1.hasOneUse()) {
686 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
688 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
689 if (!OpNode.getNode())
691 AddToWorkList(OpNode.getNode());
692 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
700 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
702 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
704 DEBUG(dbgs() << "\nReplacing.1 ";
706 dbgs() << "\nWith: ";
707 To[0].getNode()->dump(&DAG);
708 dbgs() << " and " << NumTo-1 << " other values\n";
709 for (unsigned i = 0, e = NumTo; i != e; ++i)
710 assert((!To[i].getNode() ||
711 N->getValueType(i) == To[i].getValueType()) &&
712 "Cannot combine value to value of different type!"));
713 WorkListRemover DeadNodes(*this);
714 DAG.ReplaceAllUsesWith(N, To);
716 // Push the new nodes and any users onto the worklist
717 for (unsigned i = 0, e = NumTo; i != e; ++i) {
718 if (To[i].getNode()) {
719 AddToWorkList(To[i].getNode());
720 AddUsersToWorkList(To[i].getNode());
725 // Finally, if the node is now dead, remove it from the graph. The node
726 // may not be dead if the replacement process recursively simplified to
727 // something else needing this node.
728 if (N->use_empty()) {
729 // Nodes can be reintroduced into the worklist. Make sure we do not
730 // process a node that has been replaced.
731 removeFromWorkList(N);
733 // Finally, since the node is now dead, remove it from the graph.
736 return SDValue(N, 0);
740 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
741 // Replace all uses. If any nodes become isomorphic to other nodes and
742 // are deleted, make sure to remove them from our worklist.
743 WorkListRemover DeadNodes(*this);
744 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
746 // Push the new node and any (possibly new) users onto the worklist.
747 AddToWorkList(TLO.New.getNode());
748 AddUsersToWorkList(TLO.New.getNode());
750 // Finally, if the node is now dead, remove it from the graph. The node
751 // may not be dead if the replacement process recursively simplified to
752 // something else needing this node.
753 if (TLO.Old.getNode()->use_empty()) {
754 removeFromWorkList(TLO.Old.getNode());
756 // If the operands of this node are only used by the node, they will now
757 // be dead. Make sure to visit them first to delete dead nodes early.
758 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
759 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
760 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
762 DAG.DeleteNode(TLO.Old.getNode());
766 /// SimplifyDemandedBits - Check the specified integer node value to see if
767 /// it can be simplified or if things it uses can be simplified by bit
768 /// propagation. If so, return true.
769 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
770 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
771 APInt KnownZero, KnownOne;
772 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
776 AddToWorkList(Op.getNode());
778 // Replace the old value with the new one.
780 DEBUG(dbgs() << "\nReplacing.2 ";
781 TLO.Old.getNode()->dump(&DAG);
782 dbgs() << "\nWith: ";
783 TLO.New.getNode()->dump(&DAG);
786 CommitTargetLoweringOpt(TLO);
790 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
792 EVT VT = Load->getValueType(0);
793 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
795 DEBUG(dbgs() << "\nReplacing.9 ";
797 dbgs() << "\nWith: ";
798 Trunc.getNode()->dump(&DAG);
800 WorkListRemover DeadNodes(*this);
801 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
802 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
803 removeFromWorkList(Load);
804 DAG.DeleteNode(Load);
805 AddToWorkList(Trunc.getNode());
808 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
811 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
812 EVT MemVT = LD->getMemoryVT();
813 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
814 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
816 : LD->getExtensionType();
818 return DAG.getExtLoad(ExtType, dl, PVT,
819 LD->getChain(), LD->getBasePtr(),
820 MemVT, LD->getMemOperand());
823 unsigned Opc = Op.getOpcode();
826 case ISD::AssertSext:
827 return DAG.getNode(ISD::AssertSext, dl, PVT,
828 SExtPromoteOperand(Op.getOperand(0), PVT),
830 case ISD::AssertZext:
831 return DAG.getNode(ISD::AssertZext, dl, PVT,
832 ZExtPromoteOperand(Op.getOperand(0), PVT),
834 case ISD::Constant: {
836 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
837 return DAG.getNode(ExtOpc, dl, PVT, Op);
841 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
843 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
846 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
847 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
849 EVT OldVT = Op.getValueType();
851 bool Replace = false;
852 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
853 if (!NewOp.getNode())
855 AddToWorkList(NewOp.getNode());
858 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
859 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
860 DAG.getValueType(OldVT));
863 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
864 EVT OldVT = Op.getValueType();
866 bool Replace = false;
867 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
868 if (!NewOp.getNode())
870 AddToWorkList(NewOp.getNode());
873 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
874 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
877 /// PromoteIntBinOp - Promote the specified integer binary operation if the
878 /// target indicates it is beneficial. e.g. On x86, it's usually better to
879 /// promote i16 operations to i32 since i16 instructions are longer.
880 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
881 if (!LegalOperations)
884 EVT VT = Op.getValueType();
885 if (VT.isVector() || !VT.isInteger())
888 // If operation type is 'undesirable', e.g. i16 on x86, consider
890 unsigned Opc = Op.getOpcode();
891 if (TLI.isTypeDesirableForOp(Opc, VT))
895 // Consult target whether it is a good idea to promote this operation and
896 // what's the right type to promote it to.
897 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
898 assert(PVT != VT && "Don't know what type to promote to!");
900 bool Replace0 = false;
901 SDValue N0 = Op.getOperand(0);
902 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
906 bool Replace1 = false;
907 SDValue N1 = Op.getOperand(1);
912 NN1 = PromoteOperand(N1, PVT, Replace1);
917 AddToWorkList(NN0.getNode());
919 AddToWorkList(NN1.getNode());
922 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
924 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
926 DEBUG(dbgs() << "\nPromoting ";
927 Op.getNode()->dump(&DAG));
929 return DAG.getNode(ISD::TRUNCATE, dl, VT,
930 DAG.getNode(Opc, dl, PVT, NN0, NN1));
935 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
936 /// target indicates it is beneficial. e.g. On x86, it's usually better to
937 /// promote i16 operations to i32 since i16 instructions are longer.
938 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
939 if (!LegalOperations)
942 EVT VT = Op.getValueType();
943 if (VT.isVector() || !VT.isInteger())
946 // If operation type is 'undesirable', e.g. i16 on x86, consider
948 unsigned Opc = Op.getOpcode();
949 if (TLI.isTypeDesirableForOp(Opc, VT))
953 // Consult target whether it is a good idea to promote this operation and
954 // what's the right type to promote it to.
955 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
956 assert(PVT != VT && "Don't know what type to promote to!");
958 bool Replace = false;
959 SDValue N0 = Op.getOperand(0);
961 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
962 else if (Opc == ISD::SRL)
963 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
965 N0 = PromoteOperand(N0, PVT, Replace);
969 AddToWorkList(N0.getNode());
971 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
973 DEBUG(dbgs() << "\nPromoting ";
974 Op.getNode()->dump(&DAG));
976 return DAG.getNode(ISD::TRUNCATE, dl, VT,
977 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
982 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
983 if (!LegalOperations)
986 EVT VT = Op.getValueType();
987 if (VT.isVector() || !VT.isInteger())
990 // If operation type is 'undesirable', e.g. i16 on x86, consider
992 unsigned Opc = Op.getOpcode();
993 if (TLI.isTypeDesirableForOp(Opc, VT))
997 // Consult target whether it is a good idea to promote this operation and
998 // what's the right type to promote it to.
999 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1000 assert(PVT != VT && "Don't know what type to promote to!");
1001 // fold (aext (aext x)) -> (aext x)
1002 // fold (aext (zext x)) -> (zext x)
1003 // fold (aext (sext x)) -> (sext x)
1004 DEBUG(dbgs() << "\nPromoting ";
1005 Op.getNode()->dump(&DAG));
1006 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1011 bool DAGCombiner::PromoteLoad(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!");
1032 SDNode *N = Op.getNode();
1033 LoadSDNode *LD = cast<LoadSDNode>(N);
1034 EVT MemVT = LD->getMemoryVT();
1035 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1036 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1038 : LD->getExtensionType();
1039 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1040 LD->getChain(), LD->getBasePtr(),
1041 MemVT, LD->getMemOperand());
1042 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1044 DEBUG(dbgs() << "\nPromoting ";
1047 Result.getNode()->dump(&DAG);
1049 WorkListRemover DeadNodes(*this);
1050 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1051 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1052 removeFromWorkList(N);
1054 AddToWorkList(Result.getNode());
1061 //===----------------------------------------------------------------------===//
1062 // Main DAG Combiner implementation
1063 //===----------------------------------------------------------------------===//
1065 void DAGCombiner::Run(CombineLevel AtLevel) {
1066 // set the instance variables, so that the various visit routines may use it.
1068 LegalOperations = Level >= AfterLegalizeVectorOps;
1069 LegalTypes = Level >= AfterLegalizeTypes;
1071 // Add all the dag nodes to the worklist.
1072 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1073 E = DAG.allnodes_end(); I != E; ++I)
1076 // Create a dummy node (which is not added to allnodes), that adds a reference
1077 // to the root node, preventing it from being deleted, and tracking any
1078 // changes of the root.
1079 HandleSDNode Dummy(DAG.getRoot());
1081 // The root of the dag may dangle to deleted nodes until the dag combiner is
1082 // done. Set it to null to avoid confusion.
1083 DAG.setRoot(SDValue());
1085 // while the worklist isn't empty, find a node and
1086 // try and combine it.
1087 while (!WorkListContents.empty()) {
1089 // The WorkListOrder holds the SDNodes in order, but it may contain
1091 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1092 // worklist *should* contain, and check the node we want to visit is should
1093 // actually be visited.
1095 N = WorkListOrder.pop_back_val();
1096 } while (!WorkListContents.erase(N));
1098 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1099 // N is deleted from the DAG, since they too may now be dead or may have a
1100 // reduced number of uses, allowing other xforms.
1101 if (N->use_empty() && N != &Dummy) {
1102 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1103 AddToWorkList(N->getOperand(i).getNode());
1109 SDValue RV = combine(N);
1116 // If we get back the same node we passed in, rather than a new node or
1117 // zero, we know that the node must have defined multiple values and
1118 // CombineTo was used. Since CombineTo takes care of the worklist
1119 // mechanics for us, we have no work to do in this case.
1120 if (RV.getNode() == N)
1123 assert(N->getOpcode() != ISD::DELETED_NODE &&
1124 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1125 "Node was deleted but visit returned new node!");
1127 DEBUG(dbgs() << "\nReplacing.3 ";
1129 dbgs() << "\nWith: ";
1130 RV.getNode()->dump(&DAG);
1133 // Transfer debug value.
1134 DAG.TransferDbgValues(SDValue(N, 0), RV);
1135 WorkListRemover DeadNodes(*this);
1136 if (N->getNumValues() == RV.getNode()->getNumValues())
1137 DAG.ReplaceAllUsesWith(N, RV.getNode());
1139 assert(N->getValueType(0) == RV.getValueType() &&
1140 N->getNumValues() == 1 && "Type mismatch");
1142 DAG.ReplaceAllUsesWith(N, &OpV);
1145 // Push the new node and any users onto the worklist
1146 AddToWorkList(RV.getNode());
1147 AddUsersToWorkList(RV.getNode());
1149 // Add any uses of the old node to the worklist in case this node is the
1150 // last one that uses them. They may become dead after this node is
1152 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1153 AddToWorkList(N->getOperand(i).getNode());
1155 // Finally, if the node is now dead, remove it from the graph. The node
1156 // may not be dead if the replacement process recursively simplified to
1157 // something else needing this node.
1158 if (N->use_empty()) {
1159 // Nodes can be reintroduced into the worklist. Make sure we do not
1160 // process a node that has been replaced.
1161 removeFromWorkList(N);
1163 // Finally, since the node is now dead, remove it from the graph.
1168 // If the root changed (e.g. it was a dead load, update the root).
1169 DAG.setRoot(Dummy.getValue());
1170 DAG.RemoveDeadNodes();
1173 SDValue DAGCombiner::visit(SDNode *N) {
1174 switch (N->getOpcode()) {
1176 case ISD::TokenFactor: return visitTokenFactor(N);
1177 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1178 case ISD::ADD: return visitADD(N);
1179 case ISD::SUB: return visitSUB(N);
1180 case ISD::ADDC: return visitADDC(N);
1181 case ISD::SUBC: return visitSUBC(N);
1182 case ISD::ADDE: return visitADDE(N);
1183 case ISD::SUBE: return visitSUBE(N);
1184 case ISD::MUL: return visitMUL(N);
1185 case ISD::SDIV: return visitSDIV(N);
1186 case ISD::UDIV: return visitUDIV(N);
1187 case ISD::SREM: return visitSREM(N);
1188 case ISD::UREM: return visitUREM(N);
1189 case ISD::MULHU: return visitMULHU(N);
1190 case ISD::MULHS: return visitMULHS(N);
1191 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1192 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1193 case ISD::SMULO: return visitSMULO(N);
1194 case ISD::UMULO: return visitUMULO(N);
1195 case ISD::SDIVREM: return visitSDIVREM(N);
1196 case ISD::UDIVREM: return visitUDIVREM(N);
1197 case ISD::AND: return visitAND(N);
1198 case ISD::OR: return visitOR(N);
1199 case ISD::XOR: return visitXOR(N);
1200 case ISD::SHL: return visitSHL(N);
1201 case ISD::SRA: return visitSRA(N);
1202 case ISD::SRL: return visitSRL(N);
1204 case ISD::ROTL: return visitRotate(N);
1205 case ISD::CTLZ: return visitCTLZ(N);
1206 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1207 case ISD::CTTZ: return visitCTTZ(N);
1208 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1209 case ISD::CTPOP: return visitCTPOP(N);
1210 case ISD::SELECT: return visitSELECT(N);
1211 case ISD::VSELECT: return visitVSELECT(N);
1212 case ISD::SELECT_CC: return visitSELECT_CC(N);
1213 case ISD::SETCC: return visitSETCC(N);
1214 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1215 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1216 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1217 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1218 case ISD::TRUNCATE: return visitTRUNCATE(N);
1219 case ISD::BITCAST: return visitBITCAST(N);
1220 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1221 case ISD::FADD: return visitFADD(N);
1222 case ISD::FSUB: return visitFSUB(N);
1223 case ISD::FMUL: return visitFMUL(N);
1224 case ISD::FMA: return visitFMA(N);
1225 case ISD::FDIV: return visitFDIV(N);
1226 case ISD::FREM: return visitFREM(N);
1227 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1228 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1229 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1230 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1231 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1232 case ISD::FP_ROUND: return visitFP_ROUND(N);
1233 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1234 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1235 case ISD::FNEG: return visitFNEG(N);
1236 case ISD::FABS: return visitFABS(N);
1237 case ISD::FFLOOR: return visitFFLOOR(N);
1238 case ISD::FCEIL: return visitFCEIL(N);
1239 case ISD::FTRUNC: return visitFTRUNC(N);
1240 case ISD::BRCOND: return visitBRCOND(N);
1241 case ISD::BR_CC: return visitBR_CC(N);
1242 case ISD::LOAD: return visitLOAD(N);
1243 case ISD::STORE: return visitSTORE(N);
1244 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1245 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1246 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1247 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1248 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1249 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1250 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1255 SDValue DAGCombiner::combine(SDNode *N) {
1256 SDValue RV = visit(N);
1258 // If nothing happened, try a target-specific DAG combine.
1259 if (!RV.getNode()) {
1260 assert(N->getOpcode() != ISD::DELETED_NODE &&
1261 "Node was deleted but visit returned NULL!");
1263 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1264 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1266 // Expose the DAG combiner to the target combiner impls.
1267 TargetLowering::DAGCombinerInfo
1268 DagCombineInfo(DAG, Level, false, this);
1270 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1274 // If nothing happened still, try promoting the operation.
1275 if (!RV.getNode()) {
1276 switch (N->getOpcode()) {
1284 RV = PromoteIntBinOp(SDValue(N, 0));
1289 RV = PromoteIntShiftOp(SDValue(N, 0));
1291 case ISD::SIGN_EXTEND:
1292 case ISD::ZERO_EXTEND:
1293 case ISD::ANY_EXTEND:
1294 RV = PromoteExtend(SDValue(N, 0));
1297 if (PromoteLoad(SDValue(N, 0)))
1303 // If N is a commutative binary node, try commuting it to enable more
1305 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1306 N->getNumValues() == 1) {
1307 SDValue N0 = N->getOperand(0);
1308 SDValue N1 = N->getOperand(1);
1310 // Constant operands are canonicalized to RHS.
1311 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1312 SDValue Ops[] = { N1, N0 };
1313 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1316 return SDValue(CSENode, 0);
1323 /// getInputChainForNode - Given a node, return its input chain if it has one,
1324 /// otherwise return a null sd operand.
1325 static SDValue getInputChainForNode(SDNode *N) {
1326 if (unsigned NumOps = N->getNumOperands()) {
1327 if (N->getOperand(0).getValueType() == MVT::Other)
1328 return N->getOperand(0);
1329 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1330 return N->getOperand(NumOps-1);
1331 for (unsigned i = 1; i < NumOps-1; ++i)
1332 if (N->getOperand(i).getValueType() == MVT::Other)
1333 return N->getOperand(i);
1338 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1339 // If N has two operands, where one has an input chain equal to the other,
1340 // the 'other' chain is redundant.
1341 if (N->getNumOperands() == 2) {
1342 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1343 return N->getOperand(0);
1344 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1345 return N->getOperand(1);
1348 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1349 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1350 SmallPtrSet<SDNode*, 16> SeenOps;
1351 bool Changed = false; // If we should replace this token factor.
1353 // Start out with this token factor.
1356 // Iterate through token factors. The TFs grows when new token factors are
1358 for (unsigned i = 0; i < TFs.size(); ++i) {
1359 SDNode *TF = TFs[i];
1361 // Check each of the operands.
1362 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1363 SDValue Op = TF->getOperand(i);
1365 switch (Op.getOpcode()) {
1366 case ISD::EntryToken:
1367 // Entry tokens don't need to be added to the list. They are
1372 case ISD::TokenFactor:
1373 if (Op.hasOneUse() &&
1374 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1375 // Queue up for processing.
1376 TFs.push_back(Op.getNode());
1377 // Clean up in case the token factor is removed.
1378 AddToWorkList(Op.getNode());
1385 // Only add if it isn't already in the list.
1386 if (SeenOps.insert(Op.getNode()))
1397 // If we've change things around then replace token factor.
1400 // The entry token is the only possible outcome.
1401 Result = DAG.getEntryNode();
1403 // New and improved token factor.
1404 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1405 MVT::Other, &Ops[0], Ops.size());
1408 // Don't add users to work list.
1409 return CombineTo(N, Result, false);
1415 /// MERGE_VALUES can always be eliminated.
1416 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1417 WorkListRemover DeadNodes(*this);
1418 // Replacing results may cause a different MERGE_VALUES to suddenly
1419 // be CSE'd with N, and carry its uses with it. Iterate until no
1420 // uses remain, to ensure that the node can be safely deleted.
1421 // First add the users of this node to the work list so that they
1422 // can be tried again once they have new operands.
1423 AddUsersToWorkList(N);
1425 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1426 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1427 } while (!N->use_empty());
1428 removeFromWorkList(N);
1430 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1434 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1435 SelectionDAG &DAG) {
1436 EVT VT = N0.getValueType();
1437 SDValue N00 = N0.getOperand(0);
1438 SDValue N01 = N0.getOperand(1);
1439 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1441 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1442 isa<ConstantSDNode>(N00.getOperand(1))) {
1443 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1444 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1445 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1446 N00.getOperand(0), N01),
1447 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1448 N00.getOperand(1), N01));
1449 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1455 SDValue DAGCombiner::visitADD(SDNode *N) {
1456 SDValue N0 = N->getOperand(0);
1457 SDValue N1 = N->getOperand(1);
1458 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1459 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1460 EVT VT = N0.getValueType();
1463 if (VT.isVector()) {
1464 SDValue FoldedVOp = SimplifyVBinOp(N);
1465 if (FoldedVOp.getNode()) return FoldedVOp;
1467 // fold (add x, 0) -> x, vector edition
1468 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1470 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1474 // fold (add x, undef) -> undef
1475 if (N0.getOpcode() == ISD::UNDEF)
1477 if (N1.getOpcode() == ISD::UNDEF)
1479 // fold (add c1, c2) -> c1+c2
1481 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1482 // canonicalize constant to RHS
1484 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1485 // fold (add x, 0) -> x
1486 if (N1C && N1C->isNullValue())
1488 // fold (add Sym, c) -> Sym+c
1489 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1490 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1491 GA->getOpcode() == ISD::GlobalAddress)
1492 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1494 (uint64_t)N1C->getSExtValue());
1495 // fold ((c1-A)+c2) -> (c1+c2)-A
1496 if (N1C && N0.getOpcode() == ISD::SUB)
1497 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1498 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1499 DAG.getConstant(N1C->getAPIntValue()+
1500 N0C->getAPIntValue(), VT),
1503 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1506 // fold ((0-A) + B) -> B-A
1507 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1508 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1509 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1510 // fold (A + (0-B)) -> A-B
1511 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1512 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1513 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1514 // fold (A+(B-A)) -> B
1515 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1516 return N1.getOperand(0);
1517 // fold ((B-A)+A) -> B
1518 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1519 return N0.getOperand(0);
1520 // fold (A+(B-(A+C))) to (B-C)
1521 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1522 N0 == N1.getOperand(1).getOperand(0))
1523 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1524 N1.getOperand(1).getOperand(1));
1525 // fold (A+(B-(C+A))) to (B-C)
1526 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1527 N0 == N1.getOperand(1).getOperand(1))
1528 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1529 N1.getOperand(1).getOperand(0));
1530 // fold (A+((B-A)+or-C)) to (B+or-C)
1531 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1532 N1.getOperand(0).getOpcode() == ISD::SUB &&
1533 N0 == N1.getOperand(0).getOperand(1))
1534 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1535 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1537 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1538 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1539 SDValue N00 = N0.getOperand(0);
1540 SDValue N01 = N0.getOperand(1);
1541 SDValue N10 = N1.getOperand(0);
1542 SDValue N11 = N1.getOperand(1);
1544 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1545 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1546 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1547 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1550 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1551 return SDValue(N, 0);
1553 // fold (a+b) -> (a|b) iff a and b share no bits.
1554 if (VT.isInteger() && !VT.isVector()) {
1555 APInt LHSZero, LHSOne;
1556 APInt RHSZero, RHSOne;
1557 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1559 if (LHSZero.getBoolValue()) {
1560 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1562 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1563 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1564 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1565 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1566 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1571 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1572 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1573 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1574 if (Result.getNode()) return Result;
1576 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1577 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1578 if (Result.getNode()) return Result;
1581 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1582 if (N1.getOpcode() == ISD::SHL &&
1583 N1.getOperand(0).getOpcode() == ISD::SUB)
1584 if (ConstantSDNode *C =
1585 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1586 if (C->getAPIntValue() == 0)
1587 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1588 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1589 N1.getOperand(0).getOperand(1),
1591 if (N0.getOpcode() == ISD::SHL &&
1592 N0.getOperand(0).getOpcode() == ISD::SUB)
1593 if (ConstantSDNode *C =
1594 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1595 if (C->getAPIntValue() == 0)
1596 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1597 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1598 N0.getOperand(0).getOperand(1),
1601 if (N1.getOpcode() == ISD::AND) {
1602 SDValue AndOp0 = N1.getOperand(0);
1603 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1604 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1605 unsigned DestBits = VT.getScalarType().getSizeInBits();
1607 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1608 // and similar xforms where the inner op is either ~0 or 0.
1609 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1611 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1615 // add (sext i1), X -> sub X, (zext i1)
1616 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1617 N0.getOperand(0).getValueType() == MVT::i1 &&
1618 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1620 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1621 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1627 SDValue DAGCombiner::visitADDC(SDNode *N) {
1628 SDValue N0 = N->getOperand(0);
1629 SDValue N1 = N->getOperand(1);
1630 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1631 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1632 EVT VT = N0.getValueType();
1634 // If the flag result is dead, turn this into an ADD.
1635 if (!N->hasAnyUseOfValue(1))
1636 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1637 DAG.getNode(ISD::CARRY_FALSE,
1638 SDLoc(N), MVT::Glue));
1640 // canonicalize constant to RHS.
1642 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1644 // fold (addc x, 0) -> x + no carry out
1645 if (N1C && N1C->isNullValue())
1646 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1647 SDLoc(N), MVT::Glue));
1649 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1650 APInt LHSZero, LHSOne;
1651 APInt RHSZero, RHSOne;
1652 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1654 if (LHSZero.getBoolValue()) {
1655 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1657 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1658 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1659 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1660 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1661 DAG.getNode(ISD::CARRY_FALSE,
1662 SDLoc(N), MVT::Glue));
1668 SDValue DAGCombiner::visitADDE(SDNode *N) {
1669 SDValue N0 = N->getOperand(0);
1670 SDValue N1 = N->getOperand(1);
1671 SDValue CarryIn = N->getOperand(2);
1672 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1673 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1675 // canonicalize constant to RHS
1677 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1680 // fold (adde x, y, false) -> (addc x, y)
1681 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1682 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1687 // Since it may not be valid to emit a fold to zero for vector initializers
1688 // check if we can before folding.
1689 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1691 bool LegalOperations, bool LegalTypes) {
1693 return DAG.getConstant(0, VT);
1694 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1695 return DAG.getConstant(0, VT);
1699 SDValue DAGCombiner::visitSUB(SDNode *N) {
1700 SDValue N0 = N->getOperand(0);
1701 SDValue N1 = N->getOperand(1);
1702 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1703 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1704 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1705 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1706 EVT VT = N0.getValueType();
1709 if (VT.isVector()) {
1710 SDValue FoldedVOp = SimplifyVBinOp(N);
1711 if (FoldedVOp.getNode()) return FoldedVOp;
1713 // fold (sub x, 0) -> x, vector edition
1714 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1718 // fold (sub x, x) -> 0
1719 // FIXME: Refactor this and xor and other similar operations together.
1721 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1722 // fold (sub c1, c2) -> c1-c2
1724 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1725 // fold (sub x, c) -> (add x, -c)
1727 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1728 DAG.getConstant(-N1C->getAPIntValue(), VT));
1729 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1730 if (N0C && N0C->isAllOnesValue())
1731 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1732 // fold A-(A-B) -> B
1733 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1734 return N1.getOperand(1);
1735 // fold (A+B)-A -> B
1736 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1737 return N0.getOperand(1);
1738 // fold (A+B)-B -> A
1739 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1740 return N0.getOperand(0);
1741 // fold C2-(A+C1) -> (C2-C1)-A
1742 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1743 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1745 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1748 // fold ((A+(B+or-C))-B) -> A+or-C
1749 if (N0.getOpcode() == ISD::ADD &&
1750 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1751 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1752 N0.getOperand(1).getOperand(0) == N1)
1753 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1754 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1755 // fold ((A+(C+B))-B) -> A+C
1756 if (N0.getOpcode() == ISD::ADD &&
1757 N0.getOperand(1).getOpcode() == ISD::ADD &&
1758 N0.getOperand(1).getOperand(1) == N1)
1759 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1760 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1761 // fold ((A-(B-C))-C) -> A-B
1762 if (N0.getOpcode() == ISD::SUB &&
1763 N0.getOperand(1).getOpcode() == ISD::SUB &&
1764 N0.getOperand(1).getOperand(1) == N1)
1765 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1766 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1768 // If either operand of a sub is undef, the result is undef
1769 if (N0.getOpcode() == ISD::UNDEF)
1771 if (N1.getOpcode() == ISD::UNDEF)
1774 // If the relocation model supports it, consider symbol offsets.
1775 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1776 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1777 // fold (sub Sym, c) -> Sym-c
1778 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1779 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1781 (uint64_t)N1C->getSExtValue());
1782 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1783 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1784 if (GA->getGlobal() == GB->getGlobal())
1785 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1792 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1793 SDValue N0 = N->getOperand(0);
1794 SDValue N1 = N->getOperand(1);
1795 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1796 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1797 EVT VT = N0.getValueType();
1799 // If the flag result is dead, turn this into an SUB.
1800 if (!N->hasAnyUseOfValue(1))
1801 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1802 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1805 // fold (subc x, x) -> 0 + no borrow
1807 return CombineTo(N, DAG.getConstant(0, VT),
1808 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1811 // fold (subc x, 0) -> x + no borrow
1812 if (N1C && N1C->isNullValue())
1813 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1816 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1817 if (N0C && N0C->isAllOnesValue())
1818 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1819 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1825 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1826 SDValue N0 = N->getOperand(0);
1827 SDValue N1 = N->getOperand(1);
1828 SDValue CarryIn = N->getOperand(2);
1830 // fold (sube x, y, false) -> (subc x, y)
1831 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1832 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1837 SDValue DAGCombiner::visitMUL(SDNode *N) {
1838 SDValue N0 = N->getOperand(0);
1839 SDValue N1 = N->getOperand(1);
1840 EVT VT = N0.getValueType();
1842 // fold (mul x, undef) -> 0
1843 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1844 return DAG.getConstant(0, VT);
1846 bool N0IsConst = false;
1847 bool N1IsConst = false;
1848 APInt ConstValue0, ConstValue1;
1850 if (VT.isVector()) {
1851 SDValue FoldedVOp = SimplifyVBinOp(N);
1852 if (FoldedVOp.getNode()) return FoldedVOp;
1854 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1855 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1857 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1858 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1860 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1861 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1865 // fold (mul c1, c2) -> c1*c2
1866 if (N0IsConst && N1IsConst)
1867 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1869 // canonicalize constant to RHS
1870 if (N0IsConst && !N1IsConst)
1871 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1872 // fold (mul x, 0) -> 0
1873 if (N1IsConst && ConstValue1 == 0)
1875 // We require a splat of the entire scalar bit width for non-contiguous
1878 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1879 // fold (mul x, 1) -> x
1880 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1882 // fold (mul x, -1) -> 0-x
1883 if (N1IsConst && ConstValue1.isAllOnesValue())
1884 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1885 DAG.getConstant(0, VT), N0);
1886 // fold (mul x, (1 << c)) -> x << c
1887 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1888 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1889 DAG.getConstant(ConstValue1.logBase2(),
1890 getShiftAmountTy(N0.getValueType())));
1891 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1892 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1893 unsigned Log2Val = (-ConstValue1).logBase2();
1894 // FIXME: If the input is something that is easily negated (e.g. a
1895 // single-use add), we should put the negate there.
1896 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1897 DAG.getConstant(0, VT),
1898 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1899 DAG.getConstant(Log2Val,
1900 getShiftAmountTy(N0.getValueType()))));
1904 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1905 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1906 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1907 isa<ConstantSDNode>(N0.getOperand(1)))) {
1908 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1909 N1, N0.getOperand(1));
1910 AddToWorkList(C3.getNode());
1911 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1912 N0.getOperand(0), C3);
1915 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1918 SDValue Sh(nullptr,0), Y(nullptr,0);
1919 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1920 if (N0.getOpcode() == ISD::SHL &&
1921 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1922 isa<ConstantSDNode>(N0.getOperand(1))) &&
1923 N0.getNode()->hasOneUse()) {
1925 } else if (N1.getOpcode() == ISD::SHL &&
1926 isa<ConstantSDNode>(N1.getOperand(1)) &&
1927 N1.getNode()->hasOneUse()) {
1932 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1933 Sh.getOperand(0), Y);
1934 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1935 Mul, Sh.getOperand(1));
1939 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1940 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1941 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1942 isa<ConstantSDNode>(N0.getOperand(1))))
1943 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1944 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1945 N0.getOperand(0), N1),
1946 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1947 N0.getOperand(1), N1));
1950 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1957 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1958 SDValue N0 = N->getOperand(0);
1959 SDValue N1 = N->getOperand(1);
1960 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1961 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1962 EVT VT = N->getValueType(0);
1965 if (VT.isVector()) {
1966 SDValue FoldedVOp = SimplifyVBinOp(N);
1967 if (FoldedVOp.getNode()) return FoldedVOp;
1970 // fold (sdiv c1, c2) -> c1/c2
1971 if (N0C && N1C && !N1C->isNullValue())
1972 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1973 // fold (sdiv X, 1) -> X
1974 if (N1C && N1C->getAPIntValue() == 1LL)
1976 // fold (sdiv X, -1) -> 0-X
1977 if (N1C && N1C->isAllOnesValue())
1978 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1979 DAG.getConstant(0, VT), N0);
1980 // If we know the sign bits of both operands are zero, strength reduce to a
1981 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1982 if (!VT.isVector()) {
1983 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1984 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1987 // fold (sdiv X, pow2) -> simple ops after legalize
1988 if (N1C && !N1C->isNullValue() &&
1989 (N1C->getAPIntValue().isPowerOf2() ||
1990 (-N1C->getAPIntValue()).isPowerOf2())) {
1991 // If dividing by powers of two is cheap, then don't perform the following
1993 if (TLI.isPow2DivCheap())
1996 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1998 // Splat the sign bit into the register
1999 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2000 DAG.getConstant(VT.getSizeInBits()-1,
2001 getShiftAmountTy(N0.getValueType())));
2002 AddToWorkList(SGN.getNode());
2004 // Add (N0 < 0) ? abs2 - 1 : 0;
2005 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2006 DAG.getConstant(VT.getSizeInBits() - lg2,
2007 getShiftAmountTy(SGN.getValueType())));
2008 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2009 AddToWorkList(SRL.getNode());
2010 AddToWorkList(ADD.getNode()); // Divide by pow2
2011 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2012 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2014 // If we're dividing by a positive value, we're done. Otherwise, we must
2015 // negate the result.
2016 if (N1C->getAPIntValue().isNonNegative())
2019 AddToWorkList(SRA.getNode());
2020 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2021 DAG.getConstant(0, VT), SRA);
2024 // if integer divide is expensive and we satisfy the requirements, emit an
2025 // alternate sequence.
2026 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2027 SDValue Op = BuildSDIV(N);
2028 if (Op.getNode()) return Op;
2032 if (N0.getOpcode() == ISD::UNDEF)
2033 return DAG.getConstant(0, VT);
2034 // X / undef -> undef
2035 if (N1.getOpcode() == ISD::UNDEF)
2041 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2042 SDValue N0 = N->getOperand(0);
2043 SDValue N1 = N->getOperand(1);
2044 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2045 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2046 EVT VT = N->getValueType(0);
2049 if (VT.isVector()) {
2050 SDValue FoldedVOp = SimplifyVBinOp(N);
2051 if (FoldedVOp.getNode()) return FoldedVOp;
2054 // fold (udiv c1, c2) -> c1/c2
2055 if (N0C && N1C && !N1C->isNullValue())
2056 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2057 // fold (udiv x, (1 << c)) -> x >>u c
2058 if (N1C && N1C->getAPIntValue().isPowerOf2())
2059 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2060 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2061 getShiftAmountTy(N0.getValueType())));
2062 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2063 if (N1.getOpcode() == ISD::SHL) {
2064 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2065 if (SHC->getAPIntValue().isPowerOf2()) {
2066 EVT ADDVT = N1.getOperand(1).getValueType();
2067 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2069 DAG.getConstant(SHC->getAPIntValue()
2072 AddToWorkList(Add.getNode());
2073 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2077 // fold (udiv x, c) -> alternate
2078 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2079 SDValue Op = BuildUDIV(N);
2080 if (Op.getNode()) return Op;
2084 if (N0.getOpcode() == ISD::UNDEF)
2085 return DAG.getConstant(0, VT);
2086 // X / undef -> undef
2087 if (N1.getOpcode() == ISD::UNDEF)
2093 SDValue DAGCombiner::visitSREM(SDNode *N) {
2094 SDValue N0 = N->getOperand(0);
2095 SDValue N1 = N->getOperand(1);
2096 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2097 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2098 EVT VT = N->getValueType(0);
2100 // fold (srem c1, c2) -> c1%c2
2101 if (N0C && N1C && !N1C->isNullValue())
2102 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2103 // If we know the sign bits of both operands are zero, strength reduce to a
2104 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2105 if (!VT.isVector()) {
2106 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2107 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2110 // If X/C can be simplified by the division-by-constant logic, lower
2111 // X%C to the equivalent of X-X/C*C.
2112 if (N1C && !N1C->isNullValue()) {
2113 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2114 AddToWorkList(Div.getNode());
2115 SDValue OptimizedDiv = combine(Div.getNode());
2116 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2117 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2119 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2120 AddToWorkList(Mul.getNode());
2126 if (N0.getOpcode() == ISD::UNDEF)
2127 return DAG.getConstant(0, VT);
2128 // X % undef -> undef
2129 if (N1.getOpcode() == ISD::UNDEF)
2135 SDValue DAGCombiner::visitUREM(SDNode *N) {
2136 SDValue N0 = N->getOperand(0);
2137 SDValue N1 = N->getOperand(1);
2138 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2139 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2140 EVT VT = N->getValueType(0);
2142 // fold (urem c1, c2) -> c1%c2
2143 if (N0C && N1C && !N1C->isNullValue())
2144 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2145 // fold (urem x, pow2) -> (and x, pow2-1)
2146 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2147 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2148 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2149 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2150 if (N1.getOpcode() == ISD::SHL) {
2151 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2152 if (SHC->getAPIntValue().isPowerOf2()) {
2154 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2155 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2157 AddToWorkList(Add.getNode());
2158 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2163 // If X/C can be simplified by the division-by-constant logic, lower
2164 // X%C to the equivalent of X-X/C*C.
2165 if (N1C && !N1C->isNullValue()) {
2166 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2167 AddToWorkList(Div.getNode());
2168 SDValue OptimizedDiv = combine(Div.getNode());
2169 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2170 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2172 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2173 AddToWorkList(Mul.getNode());
2179 if (N0.getOpcode() == ISD::UNDEF)
2180 return DAG.getConstant(0, VT);
2181 // X % undef -> undef
2182 if (N1.getOpcode() == ISD::UNDEF)
2188 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2189 SDValue N0 = N->getOperand(0);
2190 SDValue N1 = N->getOperand(1);
2191 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2192 EVT VT = N->getValueType(0);
2195 // fold (mulhs x, 0) -> 0
2196 if (N1C && N1C->isNullValue())
2198 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2199 if (N1C && N1C->getAPIntValue() == 1)
2200 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2201 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2202 getShiftAmountTy(N0.getValueType())));
2203 // fold (mulhs x, undef) -> 0
2204 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2205 return DAG.getConstant(0, VT);
2207 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2209 if (VT.isSimple() && !VT.isVector()) {
2210 MVT Simple = VT.getSimpleVT();
2211 unsigned SimpleSize = Simple.getSizeInBits();
2212 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2213 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2214 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2215 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2216 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2217 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2218 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2219 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2226 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2227 SDValue N0 = N->getOperand(0);
2228 SDValue N1 = N->getOperand(1);
2229 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2230 EVT VT = N->getValueType(0);
2233 // fold (mulhu x, 0) -> 0
2234 if (N1C && N1C->isNullValue())
2236 // fold (mulhu x, 1) -> 0
2237 if (N1C && N1C->getAPIntValue() == 1)
2238 return DAG.getConstant(0, N0.getValueType());
2239 // fold (mulhu x, undef) -> 0
2240 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2241 return DAG.getConstant(0, VT);
2243 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2245 if (VT.isSimple() && !VT.isVector()) {
2246 MVT Simple = VT.getSimpleVT();
2247 unsigned SimpleSize = Simple.getSizeInBits();
2248 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2249 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2250 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2251 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2252 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2253 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2254 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2255 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2262 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2263 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2264 /// that are being performed. Return true if a simplification was made.
2266 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2268 // If the high half is not needed, just compute the low half.
2269 bool HiExists = N->hasAnyUseOfValue(1);
2271 (!LegalOperations ||
2272 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2273 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2274 N->op_begin(), N->getNumOperands());
2275 return CombineTo(N, Res, Res);
2278 // If the low half is not needed, just compute the high half.
2279 bool LoExists = N->hasAnyUseOfValue(0);
2281 (!LegalOperations ||
2282 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2283 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2284 N->op_begin(), N->getNumOperands());
2285 return CombineTo(N, Res, Res);
2288 // If both halves are used, return as it is.
2289 if (LoExists && HiExists)
2292 // If the two computed results can be simplified separately, separate them.
2294 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2295 N->op_begin(), N->getNumOperands());
2296 AddToWorkList(Lo.getNode());
2297 SDValue LoOpt = combine(Lo.getNode());
2298 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2299 (!LegalOperations ||
2300 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2301 return CombineTo(N, LoOpt, LoOpt);
2305 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2306 N->op_begin(), N->getNumOperands());
2307 AddToWorkList(Hi.getNode());
2308 SDValue HiOpt = combine(Hi.getNode());
2309 if (HiOpt.getNode() && HiOpt != Hi &&
2310 (!LegalOperations ||
2311 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2312 return CombineTo(N, HiOpt, HiOpt);
2318 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2319 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2320 if (Res.getNode()) return Res;
2322 EVT VT = N->getValueType(0);
2325 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2327 if (VT.isSimple() && !VT.isVector()) {
2328 MVT Simple = VT.getSimpleVT();
2329 unsigned SimpleSize = Simple.getSizeInBits();
2330 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2331 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2332 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2333 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2334 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2335 // Compute the high part as N1.
2336 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2337 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2338 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2339 // Compute the low part as N0.
2340 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2341 return CombineTo(N, Lo, Hi);
2348 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2349 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2350 if (Res.getNode()) return Res;
2352 EVT VT = N->getValueType(0);
2355 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2357 if (VT.isSimple() && !VT.isVector()) {
2358 MVT Simple = VT.getSimpleVT();
2359 unsigned SimpleSize = Simple.getSizeInBits();
2360 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2361 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2362 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2363 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2364 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2365 // Compute the high part as N1.
2366 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2367 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2368 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2369 // Compute the low part as N0.
2370 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2371 return CombineTo(N, Lo, Hi);
2378 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2379 // (smulo x, 2) -> (saddo x, x)
2380 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2381 if (C2->getAPIntValue() == 2)
2382 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2383 N->getOperand(0), N->getOperand(0));
2388 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2389 // (umulo x, 2) -> (uaddo x, x)
2390 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2391 if (C2->getAPIntValue() == 2)
2392 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2393 N->getOperand(0), N->getOperand(0));
2398 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2399 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2400 if (Res.getNode()) return Res;
2405 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2406 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2407 if (Res.getNode()) return Res;
2412 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2413 /// two operands of the same opcode, try to simplify it.
2414 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2415 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2416 EVT VT = N0.getValueType();
2417 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2419 // Bail early if none of these transforms apply.
2420 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2422 // For each of OP in AND/OR/XOR:
2423 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2424 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2425 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2426 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2428 // do not sink logical op inside of a vector extend, since it may combine
2430 EVT Op0VT = N0.getOperand(0).getValueType();
2431 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2432 N0.getOpcode() == ISD::SIGN_EXTEND ||
2433 // Avoid infinite looping with PromoteIntBinOp.
2434 (N0.getOpcode() == ISD::ANY_EXTEND &&
2435 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2436 (N0.getOpcode() == ISD::TRUNCATE &&
2437 (!TLI.isZExtFree(VT, Op0VT) ||
2438 !TLI.isTruncateFree(Op0VT, VT)) &&
2439 TLI.isTypeLegal(Op0VT))) &&
2441 Op0VT == N1.getOperand(0).getValueType() &&
2442 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2443 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2444 N0.getOperand(0).getValueType(),
2445 N0.getOperand(0), N1.getOperand(0));
2446 AddToWorkList(ORNode.getNode());
2447 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2450 // For each of OP in SHL/SRL/SRA/AND...
2451 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2452 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2453 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2454 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2455 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2456 N0.getOperand(1) == N1.getOperand(1)) {
2457 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2458 N0.getOperand(0).getValueType(),
2459 N0.getOperand(0), N1.getOperand(0));
2460 AddToWorkList(ORNode.getNode());
2461 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2462 ORNode, N0.getOperand(1));
2465 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2466 // Only perform this optimization after type legalization and before
2467 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2468 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2469 // we don't want to undo this promotion.
2470 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2472 if ((N0.getOpcode() == ISD::BITCAST ||
2473 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2474 Level == AfterLegalizeTypes) {
2475 SDValue In0 = N0.getOperand(0);
2476 SDValue In1 = N1.getOperand(0);
2477 EVT In0Ty = In0.getValueType();
2478 EVT In1Ty = In1.getValueType();
2480 // If both incoming values are integers, and the original types are the
2482 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2483 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2484 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2485 AddToWorkList(Op.getNode());
2490 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2491 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2492 // If both shuffles use the same mask, and both shuffle within a single
2493 // vector, then it is worthwhile to move the swizzle after the operation.
2494 // The type-legalizer generates this pattern when loading illegal
2495 // vector types from memory. In many cases this allows additional shuffle
2497 // There are other cases where moving the shuffle after the xor/and/or
2498 // is profitable even if shuffles don't perform a swizzle.
2499 // If both shuffles use the same mask, and both shuffles have the same first
2500 // or second operand, then it might still be profitable to move the shuffle
2501 // after the xor/and/or operation.
2502 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2503 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2504 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2506 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2507 "Inputs to shuffles are not the same type");
2509 // Check that both shuffles use the same mask. The masks are known to be of
2510 // the same length because the result vector type is the same.
2511 // Check also that shuffles have only one use to avoid introducing extra
2513 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2514 SVN0->getMask().equals(SVN1->getMask())) {
2515 SDValue ShOp = N0->getOperand(1);
2517 // Don't try to fold this node if it requires introducing a
2518 // build vector of all zeros that might be illegal at this stage.
2519 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2521 ShOp = DAG.getConstant(0, VT);
2526 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2527 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2528 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2529 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2530 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2531 N0->getOperand(0), N1->getOperand(0));
2532 AddToWorkList(NewNode.getNode());
2533 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2534 &SVN0->getMask()[0]);
2537 // Don't try to fold this node if it requires introducing a
2538 // build vector of all zeros that might be illegal at this stage.
2539 ShOp = N0->getOperand(0);
2540 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2542 ShOp = DAG.getConstant(0, VT);
2547 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2548 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2549 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2550 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2551 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2552 N0->getOperand(1), N1->getOperand(1));
2553 AddToWorkList(NewNode.getNode());
2554 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2555 &SVN0->getMask()[0]);
2563 SDValue DAGCombiner::visitAND(SDNode *N) {
2564 SDValue N0 = N->getOperand(0);
2565 SDValue N1 = N->getOperand(1);
2566 SDValue LL, LR, RL, RR, CC0, CC1;
2567 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2568 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2569 EVT VT = N1.getValueType();
2570 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2573 if (VT.isVector()) {
2574 SDValue FoldedVOp = SimplifyVBinOp(N);
2575 if (FoldedVOp.getNode()) return FoldedVOp;
2577 // fold (and x, 0) -> 0, vector edition
2578 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2580 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2583 // fold (and x, -1) -> x, vector edition
2584 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2586 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2590 // fold (and x, undef) -> 0
2591 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2592 return DAG.getConstant(0, VT);
2593 // fold (and c1, c2) -> c1&c2
2595 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2596 // canonicalize constant to RHS
2598 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2599 // fold (and x, -1) -> x
2600 if (N1C && N1C->isAllOnesValue())
2602 // if (and x, c) is known to be zero, return 0
2603 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2604 APInt::getAllOnesValue(BitWidth)))
2605 return DAG.getConstant(0, VT);
2607 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2610 // fold (and (or x, C), D) -> D if (C & D) == D
2611 if (N1C && N0.getOpcode() == ISD::OR)
2612 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2613 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2615 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2616 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2617 SDValue N0Op0 = N0.getOperand(0);
2618 APInt Mask = ~N1C->getAPIntValue();
2619 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2620 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2621 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2622 N0.getValueType(), N0Op0);
2624 // Replace uses of the AND with uses of the Zero extend node.
2627 // We actually want to replace all uses of the any_extend with the
2628 // zero_extend, to avoid duplicating things. This will later cause this
2629 // AND to be folded.
2630 CombineTo(N0.getNode(), Zext);
2631 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2634 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2635 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2636 // already be zero by virtue of the width of the base type of the load.
2638 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2640 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2641 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2642 N0.getOpcode() == ISD::LOAD) {
2643 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2644 N0 : N0.getOperand(0) );
2646 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2647 // This can be a pure constant or a vector splat, in which case we treat the
2648 // vector as a scalar and use the splat value.
2649 APInt Constant = APInt::getNullValue(1);
2650 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2651 Constant = C->getAPIntValue();
2652 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2653 APInt SplatValue, SplatUndef;
2654 unsigned SplatBitSize;
2656 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2657 SplatBitSize, HasAnyUndefs);
2659 // Undef bits can contribute to a possible optimisation if set, so
2661 SplatValue |= SplatUndef;
2663 // The splat value may be something like "0x00FFFFFF", which means 0 for
2664 // the first vector value and FF for the rest, repeating. We need a mask
2665 // that will apply equally to all members of the vector, so AND all the
2666 // lanes of the constant together.
2667 EVT VT = Vector->getValueType(0);
2668 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2670 // If the splat value has been compressed to a bitlength lower
2671 // than the size of the vector lane, we need to re-expand it to
2673 if (BitWidth > SplatBitSize)
2674 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2675 SplatBitSize < BitWidth;
2676 SplatBitSize = SplatBitSize * 2)
2677 SplatValue |= SplatValue.shl(SplatBitSize);
2679 Constant = APInt::getAllOnesValue(BitWidth);
2680 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2681 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2685 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2686 // actually legal and isn't going to get expanded, else this is a false
2688 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2689 Load->getMemoryVT());
2691 // Resize the constant to the same size as the original memory access before
2692 // extension. If it is still the AllOnesValue then this AND is completely
2695 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2698 switch (Load->getExtensionType()) {
2699 default: B = false; break;
2700 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2702 case ISD::NON_EXTLOAD: B = true; break;
2705 if (B && Constant.isAllOnesValue()) {
2706 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2707 // preserve semantics once we get rid of the AND.
2708 SDValue NewLoad(Load, 0);
2709 if (Load->getExtensionType() == ISD::EXTLOAD) {
2710 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2711 Load->getValueType(0), SDLoc(Load),
2712 Load->getChain(), Load->getBasePtr(),
2713 Load->getOffset(), Load->getMemoryVT(),
2714 Load->getMemOperand());
2715 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2716 if (Load->getNumValues() == 3) {
2717 // PRE/POST_INC loads have 3 values.
2718 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2719 NewLoad.getValue(2) };
2720 CombineTo(Load, To, 3, true);
2722 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2726 // Fold the AND away, taking care not to fold to the old load node if we
2728 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2730 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2733 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2734 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2735 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2736 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2738 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2739 LL.getValueType().isInteger()) {
2740 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2741 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2742 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2743 LR.getValueType(), LL, RL);
2744 AddToWorkList(ORNode.getNode());
2745 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2747 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2748 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2749 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2750 LR.getValueType(), LL, RL);
2751 AddToWorkList(ANDNode.getNode());
2752 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2754 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2755 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2756 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2757 LR.getValueType(), LL, RL);
2758 AddToWorkList(ORNode.getNode());
2759 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2762 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2763 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2764 Op0 == Op1 && LL.getValueType().isInteger() &&
2765 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2766 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2767 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2768 cast<ConstantSDNode>(RR)->isNullValue()))) {
2769 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2770 LL, DAG.getConstant(1, LL.getValueType()));
2771 AddToWorkList(ADDNode.getNode());
2772 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2773 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2775 // canonicalize equivalent to ll == rl
2776 if (LL == RR && LR == RL) {
2777 Op1 = ISD::getSetCCSwappedOperands(Op1);
2780 if (LL == RL && LR == RR) {
2781 bool isInteger = LL.getValueType().isInteger();
2782 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2783 if (Result != ISD::SETCC_INVALID &&
2784 (!LegalOperations ||
2785 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2786 TLI.isOperationLegal(ISD::SETCC,
2787 getSetCCResultType(N0.getSimpleValueType())))))
2788 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2793 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2794 if (N0.getOpcode() == N1.getOpcode()) {
2795 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2796 if (Tmp.getNode()) return Tmp;
2799 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2800 // fold (and (sra)) -> (and (srl)) when possible.
2801 if (!VT.isVector() &&
2802 SimplifyDemandedBits(SDValue(N, 0)))
2803 return SDValue(N, 0);
2805 // fold (zext_inreg (extload x)) -> (zextload x)
2806 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2807 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2808 EVT MemVT = LN0->getMemoryVT();
2809 // If we zero all the possible extended bits, then we can turn this into
2810 // a zextload if we are running before legalize or the operation is legal.
2811 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2812 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2813 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2814 ((!LegalOperations && !LN0->isVolatile()) ||
2815 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2816 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2817 LN0->getChain(), LN0->getBasePtr(),
2818 MemVT, LN0->getMemOperand());
2820 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2821 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2824 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2825 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2827 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2828 EVT MemVT = LN0->getMemoryVT();
2829 // If we zero all the possible extended bits, then we can turn this into
2830 // a zextload if we are running before legalize or the operation is legal.
2831 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2832 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2833 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2834 ((!LegalOperations && !LN0->isVolatile()) ||
2835 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2836 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2837 LN0->getChain(), LN0->getBasePtr(),
2838 MemVT, LN0->getMemOperand());
2840 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2841 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2845 // fold (and (load x), 255) -> (zextload x, i8)
2846 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2847 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2848 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2849 (N0.getOpcode() == ISD::ANY_EXTEND &&
2850 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2851 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2852 LoadSDNode *LN0 = HasAnyExt
2853 ? cast<LoadSDNode>(N0.getOperand(0))
2854 : cast<LoadSDNode>(N0);
2855 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2856 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2857 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2858 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2859 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2860 EVT LoadedVT = LN0->getMemoryVT();
2862 if (ExtVT == LoadedVT &&
2863 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2864 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2867 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2868 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2869 LN0->getMemOperand());
2871 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2872 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2875 // Do not change the width of a volatile load.
2876 // Do not generate loads of non-round integer types since these can
2877 // be expensive (and would be wrong if the type is not byte sized).
2878 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2879 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2880 EVT PtrType = LN0->getOperand(1).getValueType();
2882 unsigned Alignment = LN0->getAlignment();
2883 SDValue NewPtr = LN0->getBasePtr();
2885 // For big endian targets, we need to add an offset to the pointer
2886 // to load the correct bytes. For little endian systems, we merely
2887 // need to read fewer bytes from the same pointer.
2888 if (TLI.isBigEndian()) {
2889 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2890 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2891 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2892 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2893 NewPtr, DAG.getConstant(PtrOff, PtrType));
2894 Alignment = MinAlign(Alignment, PtrOff);
2897 AddToWorkList(NewPtr.getNode());
2899 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2901 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2902 LN0->getChain(), NewPtr,
2903 LN0->getPointerInfo(),
2904 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2905 Alignment, LN0->getTBAAInfo());
2907 CombineTo(LN0, Load, Load.getValue(1));
2908 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2914 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2915 VT.getSizeInBits() <= 64) {
2916 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2917 APInt ADDC = ADDI->getAPIntValue();
2918 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2919 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2920 // immediate for an add, but it is legal if its top c2 bits are set,
2921 // transform the ADD so the immediate doesn't need to be materialized
2923 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2924 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2925 SRLI->getZExtValue());
2926 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2928 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2930 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2931 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2932 CombineTo(N0.getNode(), NewAdd);
2933 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2941 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2942 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2943 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2944 N0.getOperand(1), false);
2945 if (BSwap.getNode())
2952 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2954 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2955 bool DemandHighBits) {
2956 if (!LegalOperations)
2959 EVT VT = N->getValueType(0);
2960 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2962 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2965 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2966 bool LookPassAnd0 = false;
2967 bool LookPassAnd1 = false;
2968 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2970 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2972 if (N0.getOpcode() == ISD::AND) {
2973 if (!N0.getNode()->hasOneUse())
2975 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2976 if (!N01C || N01C->getZExtValue() != 0xFF00)
2978 N0 = N0.getOperand(0);
2979 LookPassAnd0 = true;
2982 if (N1.getOpcode() == ISD::AND) {
2983 if (!N1.getNode()->hasOneUse())
2985 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2986 if (!N11C || N11C->getZExtValue() != 0xFF)
2988 N1 = N1.getOperand(0);
2989 LookPassAnd1 = true;
2992 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2994 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2996 if (!N0.getNode()->hasOneUse() ||
2997 !N1.getNode()->hasOneUse())
3000 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3001 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3004 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3007 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3008 SDValue N00 = N0->getOperand(0);
3009 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3010 if (!N00.getNode()->hasOneUse())
3012 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3013 if (!N001C || N001C->getZExtValue() != 0xFF)
3015 N00 = N00.getOperand(0);
3016 LookPassAnd0 = true;
3019 SDValue N10 = N1->getOperand(0);
3020 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3021 if (!N10.getNode()->hasOneUse())
3023 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3024 if (!N101C || N101C->getZExtValue() != 0xFF00)
3026 N10 = N10.getOperand(0);
3027 LookPassAnd1 = true;
3033 // Make sure everything beyond the low halfword gets set to zero since the SRL
3034 // 16 will clear the top bits.
3035 unsigned OpSizeInBits = VT.getSizeInBits();
3036 if (DemandHighBits && OpSizeInBits > 16) {
3037 // If the left-shift isn't masked out then the only way this is a bswap is
3038 // if all bits beyond the low 8 are 0. In that case the entire pattern
3039 // reduces to a left shift anyway: leave it for other parts of the combiner.
3043 // However, if the right shift isn't masked out then it might be because
3044 // it's not needed. See if we can spot that too.
3045 if (!LookPassAnd1 &&
3046 !DAG.MaskedValueIsZero(
3047 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3051 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3052 if (OpSizeInBits > 16)
3053 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3054 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3058 /// isBSwapHWordElement - Return true if the specified node is an element
3059 /// that makes up a 32-bit packed halfword byteswap. i.e.
3060 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3061 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3062 if (!N.getNode()->hasOneUse())
3065 unsigned Opc = N.getOpcode();
3066 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3069 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3074 switch (N1C->getZExtValue()) {
3077 case 0xFF: Num = 0; break;
3078 case 0xFF00: Num = 1; break;
3079 case 0xFF0000: Num = 2; break;
3080 case 0xFF000000: Num = 3; break;
3083 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3084 SDValue N0 = N.getOperand(0);
3085 if (Opc == ISD::AND) {
3086 if (Num == 0 || Num == 2) {
3088 // (x >> 8) & 0xff0000
3089 if (N0.getOpcode() != ISD::SRL)
3091 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3092 if (!C || C->getZExtValue() != 8)
3095 // (x << 8) & 0xff00
3096 // (x << 8) & 0xff000000
3097 if (N0.getOpcode() != ISD::SHL)
3099 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3100 if (!C || C->getZExtValue() != 8)
3103 } else if (Opc == ISD::SHL) {
3105 // (x & 0xff0000) << 8
3106 if (Num != 0 && Num != 2)
3108 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3109 if (!C || C->getZExtValue() != 8)
3111 } else { // Opc == ISD::SRL
3112 // (x & 0xff00) >> 8
3113 // (x & 0xff000000) >> 8
3114 if (Num != 1 && Num != 3)
3116 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3117 if (!C || C->getZExtValue() != 8)
3124 Parts[Num] = N0.getOperand(0).getNode();
3128 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3129 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3130 /// => (rotl (bswap x), 16)
3131 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3132 if (!LegalOperations)
3135 EVT VT = N->getValueType(0);
3138 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3141 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3143 // (or (or (and), (and)), (or (and), (and)))
3144 // (or (or (or (and), (and)), (and)), (and))
3145 if (N0.getOpcode() != ISD::OR)
3147 SDValue N00 = N0.getOperand(0);
3148 SDValue N01 = N0.getOperand(1);
3150 if (N1.getOpcode() == ISD::OR &&
3151 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3152 // (or (or (and), (and)), (or (and), (and)))
3153 SDValue N000 = N00.getOperand(0);
3154 if (!isBSwapHWordElement(N000, Parts))
3157 SDValue N001 = N00.getOperand(1);
3158 if (!isBSwapHWordElement(N001, Parts))
3160 SDValue N010 = N01.getOperand(0);
3161 if (!isBSwapHWordElement(N010, Parts))
3163 SDValue N011 = N01.getOperand(1);
3164 if (!isBSwapHWordElement(N011, Parts))
3167 // (or (or (or (and), (and)), (and)), (and))
3168 if (!isBSwapHWordElement(N1, Parts))
3170 if (!isBSwapHWordElement(N01, Parts))
3172 if (N00.getOpcode() != ISD::OR)
3174 SDValue N000 = N00.getOperand(0);
3175 if (!isBSwapHWordElement(N000, Parts))
3177 SDValue N001 = N00.getOperand(1);
3178 if (!isBSwapHWordElement(N001, Parts))
3182 // Make sure the parts are all coming from the same node.
3183 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3186 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3187 SDValue(Parts[0],0));
3189 // Result of the bswap should be rotated by 16. If it's not legal, then
3190 // do (x << 16) | (x >> 16).
3191 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3192 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3193 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3194 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3195 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3196 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3197 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3198 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3201 SDValue DAGCombiner::visitOR(SDNode *N) {
3202 SDValue N0 = N->getOperand(0);
3203 SDValue N1 = N->getOperand(1);
3204 SDValue LL, LR, RL, RR, CC0, CC1;
3205 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3206 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3207 EVT VT = N1.getValueType();
3210 if (VT.isVector()) {
3211 SDValue FoldedVOp = SimplifyVBinOp(N);
3212 if (FoldedVOp.getNode()) return FoldedVOp;
3214 // fold (or x, 0) -> x, vector edition
3215 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3217 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3220 // fold (or x, -1) -> -1, vector edition
3221 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3223 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3226 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3227 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3228 // Do this only if the resulting shuffle is legal.
3229 if (isa<ShuffleVectorSDNode>(N0) &&
3230 isa<ShuffleVectorSDNode>(N1) &&
3231 N0->getOperand(1) == N1->getOperand(1) &&
3232 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3233 bool CanFold = true;
3234 unsigned NumElts = VT.getVectorNumElements();
3235 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3236 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3237 // We construct two shuffle masks:
3238 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3239 // and N1 as the second operand.
3240 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3241 // and N0 as the second operand.
3242 // We do this because OR is commutable and therefore there might be
3243 // two ways to fold this node into a shuffle.
3244 SmallVector<int,4> Mask1;
3245 SmallVector<int,4> Mask2;
3247 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3248 int M0 = SV0->getMaskElt(i);
3249 int M1 = SV1->getMaskElt(i);
3251 // Both shuffle indexes are undef. Propagate Undef.
3252 if (M0 < 0 && M1 < 0) {
3253 Mask1.push_back(M0);
3254 Mask2.push_back(M0);
3258 if (M0 < 0 || M1 < 0 ||
3259 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3260 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3265 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3266 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3270 // Fold this sequence only if the resulting shuffle is 'legal'.
3271 if (TLI.isShuffleMaskLegal(Mask1, VT))
3272 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3273 N1->getOperand(0), &Mask1[0]);
3274 if (TLI.isShuffleMaskLegal(Mask2, VT))
3275 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3276 N0->getOperand(0), &Mask2[0]);
3281 // fold (or x, undef) -> -1
3282 if (!LegalOperations &&
3283 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3284 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3285 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3287 // fold (or c1, c2) -> c1|c2
3289 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3290 // canonicalize constant to RHS
3292 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3293 // fold (or x, 0) -> x
3294 if (N1C && N1C->isNullValue())
3296 // fold (or x, -1) -> -1
3297 if (N1C && N1C->isAllOnesValue())
3299 // fold (or x, c) -> c iff (x & ~c) == 0
3300 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3303 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3304 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3305 if (BSwap.getNode())
3307 BSwap = MatchBSwapHWordLow(N, N0, N1);
3308 if (BSwap.getNode())
3312 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3315 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3316 // iff (c1 & c2) == 0.
3317 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3318 isa<ConstantSDNode>(N0.getOperand(1))) {
3319 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3320 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3321 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3324 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3325 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3326 N0.getOperand(0), N1), COR);
3329 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3330 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3331 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3332 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3334 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3335 LL.getValueType().isInteger()) {
3336 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3337 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3338 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3339 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3340 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3341 LR.getValueType(), LL, RL);
3342 AddToWorkList(ORNode.getNode());
3343 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3345 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3346 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3347 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3348 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3349 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3350 LR.getValueType(), LL, RL);
3351 AddToWorkList(ANDNode.getNode());
3352 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3355 // canonicalize equivalent to ll == rl
3356 if (LL == RR && LR == RL) {
3357 Op1 = ISD::getSetCCSwappedOperands(Op1);
3360 if (LL == RL && LR == RR) {
3361 bool isInteger = LL.getValueType().isInteger();
3362 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3363 if (Result != ISD::SETCC_INVALID &&
3364 (!LegalOperations ||
3365 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3366 TLI.isOperationLegal(ISD::SETCC,
3367 getSetCCResultType(N0.getValueType())))))
3368 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3373 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3374 if (N0.getOpcode() == N1.getOpcode()) {
3375 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3376 if (Tmp.getNode()) return Tmp;
3379 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3380 if (N0.getOpcode() == ISD::AND &&
3381 N1.getOpcode() == ISD::AND &&
3382 N0.getOperand(1).getOpcode() == ISD::Constant &&
3383 N1.getOperand(1).getOpcode() == ISD::Constant &&
3384 // Don't increase # computations.
3385 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3386 // We can only do this xform if we know that bits from X that are set in C2
3387 // but not in C1 are already zero. Likewise for Y.
3388 const APInt &LHSMask =
3389 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3390 const APInt &RHSMask =
3391 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3393 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3394 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3395 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3396 N0.getOperand(0), N1.getOperand(0));
3397 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3398 DAG.getConstant(LHSMask | RHSMask, VT));
3402 // See if this is some rotate idiom.
3403 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3404 return SDValue(Rot, 0);
3406 // Simplify the operands using demanded-bits information.
3407 if (!VT.isVector() &&
3408 SimplifyDemandedBits(SDValue(N, 0)))
3409 return SDValue(N, 0);
3414 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3415 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3416 if (Op.getOpcode() == ISD::AND) {
3417 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3418 Mask = Op.getOperand(1);
3419 Op = Op.getOperand(0);
3425 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3433 // Return true if we can prove that, whenever Neg and Pos are both in the
3434 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3435 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3437 // (or (shift1 X, Neg), (shift2 X, Pos))
3439 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3440 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3441 // to consider shift amounts with defined behavior.
3442 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3443 // If OpSize is a power of 2 then:
3445 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3446 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3448 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3449 // for the stronger condition:
3451 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3453 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3454 // we can just replace Neg with Neg' for the rest of the function.
3456 // In other cases we check for the even stronger condition:
3458 // Neg == OpSize - Pos [B]
3460 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3461 // behavior if Pos == 0 (and consequently Neg == OpSize).
3463 // We could actually use [A] whenever OpSize is a power of 2, but the
3464 // only extra cases that it would match are those uninteresting ones
3465 // where Neg and Pos are never in range at the same time. E.g. for
3466 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3467 // as well as (sub 32, Pos), but:
3469 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3471 // always invokes undefined behavior for 32-bit X.
3473 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3474 unsigned MaskLoBits = 0;
3475 if (Neg.getOpcode() == ISD::AND &&
3476 isPowerOf2_64(OpSize) &&
3477 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3478 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3479 Neg = Neg.getOperand(0);
3480 MaskLoBits = Log2_64(OpSize);
3483 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3484 if (Neg.getOpcode() != ISD::SUB)
3486 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3489 SDValue NegOp1 = Neg.getOperand(1);
3491 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3492 // Pos'. The truncation is redundant for the purpose of the equality.
3494 Pos.getOpcode() == ISD::AND &&
3495 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3496 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3497 Pos = Pos.getOperand(0);
3499 // The condition we need is now:
3501 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3503 // If NegOp1 == Pos then we need:
3505 // OpSize & Mask == NegC & Mask
3507 // (because "x & Mask" is a truncation and distributes through subtraction).
3510 Width = NegC->getAPIntValue();
3511 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3512 // Then the condition we want to prove becomes:
3514 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3516 // which, again because "x & Mask" is a truncation, becomes:
3518 // NegC & Mask == (OpSize - PosC) & Mask
3519 // OpSize & Mask == (NegC + PosC) & Mask
3520 else if (Pos.getOpcode() == ISD::ADD &&
3521 Pos.getOperand(0) == NegOp1 &&
3522 Pos.getOperand(1).getOpcode() == ISD::Constant)
3523 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3524 NegC->getAPIntValue());
3528 // Now we just need to check that OpSize & Mask == Width & Mask.
3530 // Opsize & Mask is 0 since Mask is Opsize - 1.
3531 return Width.getLoBits(MaskLoBits) == 0;
3532 return Width == OpSize;
3535 // A subroutine of MatchRotate used once we have found an OR of two opposite
3536 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3537 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3538 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3539 // Neg with outer conversions stripped away.
3540 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3541 SDValue Neg, SDValue InnerPos,
3542 SDValue InnerNeg, unsigned PosOpcode,
3543 unsigned NegOpcode, SDLoc DL) {
3544 // fold (or (shl x, (*ext y)),
3545 // (srl x, (*ext (sub 32, y)))) ->
3546 // (rotl x, y) or (rotr x, (sub 32, y))
3548 // fold (or (shl x, (*ext (sub 32, y))),
3549 // (srl x, (*ext y))) ->
3550 // (rotr x, y) or (rotl x, (sub 32, y))
3551 EVT VT = Shifted.getValueType();
3552 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3553 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3554 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3555 HasPos ? Pos : Neg).getNode();
3558 // fold (or (shl (*ext x), (*ext y)),
3559 // (srl (*ext x), (*ext (sub 32, y)))) ->
3560 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3562 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3563 // (srl (*ext x), (*ext y))) ->
3564 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3565 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3566 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3567 SDValue InnerShifted = Shifted.getOperand(0);
3568 EVT InnerVT = InnerShifted.getValueType();
3569 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3570 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3571 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3572 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3573 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3574 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3582 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3583 // idioms for rotate, and if the target supports rotation instructions, generate
3585 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3586 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3587 EVT VT = LHS.getValueType();
3588 if (!TLI.isTypeLegal(VT)) return nullptr;
3590 // The target must have at least one rotate flavor.
3591 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3592 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3593 if (!HasROTL && !HasROTR) return nullptr;
3595 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3596 SDValue LHSShift; // The shift.
3597 SDValue LHSMask; // AND value if any.
3598 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3599 return nullptr; // Not part of a rotate.
3601 SDValue RHSShift; // The shift.
3602 SDValue RHSMask; // AND value if any.
3603 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3604 return nullptr; // Not part of a rotate.
3606 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3607 return nullptr; // Not shifting the same value.
3609 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3610 return nullptr; // Shifts must disagree.
3612 // Canonicalize shl to left side in a shl/srl pair.
3613 if (RHSShift.getOpcode() == ISD::SHL) {
3614 std::swap(LHS, RHS);
3615 std::swap(LHSShift, RHSShift);
3616 std::swap(LHSMask , RHSMask );
3619 unsigned OpSizeInBits = VT.getSizeInBits();
3620 SDValue LHSShiftArg = LHSShift.getOperand(0);
3621 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3622 SDValue RHSShiftArg = RHSShift.getOperand(0);
3623 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3625 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3626 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3627 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3628 RHSShiftAmt.getOpcode() == ISD::Constant) {
3629 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3630 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3631 if ((LShVal + RShVal) != OpSizeInBits)
3634 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3635 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3637 // If there is an AND of either shifted operand, apply it to the result.
3638 if (LHSMask.getNode() || RHSMask.getNode()) {
3639 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3641 if (LHSMask.getNode()) {
3642 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3643 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3645 if (RHSMask.getNode()) {
3646 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3647 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3650 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3653 return Rot.getNode();
3656 // If there is a mask here, and we have a variable shift, we can't be sure
3657 // that we're masking out the right stuff.
3658 if (LHSMask.getNode() || RHSMask.getNode())
3661 // If the shift amount is sign/zext/any-extended just peel it off.
3662 SDValue LExtOp0 = LHSShiftAmt;
3663 SDValue RExtOp0 = RHSShiftAmt;
3664 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3665 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3666 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3667 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3668 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3669 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3670 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3671 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3672 LExtOp0 = LHSShiftAmt.getOperand(0);
3673 RExtOp0 = RHSShiftAmt.getOperand(0);
3676 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3677 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3681 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3682 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3689 SDValue DAGCombiner::visitXOR(SDNode *N) {
3690 SDValue N0 = N->getOperand(0);
3691 SDValue N1 = N->getOperand(1);
3692 SDValue LHS, RHS, CC;
3693 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3694 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3695 EVT VT = N0.getValueType();
3698 if (VT.isVector()) {
3699 SDValue FoldedVOp = SimplifyVBinOp(N);
3700 if (FoldedVOp.getNode()) return FoldedVOp;
3702 // fold (xor x, 0) -> x, vector edition
3703 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3705 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3709 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3710 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3711 return DAG.getConstant(0, VT);
3712 // fold (xor x, undef) -> undef
3713 if (N0.getOpcode() == ISD::UNDEF)
3715 if (N1.getOpcode() == ISD::UNDEF)
3717 // fold (xor c1, c2) -> c1^c2
3719 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3720 // canonicalize constant to RHS
3722 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3723 // fold (xor x, 0) -> x
3724 if (N1C && N1C->isNullValue())
3727 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3731 // fold !(x cc y) -> (x !cc y)
3732 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3733 bool isInt = LHS.getValueType().isInteger();
3734 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3737 if (!LegalOperations ||
3738 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3739 switch (N0.getOpcode()) {
3741 llvm_unreachable("Unhandled SetCC Equivalent!");
3743 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3744 case ISD::SELECT_CC:
3745 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3746 N0.getOperand(3), NotCC);
3751 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3752 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3753 N0.getNode()->hasOneUse() &&
3754 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3755 SDValue V = N0.getOperand(0);
3756 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3757 DAG.getConstant(1, V.getValueType()));
3758 AddToWorkList(V.getNode());
3759 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3762 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3763 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3764 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3765 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3766 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3767 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3768 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3769 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3770 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3771 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3774 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3775 if (N1C && N1C->isAllOnesValue() &&
3776 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3777 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3778 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3779 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3780 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3781 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3782 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3783 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3786 // fold (xor (and x, y), y) -> (and (not x), y)
3787 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3788 N0->getOperand(1) == N1) {
3789 SDValue X = N0->getOperand(0);
3790 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3791 AddToWorkList(NotX.getNode());
3792 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3794 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3795 if (N1C && N0.getOpcode() == ISD::XOR) {
3796 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3797 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3799 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3800 DAG.getConstant(N1C->getAPIntValue() ^
3801 N00C->getAPIntValue(), VT));
3803 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3804 DAG.getConstant(N1C->getAPIntValue() ^
3805 N01C->getAPIntValue(), VT));
3807 // fold (xor x, x) -> 0
3809 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3811 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3812 if (N0.getOpcode() == N1.getOpcode()) {
3813 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3814 if (Tmp.getNode()) return Tmp;
3817 // Simplify the expression using non-local knowledge.
3818 if (!VT.isVector() &&
3819 SimplifyDemandedBits(SDValue(N, 0)))
3820 return SDValue(N, 0);
3825 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3826 /// the shift amount is a constant.
3827 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3828 // We can't and shouldn't fold opaque constants.
3829 if (Amt->isOpaque())
3832 SDNode *LHS = N->getOperand(0).getNode();
3833 if (!LHS->hasOneUse()) return SDValue();
3835 // We want to pull some binops through shifts, so that we have (and (shift))
3836 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3837 // thing happens with address calculations, so it's important to canonicalize
3839 bool HighBitSet = false; // Can we transform this if the high bit is set?
3841 switch (LHS->getOpcode()) {
3842 default: return SDValue();
3845 HighBitSet = false; // We can only transform sra if the high bit is clear.
3848 HighBitSet = true; // We can only transform sra if the high bit is set.
3851 if (N->getOpcode() != ISD::SHL)
3852 return SDValue(); // only shl(add) not sr[al](add).
3853 HighBitSet = false; // We can only transform sra if the high bit is clear.
3857 // We require the RHS of the binop to be a constant and not opaque as well.
3858 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3859 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3861 // FIXME: disable this unless the input to the binop is a shift by a constant.
3862 // If it is not a shift, it pessimizes some common cases like:
3864 // void foo(int *X, int i) { X[i & 1235] = 1; }
3865 // int bar(int *X, int i) { return X[i & 255]; }
3866 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3867 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3868 BinOpLHSVal->getOpcode() != ISD::SRA &&
3869 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3870 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3873 EVT VT = N->getValueType(0);
3875 // If this is a signed shift right, and the high bit is modified by the
3876 // logical operation, do not perform the transformation. The highBitSet
3877 // boolean indicates the value of the high bit of the constant which would
3878 // cause it to be modified for this operation.
3879 if (N->getOpcode() == ISD::SRA) {
3880 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3881 if (BinOpRHSSignSet != HighBitSet)
3885 // Fold the constants, shifting the binop RHS by the shift amount.
3886 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3888 LHS->getOperand(1), N->getOperand(1));
3889 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3891 // Create the new shift.
3892 SDValue NewShift = DAG.getNode(N->getOpcode(),
3893 SDLoc(LHS->getOperand(0)),
3894 VT, LHS->getOperand(0), N->getOperand(1));
3896 // Create the new binop.
3897 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3900 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3901 assert(N->getOpcode() == ISD::TRUNCATE);
3902 assert(N->getOperand(0).getOpcode() == ISD::AND);
3904 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3905 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3906 SDValue N01 = N->getOperand(0).getOperand(1);
3908 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3909 EVT TruncVT = N->getValueType(0);
3910 SDValue N00 = N->getOperand(0).getOperand(0);
3911 APInt TruncC = N01C->getAPIntValue();
3912 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3914 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3915 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3916 DAG.getConstant(TruncC, TruncVT));
3923 SDValue DAGCombiner::visitRotate(SDNode *N) {
3924 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3925 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3926 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3927 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3928 if (NewOp1.getNode())
3929 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3930 N->getOperand(0), NewOp1);
3935 SDValue DAGCombiner::visitSHL(SDNode *N) {
3936 SDValue N0 = N->getOperand(0);
3937 SDValue N1 = N->getOperand(1);
3938 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3939 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3940 EVT VT = N0.getValueType();
3941 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3944 if (VT.isVector()) {
3945 SDValue FoldedVOp = SimplifyVBinOp(N);
3946 if (FoldedVOp.getNode()) return FoldedVOp;
3948 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3949 // If setcc produces all-one true value then:
3950 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3951 if (N1CV && N1CV->isConstant()) {
3952 if (N0.getOpcode() == ISD::AND &&
3953 TLI.getBooleanContents(true) ==
3954 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3955 SDValue N00 = N0->getOperand(0);
3956 SDValue N01 = N0->getOperand(1);
3957 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3959 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3960 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3962 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3965 N1C = isConstOrConstSplat(N1);
3970 // fold (shl c1, c2) -> c1<<c2
3972 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3973 // fold (shl 0, x) -> 0
3974 if (N0C && N0C->isNullValue())
3976 // fold (shl x, c >= size(x)) -> undef
3977 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3978 return DAG.getUNDEF(VT);
3979 // fold (shl x, 0) -> x
3980 if (N1C && N1C->isNullValue())
3982 // fold (shl undef, x) -> 0
3983 if (N0.getOpcode() == ISD::UNDEF)
3984 return DAG.getConstant(0, VT);
3985 // if (shl x, c) is known to be zero, return 0
3986 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3987 APInt::getAllOnesValue(OpSizeInBits)))
3988 return DAG.getConstant(0, VT);
3989 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3990 if (N1.getOpcode() == ISD::TRUNCATE &&
3991 N1.getOperand(0).getOpcode() == ISD::AND) {
3992 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3993 if (NewOp1.getNode())
3994 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3997 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3998 return SDValue(N, 0);
4000 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4001 if (N1C && N0.getOpcode() == ISD::SHL) {
4002 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4003 uint64_t c1 = N0C1->getZExtValue();
4004 uint64_t c2 = N1C->getZExtValue();
4005 if (c1 + c2 >= OpSizeInBits)
4006 return DAG.getConstant(0, VT);
4007 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4008 DAG.getConstant(c1 + c2, N1.getValueType()));
4012 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4013 // For this to be valid, the second form must not preserve any of the bits
4014 // that are shifted out by the inner shift in the first form. This means
4015 // the outer shift size must be >= the number of bits added by the ext.
4016 // As a corollary, we don't care what kind of ext it is.
4017 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4018 N0.getOpcode() == ISD::ANY_EXTEND ||
4019 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4020 N0.getOperand(0).getOpcode() == ISD::SHL) {
4021 SDValue N0Op0 = N0.getOperand(0);
4022 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4023 uint64_t c1 = N0Op0C1->getZExtValue();
4024 uint64_t c2 = N1C->getZExtValue();
4025 EVT InnerShiftVT = N0Op0.getValueType();
4026 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4027 if (c2 >= OpSizeInBits - InnerShiftSize) {
4028 if (c1 + c2 >= OpSizeInBits)
4029 return DAG.getConstant(0, VT);
4030 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4031 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4032 N0Op0->getOperand(0)),
4033 DAG.getConstant(c1 + c2, N1.getValueType()));
4038 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4039 // Only fold this if the inner zext has no other uses to avoid increasing
4040 // the total number of instructions.
4041 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4042 N0.getOperand(0).getOpcode() == ISD::SRL) {
4043 SDValue N0Op0 = N0.getOperand(0);
4044 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4045 uint64_t c1 = N0Op0C1->getZExtValue();
4046 if (c1 < VT.getScalarSizeInBits()) {
4047 uint64_t c2 = N1C->getZExtValue();
4049 SDValue NewOp0 = N0.getOperand(0);
4050 EVT CountVT = NewOp0.getOperand(1).getValueType();
4051 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4052 NewOp0, DAG.getConstant(c2, CountVT));
4053 AddToWorkList(NewSHL.getNode());
4054 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4060 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4061 // (and (srl x, (sub c1, c2), MASK)
4062 // Only fold this if the inner shift has no other uses -- if it does, folding
4063 // this will increase the total number of instructions.
4064 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4065 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4066 uint64_t c1 = N0C1->getZExtValue();
4067 if (c1 < OpSizeInBits) {
4068 uint64_t c2 = N1C->getZExtValue();
4069 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4072 Mask = Mask.shl(c2 - c1);
4073 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4074 DAG.getConstant(c2 - c1, N1.getValueType()));
4076 Mask = Mask.lshr(c1 - c2);
4077 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4078 DAG.getConstant(c1 - c2, N1.getValueType()));
4080 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4081 DAG.getConstant(Mask, VT));
4085 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4086 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4087 unsigned BitSize = VT.getScalarSizeInBits();
4088 SDValue HiBitsMask =
4089 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4090 BitSize - N1C->getZExtValue()), VT);
4091 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4096 SDValue NewSHL = visitShiftByConstant(N, N1C);
4097 if (NewSHL.getNode())
4104 SDValue DAGCombiner::visitSRA(SDNode *N) {
4105 SDValue N0 = N->getOperand(0);
4106 SDValue N1 = N->getOperand(1);
4107 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4108 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4109 EVT VT = N0.getValueType();
4110 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4113 if (VT.isVector()) {
4114 SDValue FoldedVOp = SimplifyVBinOp(N);
4115 if (FoldedVOp.getNode()) return FoldedVOp;
4117 N1C = isConstOrConstSplat(N1);
4120 // fold (sra c1, c2) -> (sra c1, c2)
4122 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4123 // fold (sra 0, x) -> 0
4124 if (N0C && N0C->isNullValue())
4126 // fold (sra -1, x) -> -1
4127 if (N0C && N0C->isAllOnesValue())
4129 // fold (sra x, (setge c, size(x))) -> undef
4130 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4131 return DAG.getUNDEF(VT);
4132 // fold (sra x, 0) -> x
4133 if (N1C && N1C->isNullValue())
4135 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4137 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4138 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4139 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4141 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4142 ExtVT, VT.getVectorNumElements());
4143 if ((!LegalOperations ||
4144 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4145 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4146 N0.getOperand(0), DAG.getValueType(ExtVT));
4149 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4150 if (N1C && N0.getOpcode() == ISD::SRA) {
4151 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4152 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4153 if (Sum >= OpSizeInBits)
4154 Sum = OpSizeInBits - 1;
4155 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4156 DAG.getConstant(Sum, N1.getValueType()));
4160 // fold (sra (shl X, m), (sub result_size, n))
4161 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4162 // result_size - n != m.
4163 // If truncate is free for the target sext(shl) is likely to result in better
4165 if (N0.getOpcode() == ISD::SHL && N1C) {
4166 // Get the two constanst of the shifts, CN0 = m, CN = n.
4167 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4169 LLVMContext &Ctx = *DAG.getContext();
4170 // Determine what the truncate's result bitsize and type would be.
4171 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4174 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4176 // Determine the residual right-shift amount.
4177 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4179 // If the shift is not a no-op (in which case this should be just a sign
4180 // extend already), the truncated to type is legal, sign_extend is legal
4181 // on that type, and the truncate to that type is both legal and free,
4182 // perform the transform.
4183 if ((ShiftAmt > 0) &&
4184 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4185 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4186 TLI.isTruncateFree(VT, TruncVT)) {
4188 SDValue Amt = DAG.getConstant(ShiftAmt,
4189 getShiftAmountTy(N0.getOperand(0).getValueType()));
4190 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4191 N0.getOperand(0), Amt);
4192 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4194 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4195 N->getValueType(0), Trunc);
4200 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4201 if (N1.getOpcode() == ISD::TRUNCATE &&
4202 N1.getOperand(0).getOpcode() == ISD::AND) {
4203 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4204 if (NewOp1.getNode())
4205 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4208 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4209 // if c1 is equal to the number of bits the trunc removes
4210 if (N0.getOpcode() == ISD::TRUNCATE &&
4211 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4212 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4213 N0.getOperand(0).hasOneUse() &&
4214 N0.getOperand(0).getOperand(1).hasOneUse() &&
4216 SDValue N0Op0 = N0.getOperand(0);
4217 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4218 unsigned LargeShiftVal = LargeShift->getZExtValue();
4219 EVT LargeVT = N0Op0.getValueType();
4221 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4223 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4224 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4225 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4226 N0Op0.getOperand(0), Amt);
4227 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4232 // Simplify, based on bits shifted out of the LHS.
4233 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4234 return SDValue(N, 0);
4237 // If the sign bit is known to be zero, switch this to a SRL.
4238 if (DAG.SignBitIsZero(N0))
4239 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4242 SDValue NewSRA = visitShiftByConstant(N, N1C);
4243 if (NewSRA.getNode())
4250 SDValue DAGCombiner::visitSRL(SDNode *N) {
4251 SDValue N0 = N->getOperand(0);
4252 SDValue N1 = N->getOperand(1);
4253 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4254 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4255 EVT VT = N0.getValueType();
4256 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4259 if (VT.isVector()) {
4260 SDValue FoldedVOp = SimplifyVBinOp(N);
4261 if (FoldedVOp.getNode()) return FoldedVOp;
4263 N1C = isConstOrConstSplat(N1);
4266 // fold (srl c1, c2) -> c1 >>u c2
4268 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4269 // fold (srl 0, x) -> 0
4270 if (N0C && N0C->isNullValue())
4272 // fold (srl x, c >= size(x)) -> undef
4273 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4274 return DAG.getUNDEF(VT);
4275 // fold (srl x, 0) -> x
4276 if (N1C && N1C->isNullValue())
4278 // if (srl x, c) is known to be zero, return 0
4279 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4280 APInt::getAllOnesValue(OpSizeInBits)))
4281 return DAG.getConstant(0, VT);
4283 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4284 if (N1C && N0.getOpcode() == ISD::SRL) {
4285 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4286 uint64_t c1 = N01C->getZExtValue();
4287 uint64_t c2 = N1C->getZExtValue();
4288 if (c1 + c2 >= OpSizeInBits)
4289 return DAG.getConstant(0, VT);
4290 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4291 DAG.getConstant(c1 + c2, N1.getValueType()));
4295 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4296 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4297 N0.getOperand(0).getOpcode() == ISD::SRL &&
4298 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4300 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4301 uint64_t c2 = N1C->getZExtValue();
4302 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4303 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4304 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4305 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4306 if (c1 + OpSizeInBits == InnerShiftSize) {
4307 if (c1 + c2 >= InnerShiftSize)
4308 return DAG.getConstant(0, VT);
4309 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4310 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4311 N0.getOperand(0)->getOperand(0),
4312 DAG.getConstant(c1 + c2, ShiftCountVT)));
4316 // fold (srl (shl x, c), c) -> (and x, cst2)
4317 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4318 unsigned BitSize = N0.getScalarValueSizeInBits();
4319 if (BitSize <= 64) {
4320 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4321 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4322 DAG.getConstant(~0ULL >> ShAmt, VT));
4326 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4327 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4328 // Shifting in all undef bits?
4329 EVT SmallVT = N0.getOperand(0).getValueType();
4330 unsigned BitSize = SmallVT.getScalarSizeInBits();
4331 if (N1C->getZExtValue() >= BitSize)
4332 return DAG.getUNDEF(VT);
4334 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4335 uint64_t ShiftAmt = N1C->getZExtValue();
4336 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4338 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4339 AddToWorkList(SmallShift.getNode());
4340 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4341 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4342 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4343 DAG.getConstant(Mask, VT));
4347 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4348 // bit, which is unmodified by sra.
4349 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4350 if (N0.getOpcode() == ISD::SRA)
4351 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4354 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4355 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4356 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4357 APInt KnownZero, KnownOne;
4358 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4360 // If any of the input bits are KnownOne, then the input couldn't be all
4361 // zeros, thus the result of the srl will always be zero.
4362 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4364 // If all of the bits input the to ctlz node are known to be zero, then
4365 // the result of the ctlz is "32" and the result of the shift is one.
4366 APInt UnknownBits = ~KnownZero;
4367 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4369 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4370 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4371 // Okay, we know that only that the single bit specified by UnknownBits
4372 // could be set on input to the CTLZ node. If this bit is set, the SRL
4373 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4374 // to an SRL/XOR pair, which is likely to simplify more.
4375 unsigned ShAmt = UnknownBits.countTrailingZeros();
4376 SDValue Op = N0.getOperand(0);
4379 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4380 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4381 AddToWorkList(Op.getNode());
4384 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4385 Op, DAG.getConstant(1, VT));
4389 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4390 if (N1.getOpcode() == ISD::TRUNCATE &&
4391 N1.getOperand(0).getOpcode() == ISD::AND) {
4392 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4393 if (NewOp1.getNode())
4394 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4397 // fold operands of srl based on knowledge that the low bits are not
4399 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4400 return SDValue(N, 0);
4403 SDValue NewSRL = visitShiftByConstant(N, N1C);
4404 if (NewSRL.getNode())
4408 // Attempt to convert a srl of a load into a narrower zero-extending load.
4409 SDValue NarrowLoad = ReduceLoadWidth(N);
4410 if (NarrowLoad.getNode())
4413 // Here is a common situation. We want to optimize:
4416 // %b = and i32 %a, 2
4417 // %c = srl i32 %b, 1
4418 // brcond i32 %c ...
4424 // %c = setcc eq %b, 0
4427 // However when after the source operand of SRL is optimized into AND, the SRL
4428 // itself may not be optimized further. Look for it and add the BRCOND into
4430 if (N->hasOneUse()) {
4431 SDNode *Use = *N->use_begin();
4432 if (Use->getOpcode() == ISD::BRCOND)
4434 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4435 // Also look pass the truncate.
4436 Use = *Use->use_begin();
4437 if (Use->getOpcode() == ISD::BRCOND)
4445 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4446 SDValue N0 = N->getOperand(0);
4447 EVT VT = N->getValueType(0);
4449 // fold (ctlz c1) -> c2
4450 if (isa<ConstantSDNode>(N0))
4451 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4455 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4456 SDValue N0 = N->getOperand(0);
4457 EVT VT = N->getValueType(0);
4459 // fold (ctlz_zero_undef c1) -> c2
4460 if (isa<ConstantSDNode>(N0))
4461 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4465 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4466 SDValue N0 = N->getOperand(0);
4467 EVT VT = N->getValueType(0);
4469 // fold (cttz c1) -> c2
4470 if (isa<ConstantSDNode>(N0))
4471 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4475 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4476 SDValue N0 = N->getOperand(0);
4477 EVT VT = N->getValueType(0);
4479 // fold (cttz_zero_undef c1) -> c2
4480 if (isa<ConstantSDNode>(N0))
4481 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4485 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4486 SDValue N0 = N->getOperand(0);
4487 EVT VT = N->getValueType(0);
4489 // fold (ctpop c1) -> c2
4490 if (isa<ConstantSDNode>(N0))
4491 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4495 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4496 SDValue N0 = N->getOperand(0);
4497 SDValue N1 = N->getOperand(1);
4498 SDValue N2 = N->getOperand(2);
4499 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4500 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4501 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4502 EVT VT = N->getValueType(0);
4503 EVT VT0 = N0.getValueType();
4505 // fold (select C, X, X) -> X
4508 // fold (select true, X, Y) -> X
4509 if (N0C && !N0C->isNullValue())
4511 // fold (select false, X, Y) -> Y
4512 if (N0C && N0C->isNullValue())
4514 // fold (select C, 1, X) -> (or C, X)
4515 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4516 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4517 // fold (select C, 0, 1) -> (xor C, 1)
4518 if (VT.isInteger() &&
4521 TLI.getBooleanContents(false) ==
4522 TargetLowering::ZeroOrOneBooleanContent)) &&
4523 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4526 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4527 N0, DAG.getConstant(1, VT0));
4528 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4529 N0, DAG.getConstant(1, VT0));
4530 AddToWorkList(XORNode.getNode());
4532 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4533 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4535 // fold (select C, 0, X) -> (and (not C), X)
4536 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4537 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4538 AddToWorkList(NOTNode.getNode());
4539 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4541 // fold (select C, X, 1) -> (or (not C), X)
4542 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4543 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4544 AddToWorkList(NOTNode.getNode());
4545 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4547 // fold (select C, X, 0) -> (and C, X)
4548 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4549 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4550 // fold (select X, X, Y) -> (or X, Y)
4551 // fold (select X, 1, Y) -> (or X, Y)
4552 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4553 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4554 // fold (select X, Y, X) -> (and X, Y)
4555 // fold (select X, Y, 0) -> (and X, Y)
4556 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4557 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4559 // If we can fold this based on the true/false value, do so.
4560 if (SimplifySelectOps(N, N1, N2))
4561 return SDValue(N, 0); // Don't revisit N.
4563 // fold selects based on a setcc into other things, such as min/max/abs
4564 if (N0.getOpcode() == ISD::SETCC) {
4566 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4567 // having to say they don't support SELECT_CC on every type the DAG knows
4568 // about, since there is no way to mark an opcode illegal at all value types
4569 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4570 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4571 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4572 N0.getOperand(0), N0.getOperand(1),
4573 N1, N2, N0.getOperand(2));
4574 return SimplifySelect(SDLoc(N), N0, N1, N2);
4581 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4584 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4586 // Split the inputs.
4587 SDValue Lo, Hi, LL, LH, RL, RH;
4588 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4589 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4591 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4592 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4594 return std::make_pair(Lo, Hi);
4597 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4598 SDValue N0 = N->getOperand(0);
4599 SDValue N1 = N->getOperand(1);
4600 SDValue N2 = N->getOperand(2);
4603 // Canonicalize integer abs.
4604 // vselect (setg[te] X, 0), X, -X ->
4605 // vselect (setgt X, -1), X, -X ->
4606 // vselect (setl[te] X, 0), -X, X ->
4607 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4608 if (N0.getOpcode() == ISD::SETCC) {
4609 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4610 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4612 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4614 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4615 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4616 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4617 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4618 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4619 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4620 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4623 EVT VT = LHS.getValueType();
4624 SDValue Shift = DAG.getNode(
4625 ISD::SRA, DL, VT, LHS,
4626 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4627 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4628 AddToWorkList(Shift.getNode());
4629 AddToWorkList(Add.getNode());
4630 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4634 // If the VSELECT result requires splitting and the mask is provided by a
4635 // SETCC, then split both nodes and its operands before legalization. This
4636 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4637 // and enables future optimizations (e.g. min/max pattern matching on X86).
4638 if (N0.getOpcode() == ISD::SETCC) {
4639 EVT VT = N->getValueType(0);
4641 // Check if any splitting is required.
4642 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4643 TargetLowering::TypeSplitVector)
4646 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4647 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4648 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4649 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4651 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4652 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4654 // Add the new VSELECT nodes to the work list in case they need to be split
4656 AddToWorkList(Lo.getNode());
4657 AddToWorkList(Hi.getNode());
4659 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4662 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4663 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4665 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4666 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4672 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4673 SDValue N0 = N->getOperand(0);
4674 SDValue N1 = N->getOperand(1);
4675 SDValue N2 = N->getOperand(2);
4676 SDValue N3 = N->getOperand(3);
4677 SDValue N4 = N->getOperand(4);
4678 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4680 // fold select_cc lhs, rhs, x, x, cc -> x
4684 // Determine if the condition we're dealing with is constant
4685 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4686 N0, N1, CC, SDLoc(N), false);
4687 if (SCC.getNode()) {
4688 AddToWorkList(SCC.getNode());
4690 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4691 if (!SCCC->isNullValue())
4692 return N2; // cond always true -> true val
4694 return N3; // cond always false -> false val
4697 // Fold to a simpler select_cc
4698 if (SCC.getOpcode() == ISD::SETCC)
4699 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4700 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4704 // If we can fold this based on the true/false value, do so.
4705 if (SimplifySelectOps(N, N2, N3))
4706 return SDValue(N, 0); // Don't revisit N.
4708 // fold select_cc into other things, such as min/max/abs
4709 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4712 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4713 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4714 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4718 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4719 // dag node into a ConstantSDNode or a build_vector of constants.
4720 // This function is called by the DAGCombiner when visiting sext/zext/aext
4721 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4722 // Vector extends are not folded if operations are legal; this is to
4723 // avoid introducing illegal build_vector dag nodes.
4724 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4725 SelectionDAG &DAG, bool LegalTypes,
4726 bool LegalOperations) {
4727 unsigned Opcode = N->getOpcode();
4728 SDValue N0 = N->getOperand(0);
4729 EVT VT = N->getValueType(0);
4731 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4732 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4734 // fold (sext c1) -> c1
4735 // fold (zext c1) -> c1
4736 // fold (aext c1) -> c1
4737 if (isa<ConstantSDNode>(N0))
4738 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4740 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4741 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4742 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4743 EVT SVT = VT.getScalarType();
4744 if (!(VT.isVector() &&
4745 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4746 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4749 // We can fold this node into a build_vector.
4750 unsigned VTBits = SVT.getSizeInBits();
4751 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4752 unsigned ShAmt = VTBits - EVTBits;
4753 SmallVector<SDValue, 8> Elts;
4754 unsigned NumElts = N0->getNumOperands();
4757 for (unsigned i=0; i != NumElts; ++i) {
4758 SDValue Op = N0->getOperand(i);
4759 if (Op->getOpcode() == ISD::UNDEF) {
4760 Elts.push_back(DAG.getUNDEF(SVT));
4764 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4765 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4766 if (Opcode == ISD::SIGN_EXTEND)
4767 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4770 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4774 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4777 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4778 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4779 // transformation. Returns true if extension are possible and the above
4780 // mentioned transformation is profitable.
4781 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4783 SmallVectorImpl<SDNode *> &ExtendNodes,
4784 const TargetLowering &TLI) {
4785 bool HasCopyToRegUses = false;
4786 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4787 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4788 UE = N0.getNode()->use_end();
4793 if (UI.getUse().getResNo() != N0.getResNo())
4795 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4796 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4797 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4798 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4799 // Sign bits will be lost after a zext.
4802 for (unsigned i = 0; i != 2; ++i) {
4803 SDValue UseOp = User->getOperand(i);
4806 if (!isa<ConstantSDNode>(UseOp))
4811 ExtendNodes.push_back(User);
4814 // If truncates aren't free and there are users we can't
4815 // extend, it isn't worthwhile.
4818 // Remember if this value is live-out.
4819 if (User->getOpcode() == ISD::CopyToReg)
4820 HasCopyToRegUses = true;
4823 if (HasCopyToRegUses) {
4824 bool BothLiveOut = false;
4825 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4827 SDUse &Use = UI.getUse();
4828 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4834 // Both unextended and extended values are live out. There had better be
4835 // a good reason for the transformation.
4836 return ExtendNodes.size();
4841 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4842 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4843 ISD::NodeType ExtType) {
4844 // Extend SetCC uses if necessary.
4845 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4846 SDNode *SetCC = SetCCs[i];
4847 SmallVector<SDValue, 4> Ops;
4849 for (unsigned j = 0; j != 2; ++j) {
4850 SDValue SOp = SetCC->getOperand(j);
4852 Ops.push_back(ExtLoad);
4854 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4857 Ops.push_back(SetCC->getOperand(2));
4858 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4859 &Ops[0], Ops.size()));
4863 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4864 SDValue N0 = N->getOperand(0);
4865 EVT VT = N->getValueType(0);
4867 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4869 return SDValue(Res, 0);
4871 // fold (sext (sext x)) -> (sext x)
4872 // fold (sext (aext x)) -> (sext x)
4873 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4874 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4877 if (N0.getOpcode() == ISD::TRUNCATE) {
4878 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4879 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4880 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4881 if (NarrowLoad.getNode()) {
4882 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4883 if (NarrowLoad.getNode() != N0.getNode()) {
4884 CombineTo(N0.getNode(), NarrowLoad);
4885 // CombineTo deleted the truncate, if needed, but not what's under it.
4888 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4891 // See if the value being truncated is already sign extended. If so, just
4892 // eliminate the trunc/sext pair.
4893 SDValue Op = N0.getOperand(0);
4894 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4895 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4896 unsigned DestBits = VT.getScalarType().getSizeInBits();
4897 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4899 if (OpBits == DestBits) {
4900 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4901 // bits, it is already ready.
4902 if (NumSignBits > DestBits-MidBits)
4904 } else if (OpBits < DestBits) {
4905 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4906 // bits, just sext from i32.
4907 if (NumSignBits > OpBits-MidBits)
4908 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4910 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4911 // bits, just truncate to i32.
4912 if (NumSignBits > OpBits-MidBits)
4913 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4916 // fold (sext (truncate x)) -> (sextinreg x).
4917 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4918 N0.getValueType())) {
4919 if (OpBits < DestBits)
4920 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4921 else if (OpBits > DestBits)
4922 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4923 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4924 DAG.getValueType(N0.getValueType()));
4928 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4929 // None of the supported targets knows how to perform load and sign extend
4930 // on vectors in one instruction. We only perform this transformation on
4932 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4933 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4934 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4935 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4936 bool DoXform = true;
4937 SmallVector<SDNode*, 4> SetCCs;
4938 if (!N0.hasOneUse())
4939 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4941 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4942 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4944 LN0->getBasePtr(), N0.getValueType(),
4945 LN0->getMemOperand());
4946 CombineTo(N, ExtLoad);
4947 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4948 N0.getValueType(), ExtLoad);
4949 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4950 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4952 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4956 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4957 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4958 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4959 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4960 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4961 EVT MemVT = LN0->getMemoryVT();
4962 if ((!LegalOperations && !LN0->isVolatile()) ||
4963 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4964 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4966 LN0->getBasePtr(), MemVT,
4967 LN0->getMemOperand());
4968 CombineTo(N, ExtLoad);
4969 CombineTo(N0.getNode(),
4970 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4971 N0.getValueType(), ExtLoad),
4972 ExtLoad.getValue(1));
4973 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4977 // fold (sext (and/or/xor (load x), cst)) ->
4978 // (and/or/xor (sextload x), (sext cst))
4979 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4980 N0.getOpcode() == ISD::XOR) &&
4981 isa<LoadSDNode>(N0.getOperand(0)) &&
4982 N0.getOperand(1).getOpcode() == ISD::Constant &&
4983 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4984 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4985 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4986 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
4987 bool DoXform = true;
4988 SmallVector<SDNode*, 4> SetCCs;
4989 if (!N0.hasOneUse())
4990 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4993 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4994 LN0->getChain(), LN0->getBasePtr(),
4996 LN0->getMemOperand());
4997 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4998 Mask = Mask.sext(VT.getSizeInBits());
4999 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5000 ExtLoad, DAG.getConstant(Mask, VT));
5001 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5002 SDLoc(N0.getOperand(0)),
5003 N0.getOperand(0).getValueType(), ExtLoad);
5005 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5006 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5008 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5013 if (N0.getOpcode() == ISD::SETCC) {
5014 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5015 // Only do this before legalize for now.
5016 if (VT.isVector() && !LegalOperations &&
5017 TLI.getBooleanContents(true) ==
5018 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5019 EVT N0VT = N0.getOperand(0).getValueType();
5020 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5021 // of the same size as the compared operands. Only optimize sext(setcc())
5022 // if this is the case.
5023 EVT SVT = getSetCCResultType(N0VT);
5025 // We know that the # elements of the results is the same as the
5026 // # elements of the compare (and the # elements of the compare result
5027 // for that matter). Check to see that they are the same size. If so,
5028 // we know that the element size of the sext'd result matches the
5029 // element size of the compare operands.
5030 if (VT.getSizeInBits() == SVT.getSizeInBits())
5031 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5033 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5035 // If the desired elements are smaller or larger than the source
5036 // elements we can use a matching integer vector type and then
5037 // truncate/sign extend
5038 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5039 if (SVT == MatchingVectorType) {
5040 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5041 N0.getOperand(0), N0.getOperand(1),
5042 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5043 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5047 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5048 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5050 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5052 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5053 NegOne, DAG.getConstant(0, VT),
5054 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5055 if (SCC.getNode()) return SCC;
5057 if (!VT.isVector()) {
5058 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5059 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5061 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5062 SDValue SetCC = DAG.getSetCC(DL,
5064 N0.getOperand(0), N0.getOperand(1), CC);
5065 EVT SelectVT = getSetCCResultType(VT);
5066 return DAG.getSelect(DL, VT,
5067 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5068 NegOne, DAG.getConstant(0, VT));
5074 // fold (sext x) -> (zext x) if the sign bit is known zero.
5075 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5076 DAG.SignBitIsZero(N0))
5077 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5082 // isTruncateOf - If N is a truncate of some other value, return true, record
5083 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5084 // This function computes KnownZero to avoid a duplicated call to
5085 // ComputeMaskedBits in the caller.
5086 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5089 if (N->getOpcode() == ISD::TRUNCATE) {
5090 Op = N->getOperand(0);
5091 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5095 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5096 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5099 SDValue Op0 = N->getOperand(0);
5100 SDValue Op1 = N->getOperand(1);
5101 assert(Op0.getValueType() == Op1.getValueType());
5103 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5104 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5105 if (COp0 && COp0->isNullValue())
5107 else if (COp1 && COp1->isNullValue())
5112 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5114 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5120 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5121 SDValue N0 = N->getOperand(0);
5122 EVT VT = N->getValueType(0);
5124 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5126 return SDValue(Res, 0);
5128 // fold (zext (zext x)) -> (zext x)
5129 // fold (zext (aext x)) -> (zext x)
5130 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5131 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5134 // fold (zext (truncate x)) -> (zext x) or
5135 // (zext (truncate x)) -> (truncate x)
5136 // This is valid when the truncated bits of x are already zero.
5137 // FIXME: We should extend this to work for vectors too.
5140 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5141 APInt TruncatedBits =
5142 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5143 APInt(Op.getValueSizeInBits(), 0) :
5144 APInt::getBitsSet(Op.getValueSizeInBits(),
5145 N0.getValueSizeInBits(),
5146 std::min(Op.getValueSizeInBits(),
5147 VT.getSizeInBits()));
5148 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5149 if (VT.bitsGT(Op.getValueType()))
5150 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5151 if (VT.bitsLT(Op.getValueType()))
5152 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5158 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5159 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5160 if (N0.getOpcode() == ISD::TRUNCATE) {
5161 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5162 if (NarrowLoad.getNode()) {
5163 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5164 if (NarrowLoad.getNode() != N0.getNode()) {
5165 CombineTo(N0.getNode(), NarrowLoad);
5166 // CombineTo deleted the truncate, if needed, but not what's under it.
5169 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5173 // fold (zext (truncate x)) -> (and x, mask)
5174 if (N0.getOpcode() == ISD::TRUNCATE &&
5175 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5177 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5178 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5179 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5180 if (NarrowLoad.getNode()) {
5181 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5182 if (NarrowLoad.getNode() != N0.getNode()) {
5183 CombineTo(N0.getNode(), NarrowLoad);
5184 // CombineTo deleted the truncate, if needed, but not what's under it.
5187 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5190 SDValue Op = N0.getOperand(0);
5191 if (Op.getValueType().bitsLT(VT)) {
5192 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5193 AddToWorkList(Op.getNode());
5194 } else if (Op.getValueType().bitsGT(VT)) {
5195 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5196 AddToWorkList(Op.getNode());
5198 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5199 N0.getValueType().getScalarType());
5202 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5203 // if either of the casts is not free.
5204 if (N0.getOpcode() == ISD::AND &&
5205 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5206 N0.getOperand(1).getOpcode() == ISD::Constant &&
5207 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5208 N0.getValueType()) ||
5209 !TLI.isZExtFree(N0.getValueType(), VT))) {
5210 SDValue X = N0.getOperand(0).getOperand(0);
5211 if (X.getValueType().bitsLT(VT)) {
5212 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5213 } else if (X.getValueType().bitsGT(VT)) {
5214 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5216 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5217 Mask = Mask.zext(VT.getSizeInBits());
5218 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5219 X, DAG.getConstant(Mask, VT));
5222 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5223 // None of the supported targets knows how to perform load and vector_zext
5224 // on vectors in one instruction. We only perform this transformation on
5226 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5227 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5228 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5229 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5230 bool DoXform = true;
5231 SmallVector<SDNode*, 4> SetCCs;
5232 if (!N0.hasOneUse())
5233 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5235 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5236 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5238 LN0->getBasePtr(), N0.getValueType(),
5239 LN0->getMemOperand());
5240 CombineTo(N, ExtLoad);
5241 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5242 N0.getValueType(), ExtLoad);
5243 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5245 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5247 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5251 // fold (zext (and/or/xor (load x), cst)) ->
5252 // (and/or/xor (zextload x), (zext cst))
5253 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5254 N0.getOpcode() == ISD::XOR) &&
5255 isa<LoadSDNode>(N0.getOperand(0)) &&
5256 N0.getOperand(1).getOpcode() == ISD::Constant &&
5257 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5258 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5259 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5260 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5261 bool DoXform = true;
5262 SmallVector<SDNode*, 4> SetCCs;
5263 if (!N0.hasOneUse())
5264 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5267 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5268 LN0->getChain(), LN0->getBasePtr(),
5270 LN0->getMemOperand());
5271 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5272 Mask = Mask.zext(VT.getSizeInBits());
5273 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5274 ExtLoad, DAG.getConstant(Mask, VT));
5275 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5276 SDLoc(N0.getOperand(0)),
5277 N0.getOperand(0).getValueType(), ExtLoad);
5279 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5280 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5282 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5287 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5288 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5289 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5290 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5291 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5292 EVT MemVT = LN0->getMemoryVT();
5293 if ((!LegalOperations && !LN0->isVolatile()) ||
5294 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5295 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5297 LN0->getBasePtr(), MemVT,
5298 LN0->getMemOperand());
5299 CombineTo(N, ExtLoad);
5300 CombineTo(N0.getNode(),
5301 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5303 ExtLoad.getValue(1));
5304 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5308 if (N0.getOpcode() == ISD::SETCC) {
5309 if (!LegalOperations && VT.isVector() &&
5310 N0.getValueType().getVectorElementType() == MVT::i1) {
5311 EVT N0VT = N0.getOperand(0).getValueType();
5312 if (getSetCCResultType(N0VT) == N0.getValueType())
5315 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5316 // Only do this before legalize for now.
5317 EVT EltVT = VT.getVectorElementType();
5318 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5319 DAG.getConstant(1, EltVT));
5320 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5321 // We know that the # elements of the results is the same as the
5322 // # elements of the compare (and the # elements of the compare result
5323 // for that matter). Check to see that they are the same size. If so,
5324 // we know that the element size of the sext'd result matches the
5325 // element size of the compare operands.
5326 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5327 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5329 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5330 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5331 &OneOps[0], OneOps.size()));
5333 // If the desired elements are smaller or larger than the source
5334 // elements we can use a matching integer vector type and then
5335 // truncate/sign extend
5336 EVT MatchingElementType =
5337 EVT::getIntegerVT(*DAG.getContext(),
5338 N0VT.getScalarType().getSizeInBits());
5339 EVT MatchingVectorType =
5340 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5341 N0VT.getVectorNumElements());
5343 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5345 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5346 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5347 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5348 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5349 &OneOps[0], OneOps.size()));
5352 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5354 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5355 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5356 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5357 if (SCC.getNode()) return SCC;
5360 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5361 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5362 isa<ConstantSDNode>(N0.getOperand(1)) &&
5363 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5365 SDValue ShAmt = N0.getOperand(1);
5366 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5367 if (N0.getOpcode() == ISD::SHL) {
5368 SDValue InnerZExt = N0.getOperand(0);
5369 // If the original shl may be shifting out bits, do not perform this
5371 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5372 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5373 if (ShAmtVal > KnownZeroBits)
5379 // Ensure that the shift amount is wide enough for the shifted value.
5380 if (VT.getSizeInBits() >= 256)
5381 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5383 return DAG.getNode(N0.getOpcode(), DL, VT,
5384 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5391 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5392 SDValue N0 = N->getOperand(0);
5393 EVT VT = N->getValueType(0);
5395 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5397 return SDValue(Res, 0);
5399 // fold (aext (aext x)) -> (aext x)
5400 // fold (aext (zext x)) -> (zext x)
5401 // fold (aext (sext x)) -> (sext x)
5402 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5403 N0.getOpcode() == ISD::ZERO_EXTEND ||
5404 N0.getOpcode() == ISD::SIGN_EXTEND)
5405 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5407 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5408 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5409 if (N0.getOpcode() == ISD::TRUNCATE) {
5410 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5411 if (NarrowLoad.getNode()) {
5412 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5413 if (NarrowLoad.getNode() != N0.getNode()) {
5414 CombineTo(N0.getNode(), NarrowLoad);
5415 // CombineTo deleted the truncate, if needed, but not what's under it.
5418 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5422 // fold (aext (truncate x))
5423 if (N0.getOpcode() == ISD::TRUNCATE) {
5424 SDValue TruncOp = N0.getOperand(0);
5425 if (TruncOp.getValueType() == VT)
5426 return TruncOp; // x iff x size == zext size.
5427 if (TruncOp.getValueType().bitsGT(VT))
5428 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5429 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5432 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5433 // if the trunc is not free.
5434 if (N0.getOpcode() == ISD::AND &&
5435 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5436 N0.getOperand(1).getOpcode() == ISD::Constant &&
5437 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5438 N0.getValueType())) {
5439 SDValue X = N0.getOperand(0).getOperand(0);
5440 if (X.getValueType().bitsLT(VT)) {
5441 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5442 } else if (X.getValueType().bitsGT(VT)) {
5443 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5445 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5446 Mask = Mask.zext(VT.getSizeInBits());
5447 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5448 X, DAG.getConstant(Mask, VT));
5451 // fold (aext (load x)) -> (aext (truncate (extload x)))
5452 // None of the supported targets knows how to perform load and any_ext
5453 // on vectors in one instruction. We only perform this transformation on
5455 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5456 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5457 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5458 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5459 bool DoXform = true;
5460 SmallVector<SDNode*, 4> SetCCs;
5461 if (!N0.hasOneUse())
5462 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5464 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5465 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5467 LN0->getBasePtr(), N0.getValueType(),
5468 LN0->getMemOperand());
5469 CombineTo(N, ExtLoad);
5470 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5471 N0.getValueType(), ExtLoad);
5472 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5473 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5475 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5479 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5480 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5481 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5482 if (N0.getOpcode() == ISD::LOAD &&
5483 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5485 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5486 ISD::LoadExtType ExtType = LN0->getExtensionType();
5487 EVT MemVT = LN0->getMemoryVT();
5488 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5489 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5490 VT, LN0->getChain(), LN0->getBasePtr(),
5491 MemVT, LN0->getMemOperand());
5492 CombineTo(N, ExtLoad);
5493 CombineTo(N0.getNode(),
5494 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5495 N0.getValueType(), ExtLoad),
5496 ExtLoad.getValue(1));
5497 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5501 if (N0.getOpcode() == ISD::SETCC) {
5502 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5503 // Only do this before legalize for now.
5504 if (VT.isVector() && !LegalOperations) {
5505 EVT N0VT = N0.getOperand(0).getValueType();
5506 // We know that the # elements of the results is the same as the
5507 // # elements of the compare (and the # elements of the compare result
5508 // for that matter). Check to see that they are the same size. If so,
5509 // we know that the element size of the sext'd result matches the
5510 // element size of the compare operands.
5511 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5512 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5514 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5515 // If the desired elements are smaller or larger than the source
5516 // elements we can use a matching integer vector type and then
5517 // truncate/sign extend
5519 EVT MatchingElementType =
5520 EVT::getIntegerVT(*DAG.getContext(),
5521 N0VT.getScalarType().getSizeInBits());
5522 EVT MatchingVectorType =
5523 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5524 N0VT.getVectorNumElements());
5526 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5528 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5529 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5533 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5535 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5536 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5537 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5545 /// GetDemandedBits - See if the specified operand can be simplified with the
5546 /// knowledge that only the bits specified by Mask are used. If so, return the
5547 /// simpler operand, otherwise return a null SDValue.
5548 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5549 switch (V.getOpcode()) {
5551 case ISD::Constant: {
5552 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5553 assert(CV && "Const value should be ConstSDNode.");
5554 const APInt &CVal = CV->getAPIntValue();
5555 APInt NewVal = CVal & Mask;
5557 return DAG.getConstant(NewVal, V.getValueType());
5562 // If the LHS or RHS don't contribute bits to the or, drop them.
5563 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5564 return V.getOperand(1);
5565 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5566 return V.getOperand(0);
5569 // Only look at single-use SRLs.
5570 if (!V.getNode()->hasOneUse())
5572 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5573 // See if we can recursively simplify the LHS.
5574 unsigned Amt = RHSC->getZExtValue();
5576 // Watch out for shift count overflow though.
5577 if (Amt >= Mask.getBitWidth()) break;
5578 APInt NewMask = Mask << Amt;
5579 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5580 if (SimplifyLHS.getNode())
5581 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5582 SimplifyLHS, V.getOperand(1));
5588 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5589 /// bits and then truncated to a narrower type and where N is a multiple
5590 /// of number of bits of the narrower type, transform it to a narrower load
5591 /// from address + N / num of bits of new type. If the result is to be
5592 /// extended, also fold the extension to form a extending load.
5593 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5594 unsigned Opc = N->getOpcode();
5596 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5597 SDValue N0 = N->getOperand(0);
5598 EVT VT = N->getValueType(0);
5601 // This transformation isn't valid for vector loads.
5605 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5607 if (Opc == ISD::SIGN_EXTEND_INREG) {
5608 ExtType = ISD::SEXTLOAD;
5609 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5610 } else if (Opc == ISD::SRL) {
5611 // Another special-case: SRL is basically zero-extending a narrower value.
5612 ExtType = ISD::ZEXTLOAD;
5614 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5615 if (!N01) return SDValue();
5616 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5617 VT.getSizeInBits() - N01->getZExtValue());
5619 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5622 unsigned EVTBits = ExtVT.getSizeInBits();
5624 // Do not generate loads of non-round integer types since these can
5625 // be expensive (and would be wrong if the type is not byte sized).
5626 if (!ExtVT.isRound())
5630 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5631 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5632 ShAmt = N01->getZExtValue();
5633 // Is the shift amount a multiple of size of VT?
5634 if ((ShAmt & (EVTBits-1)) == 0) {
5635 N0 = N0.getOperand(0);
5636 // Is the load width a multiple of size of VT?
5637 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5641 // At this point, we must have a load or else we can't do the transform.
5642 if (!isa<LoadSDNode>(N0)) return SDValue();
5644 // Because a SRL must be assumed to *need* to zero-extend the high bits
5645 // (as opposed to anyext the high bits), we can't combine the zextload
5646 // lowering of SRL and an sextload.
5647 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5650 // If the shift amount is larger than the input type then we're not
5651 // accessing any of the loaded bytes. If the load was a zextload/extload
5652 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5653 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5658 // If the load is shifted left (and the result isn't shifted back right),
5659 // we can fold the truncate through the shift.
5660 unsigned ShLeftAmt = 0;
5661 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5662 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5663 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5664 ShLeftAmt = N01->getZExtValue();
5665 N0 = N0.getOperand(0);
5669 // If we haven't found a load, we can't narrow it. Don't transform one with
5670 // multiple uses, this would require adding a new load.
5671 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5674 // Don't change the width of a volatile load.
5675 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5676 if (LN0->isVolatile())
5679 // Verify that we are actually reducing a load width here.
5680 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5683 // For the transform to be legal, the load must produce only two values
5684 // (the value loaded and the chain). Don't transform a pre-increment
5685 // load, for example, which produces an extra value. Otherwise the
5686 // transformation is not equivalent, and the downstream logic to replace
5687 // uses gets things wrong.
5688 if (LN0->getNumValues() > 2)
5691 // If the load that we're shrinking is an extload and we're not just
5692 // discarding the extension we can't simply shrink the load. Bail.
5693 // TODO: It would be possible to merge the extensions in some cases.
5694 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5695 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5698 EVT PtrType = N0.getOperand(1).getValueType();
5700 if (PtrType == MVT::Untyped || PtrType.isExtended())
5701 // It's not possible to generate a constant of extended or untyped type.
5704 // For big endian targets, we need to adjust the offset to the pointer to
5705 // load the correct bytes.
5706 if (TLI.isBigEndian()) {
5707 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5708 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5709 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5712 uint64_t PtrOff = ShAmt / 8;
5713 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5714 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5715 PtrType, LN0->getBasePtr(),
5716 DAG.getConstant(PtrOff, PtrType));
5717 AddToWorkList(NewPtr.getNode());
5720 if (ExtType == ISD::NON_EXTLOAD)
5721 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5722 LN0->getPointerInfo().getWithOffset(PtrOff),
5723 LN0->isVolatile(), LN0->isNonTemporal(),
5724 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5726 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5727 LN0->getPointerInfo().getWithOffset(PtrOff),
5728 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5729 NewAlign, LN0->getTBAAInfo());
5731 // Replace the old load's chain with the new load's chain.
5732 WorkListRemover DeadNodes(*this);
5733 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5735 // Shift the result left, if we've swallowed a left shift.
5736 SDValue Result = Load;
5737 if (ShLeftAmt != 0) {
5738 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5739 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5741 // If the shift amount is as large as the result size (but, presumably,
5742 // no larger than the source) then the useful bits of the result are
5743 // zero; we can't simply return the shortened shift, because the result
5744 // of that operation is undefined.
5745 if (ShLeftAmt >= VT.getSizeInBits())
5746 Result = DAG.getConstant(0, VT);
5748 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5749 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5752 // Return the new loaded value.
5756 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5757 SDValue N0 = N->getOperand(0);
5758 SDValue N1 = N->getOperand(1);
5759 EVT VT = N->getValueType(0);
5760 EVT EVT = cast<VTSDNode>(N1)->getVT();
5761 unsigned VTBits = VT.getScalarType().getSizeInBits();
5762 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5764 // fold (sext_in_reg c1) -> c1
5765 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5766 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5768 // If the input is already sign extended, just drop the extension.
5769 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5772 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5773 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5774 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5775 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5776 N0.getOperand(0), N1);
5778 // fold (sext_in_reg (sext x)) -> (sext x)
5779 // fold (sext_in_reg (aext x)) -> (sext x)
5780 // if x is small enough.
5781 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5782 SDValue N00 = N0.getOperand(0);
5783 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5784 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5785 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5788 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5789 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5790 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5792 // fold operands of sext_in_reg based on knowledge that the top bits are not
5794 if (SimplifyDemandedBits(SDValue(N, 0)))
5795 return SDValue(N, 0);
5797 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5798 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5799 SDValue NarrowLoad = ReduceLoadWidth(N);
5800 if (NarrowLoad.getNode())
5803 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5804 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5805 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5806 if (N0.getOpcode() == ISD::SRL) {
5807 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5808 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5809 // We can turn this into an SRA iff the input to the SRL is already sign
5811 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5812 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5813 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5814 N0.getOperand(0), N0.getOperand(1));
5818 // fold (sext_inreg (extload x)) -> (sextload x)
5819 if (ISD::isEXTLoad(N0.getNode()) &&
5820 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5821 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5822 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5823 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5824 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5825 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5827 LN0->getBasePtr(), EVT,
5828 LN0->getMemOperand());
5829 CombineTo(N, ExtLoad);
5830 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5831 AddToWorkList(ExtLoad.getNode());
5832 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5834 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5835 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5837 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5838 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5839 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5840 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5841 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5843 LN0->getBasePtr(), EVT,
5844 LN0->getMemOperand());
5845 CombineTo(N, ExtLoad);
5846 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5847 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5850 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5851 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5852 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5853 N0.getOperand(1), false);
5854 if (BSwap.getNode())
5855 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5859 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5860 // into a build_vector.
5861 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5862 SmallVector<SDValue, 8> Elts;
5863 unsigned NumElts = N0->getNumOperands();
5864 unsigned ShAmt = VTBits - EVTBits;
5866 for (unsigned i = 0; i != NumElts; ++i) {
5867 SDValue Op = N0->getOperand(i);
5868 if (Op->getOpcode() == ISD::UNDEF) {
5873 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5874 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5875 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5876 Op.getValueType()));
5879 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5885 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5886 SDValue N0 = N->getOperand(0);
5887 EVT VT = N->getValueType(0);
5888 bool isLE = TLI.isLittleEndian();
5891 if (N0.getValueType() == N->getValueType(0))
5893 // fold (truncate c1) -> c1
5894 if (isa<ConstantSDNode>(N0))
5895 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5896 // fold (truncate (truncate x)) -> (truncate x)
5897 if (N0.getOpcode() == ISD::TRUNCATE)
5898 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5899 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5900 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5901 N0.getOpcode() == ISD::SIGN_EXTEND ||
5902 N0.getOpcode() == ISD::ANY_EXTEND) {
5903 if (N0.getOperand(0).getValueType().bitsLT(VT))
5904 // if the source is smaller than the dest, we still need an extend
5905 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5907 if (N0.getOperand(0).getValueType().bitsGT(VT))
5908 // if the source is larger than the dest, than we just need the truncate
5909 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5910 // if the source and dest are the same type, we can drop both the extend
5911 // and the truncate.
5912 return N0.getOperand(0);
5915 // Fold extract-and-trunc into a narrow extract. For example:
5916 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5917 // i32 y = TRUNCATE(i64 x)
5919 // v16i8 b = BITCAST (v2i64 val)
5920 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5922 // Note: We only run this optimization after type legalization (which often
5923 // creates this pattern) and before operation legalization after which
5924 // we need to be more careful about the vector instructions that we generate.
5925 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5926 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5928 EVT VecTy = N0.getOperand(0).getValueType();
5929 EVT ExTy = N0.getValueType();
5930 EVT TrTy = N->getValueType(0);
5932 unsigned NumElem = VecTy.getVectorNumElements();
5933 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5935 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5936 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5938 SDValue EltNo = N0->getOperand(1);
5939 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5940 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5941 EVT IndexTy = TLI.getVectorIdxTy();
5942 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5944 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5945 NVT, N0.getOperand(0));
5947 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5949 DAG.getConstant(Index, IndexTy));
5953 // Fold a series of buildvector, bitcast, and truncate if possible.
5955 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5956 // (2xi32 (buildvector x, y)).
5957 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5958 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5959 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5960 N0.getOperand(0).hasOneUse()) {
5962 SDValue BuildVect = N0.getOperand(0);
5963 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5964 EVT TruncVecEltTy = VT.getVectorElementType();
5966 // Check that the element types match.
5967 if (BuildVectEltTy == TruncVecEltTy) {
5968 // Now we only need to compute the offset of the truncated elements.
5969 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5970 unsigned TruncVecNumElts = VT.getVectorNumElements();
5971 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5973 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5974 "Invalid number of elements");
5976 SmallVector<SDValue, 8> Opnds;
5977 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5978 Opnds.push_back(BuildVect.getOperand(i));
5980 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5985 // See if we can simplify the input to this truncate through knowledge that
5986 // only the low bits are being used.
5987 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5988 // Currently we only perform this optimization on scalars because vectors
5989 // may have different active low bits.
5990 if (!VT.isVector()) {
5992 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5993 VT.getSizeInBits()));
5994 if (Shorter.getNode())
5995 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5997 // fold (truncate (load x)) -> (smaller load x)
5998 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5999 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6000 SDValue Reduced = ReduceLoadWidth(N);
6001 if (Reduced.getNode())
6003 // Handle the case where the load remains an extending load even
6004 // after truncation.
6005 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6006 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6007 if (!LN0->isVolatile() &&
6008 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6009 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6010 VT, LN0->getChain(), LN0->getBasePtr(),
6012 LN0->getMemOperand());
6013 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6018 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6019 // where ... are all 'undef'.
6020 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6021 SmallVector<EVT, 8> VTs;
6024 unsigned NumDefs = 0;
6026 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6027 SDValue X = N0.getOperand(i);
6028 if (X.getOpcode() != ISD::UNDEF) {
6033 // Stop if more than one members are non-undef.
6036 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6037 VT.getVectorElementType(),
6038 X.getValueType().getVectorNumElements()));
6042 return DAG.getUNDEF(VT);
6045 assert(V.getNode() && "The single defined operand is empty!");
6046 SmallVector<SDValue, 8> Opnds;
6047 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6049 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6052 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6053 AddToWorkList(NV.getNode());
6054 Opnds.push_back(NV);
6056 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6057 &Opnds[0], Opnds.size());
6061 // Simplify the operands using demanded-bits information.
6062 if (!VT.isVector() &&
6063 SimplifyDemandedBits(SDValue(N, 0)))
6064 return SDValue(N, 0);
6069 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6070 SDValue Elt = N->getOperand(i);
6071 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6072 return Elt.getNode();
6073 return Elt.getOperand(Elt.getResNo()).getNode();
6076 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6077 /// if load locations are consecutive.
6078 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6079 assert(N->getOpcode() == ISD::BUILD_PAIR);
6081 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6082 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6083 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6084 LD1->getAddressSpace() != LD2->getAddressSpace())
6086 EVT LD1VT = LD1->getValueType(0);
6088 if (ISD::isNON_EXTLoad(LD2) &&
6090 // If both are volatile this would reduce the number of volatile loads.
6091 // If one is volatile it might be ok, but play conservative and bail out.
6092 !LD1->isVolatile() &&
6093 !LD2->isVolatile() &&
6094 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6095 unsigned Align = LD1->getAlignment();
6096 unsigned NewAlign = TLI.getDataLayout()->
6097 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6099 if (NewAlign <= Align &&
6100 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6101 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6102 LD1->getBasePtr(), LD1->getPointerInfo(),
6103 false, false, false, Align);
6109 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6110 SDValue N0 = N->getOperand(0);
6111 EVT VT = N->getValueType(0);
6113 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6114 // Only do this before legalize, since afterward the target may be depending
6115 // on the bitconvert.
6116 // First check to see if this is all constant.
6118 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6120 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6122 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6123 assert(!DestEltVT.isVector() &&
6124 "Element type of vector ValueType must not be vector!");
6126 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6129 // If the input is a constant, let getNode fold it.
6130 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6131 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6132 if (Res.getNode() != N) {
6133 if (!LegalOperations ||
6134 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6137 // Folding it resulted in an illegal node, and it's too late to
6138 // do that. Clean up the old node and forego the transformation.
6139 // Ideally this won't happen very often, because instcombine
6140 // and the earlier dagcombine runs (where illegal nodes are
6141 // permitted) should have folded most of them already.
6142 DAG.DeleteNode(Res.getNode());
6146 // (conv (conv x, t1), t2) -> (conv x, t2)
6147 if (N0.getOpcode() == ISD::BITCAST)
6148 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6151 // fold (conv (load x)) -> (load (conv*)x)
6152 // If the resultant load doesn't need a higher alignment than the original!
6153 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6154 // Do not change the width of a volatile load.
6155 !cast<LoadSDNode>(N0)->isVolatile() &&
6156 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6157 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6158 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6159 unsigned Align = TLI.getDataLayout()->
6160 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6161 unsigned OrigAlign = LN0->getAlignment();
6163 if (Align <= OrigAlign) {
6164 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6165 LN0->getBasePtr(), LN0->getPointerInfo(),
6166 LN0->isVolatile(), LN0->isNonTemporal(),
6167 LN0->isInvariant(), OrigAlign,
6168 LN0->getTBAAInfo());
6170 CombineTo(N0.getNode(),
6171 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6172 N0.getValueType(), Load),
6178 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6179 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6180 // This often reduces constant pool loads.
6181 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6182 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6183 N0.getNode()->hasOneUse() && VT.isInteger() &&
6184 !VT.isVector() && !N0.getValueType().isVector()) {
6185 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6187 AddToWorkList(NewConv.getNode());
6189 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6190 if (N0.getOpcode() == ISD::FNEG)
6191 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6192 NewConv, DAG.getConstant(SignBit, VT));
6193 assert(N0.getOpcode() == ISD::FABS);
6194 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6195 NewConv, DAG.getConstant(~SignBit, VT));
6198 // fold (bitconvert (fcopysign cst, x)) ->
6199 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6200 // Note that we don't handle (copysign x, cst) because this can always be
6201 // folded to an fneg or fabs.
6202 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6203 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6204 VT.isInteger() && !VT.isVector()) {
6205 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6206 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6207 if (isTypeLegal(IntXVT)) {
6208 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6209 IntXVT, N0.getOperand(1));
6210 AddToWorkList(X.getNode());
6212 // If X has a different width than the result/lhs, sext it or truncate it.
6213 unsigned VTWidth = VT.getSizeInBits();
6214 if (OrigXWidth < VTWidth) {
6215 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6216 AddToWorkList(X.getNode());
6217 } else if (OrigXWidth > VTWidth) {
6218 // To get the sign bit in the right place, we have to shift it right
6219 // before truncating.
6220 X = DAG.getNode(ISD::SRL, SDLoc(X),
6221 X.getValueType(), X,
6222 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6223 AddToWorkList(X.getNode());
6224 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6225 AddToWorkList(X.getNode());
6228 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6229 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6230 X, DAG.getConstant(SignBit, VT));
6231 AddToWorkList(X.getNode());
6233 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6234 VT, N0.getOperand(0));
6235 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6236 Cst, DAG.getConstant(~SignBit, VT));
6237 AddToWorkList(Cst.getNode());
6239 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6243 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6244 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6245 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6246 if (CombineLD.getNode())
6253 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6254 EVT VT = N->getValueType(0);
6255 return CombineConsecutiveLoads(N, VT);
6258 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6259 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6260 /// destination element value type.
6261 SDValue DAGCombiner::
6262 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6263 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6265 // If this is already the right type, we're done.
6266 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6268 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6269 unsigned DstBitSize = DstEltVT.getSizeInBits();
6271 // If this is a conversion of N elements of one type to N elements of another
6272 // type, convert each element. This handles FP<->INT cases.
6273 if (SrcBitSize == DstBitSize) {
6274 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6275 BV->getValueType(0).getVectorNumElements());
6277 // Due to the FP element handling below calling this routine recursively,
6278 // we can end up with a scalar-to-vector node here.
6279 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6280 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6281 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6282 DstEltVT, BV->getOperand(0)));
6284 SmallVector<SDValue, 8> Ops;
6285 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6286 SDValue Op = BV->getOperand(i);
6287 // If the vector element type is not legal, the BUILD_VECTOR operands
6288 // are promoted and implicitly truncated. Make that explicit here.
6289 if (Op.getValueType() != SrcEltVT)
6290 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6291 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6293 AddToWorkList(Ops.back().getNode());
6295 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6296 &Ops[0], Ops.size());
6299 // Otherwise, we're growing or shrinking the elements. To avoid having to
6300 // handle annoying details of growing/shrinking FP values, we convert them to
6302 if (SrcEltVT.isFloatingPoint()) {
6303 // Convert the input float vector to a int vector where the elements are the
6305 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6306 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6307 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6311 // Now we know the input is an integer vector. If the output is a FP type,
6312 // convert to integer first, then to FP of the right size.
6313 if (DstEltVT.isFloatingPoint()) {
6314 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6315 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6316 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6318 // Next, convert to FP elements of the same size.
6319 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6322 // Okay, we know the src/dst types are both integers of differing types.
6323 // Handling growing first.
6324 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6325 if (SrcBitSize < DstBitSize) {
6326 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6328 SmallVector<SDValue, 8> Ops;
6329 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6330 i += NumInputsPerOutput) {
6331 bool isLE = TLI.isLittleEndian();
6332 APInt NewBits = APInt(DstBitSize, 0);
6333 bool EltIsUndef = true;
6334 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6335 // Shift the previously computed bits over.
6336 NewBits <<= SrcBitSize;
6337 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6338 if (Op.getOpcode() == ISD::UNDEF) continue;
6341 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6342 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6346 Ops.push_back(DAG.getUNDEF(DstEltVT));
6348 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6351 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6352 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6353 &Ops[0], Ops.size());
6356 // Finally, this must be the case where we are shrinking elements: each input
6357 // turns into multiple outputs.
6358 bool isS2V = ISD::isScalarToVector(BV);
6359 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6360 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6361 NumOutputsPerInput*BV->getNumOperands());
6362 SmallVector<SDValue, 8> Ops;
6364 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6365 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6366 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6367 Ops.push_back(DAG.getUNDEF(DstEltVT));
6371 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6372 getAPIntValue().zextOrTrunc(SrcBitSize);
6374 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6375 APInt ThisVal = OpVal.trunc(DstBitSize);
6376 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6377 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6378 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6379 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6381 OpVal = OpVal.lshr(DstBitSize);
6384 // For big endian targets, swap the order of the pieces of each element.
6385 if (TLI.isBigEndian())
6386 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6389 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6390 &Ops[0], Ops.size());
6393 SDValue DAGCombiner::visitFADD(SDNode *N) {
6394 SDValue N0 = N->getOperand(0);
6395 SDValue N1 = N->getOperand(1);
6396 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6397 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6398 EVT VT = N->getValueType(0);
6401 if (VT.isVector()) {
6402 SDValue FoldedVOp = SimplifyVBinOp(N);
6403 if (FoldedVOp.getNode()) return FoldedVOp;
6406 // fold (fadd c1, c2) -> c1 + c2
6408 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6409 // canonicalize constant to RHS
6410 if (N0CFP && !N1CFP)
6411 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6412 // fold (fadd A, 0) -> A
6413 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6414 N1CFP->getValueAPF().isZero())
6416 // fold (fadd A, (fneg B)) -> (fsub A, B)
6417 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6418 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6419 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6420 GetNegatedExpression(N1, DAG, LegalOperations));
6421 // fold (fadd (fneg A), B) -> (fsub B, A)
6422 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6423 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6424 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6425 GetNegatedExpression(N0, DAG, LegalOperations));
6427 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6428 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6429 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6430 isa<ConstantFPSDNode>(N0.getOperand(1)))
6431 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6432 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6433 N0.getOperand(1), N1));
6435 // No FP constant should be created after legalization as Instruction
6436 // Selection pass has hard time in dealing with FP constant.
6438 // We don't need test this condition for transformation like following, as
6439 // the DAG being transformed implies it is legal to take FP constant as
6442 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6444 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6446 // If allow, fold (fadd (fneg x), x) -> 0.0
6447 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6448 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6449 return DAG.getConstantFP(0.0, VT);
6451 // If allow, fold (fadd x, (fneg x)) -> 0.0
6452 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6453 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6454 return DAG.getConstantFP(0.0, VT);
6456 // In unsafe math mode, we can fold chains of FADD's of the same value
6457 // into multiplications. This transform is not safe in general because
6458 // we are reducing the number of rounding steps.
6459 if (DAG.getTarget().Options.UnsafeFPMath &&
6460 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6462 if (N0.getOpcode() == ISD::FMUL) {
6463 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6464 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6466 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6467 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6468 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6470 DAG.getConstantFP(1.0, VT));
6471 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6475 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6476 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6477 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6479 DAG.getConstantFP(1.0, VT));
6480 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6484 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6485 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6486 N1.getOperand(0) == N1.getOperand(1) &&
6487 N0.getOperand(1) == N1.getOperand(0)) {
6488 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6490 DAG.getConstantFP(2.0, VT));
6491 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6492 N0.getOperand(1), NewCFP);
6495 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6496 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6497 N1.getOperand(0) == N1.getOperand(1) &&
6498 N0.getOperand(0) == N1.getOperand(0)) {
6499 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6501 DAG.getConstantFP(2.0, VT));
6502 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6503 N0.getOperand(0), NewCFP);
6507 if (N1.getOpcode() == ISD::FMUL) {
6508 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6509 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6511 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6512 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6513 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6515 DAG.getConstantFP(1.0, VT));
6516 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6520 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6521 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6522 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6524 DAG.getConstantFP(1.0, VT));
6525 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6530 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6531 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6532 N0.getOperand(0) == N0.getOperand(1) &&
6533 N1.getOperand(1) == N0.getOperand(0)) {
6534 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6536 DAG.getConstantFP(2.0, VT));
6537 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6538 N1.getOperand(1), NewCFP);
6541 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6542 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6543 N0.getOperand(0) == N0.getOperand(1) &&
6544 N1.getOperand(0) == N0.getOperand(0)) {
6545 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6547 DAG.getConstantFP(2.0, VT));
6548 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6549 N1.getOperand(0), NewCFP);
6553 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6554 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6555 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6556 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6557 (N0.getOperand(0) == N1))
6558 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6559 N1, DAG.getConstantFP(3.0, VT));
6562 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6563 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6564 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6565 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6566 N1.getOperand(0) == N0)
6567 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6568 N0, DAG.getConstantFP(3.0, VT));
6571 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6572 if (AllowNewFpConst &&
6573 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6574 N0.getOperand(0) == N0.getOperand(1) &&
6575 N1.getOperand(0) == N1.getOperand(1) &&
6576 N0.getOperand(0) == N1.getOperand(0))
6577 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6579 DAG.getConstantFP(4.0, VT));
6582 // FADD -> FMA combines:
6583 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6584 DAG.getTarget().Options.UnsafeFPMath) &&
6585 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6586 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6588 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6589 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6590 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6591 N0.getOperand(0), N0.getOperand(1), N1);
6593 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6594 // Note: Commutes FADD operands.
6595 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6596 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6597 N1.getOperand(0), N1.getOperand(1), N0);
6603 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6604 SDValue N0 = N->getOperand(0);
6605 SDValue N1 = N->getOperand(1);
6606 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6607 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6608 EVT VT = N->getValueType(0);
6612 if (VT.isVector()) {
6613 SDValue FoldedVOp = SimplifyVBinOp(N);
6614 if (FoldedVOp.getNode()) return FoldedVOp;
6617 // fold (fsub c1, c2) -> c1-c2
6619 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6620 // fold (fsub A, 0) -> A
6621 if (DAG.getTarget().Options.UnsafeFPMath &&
6622 N1CFP && N1CFP->getValueAPF().isZero())
6624 // fold (fsub 0, B) -> -B
6625 if (DAG.getTarget().Options.UnsafeFPMath &&
6626 N0CFP && N0CFP->getValueAPF().isZero()) {
6627 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6628 return GetNegatedExpression(N1, DAG, LegalOperations);
6629 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6630 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6632 // fold (fsub A, (fneg B)) -> (fadd A, B)
6633 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6634 return DAG.getNode(ISD::FADD, dl, VT, N0,
6635 GetNegatedExpression(N1, DAG, LegalOperations));
6637 // If 'unsafe math' is enabled, fold
6638 // (fsub x, x) -> 0.0 &
6639 // (fsub x, (fadd x, y)) -> (fneg y) &
6640 // (fsub x, (fadd y, x)) -> (fneg y)
6641 if (DAG.getTarget().Options.UnsafeFPMath) {
6643 return DAG.getConstantFP(0.0f, VT);
6645 if (N1.getOpcode() == ISD::FADD) {
6646 SDValue N10 = N1->getOperand(0);
6647 SDValue N11 = N1->getOperand(1);
6649 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6650 &DAG.getTarget().Options))
6651 return GetNegatedExpression(N11, DAG, LegalOperations);
6653 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6654 &DAG.getTarget().Options))
6655 return GetNegatedExpression(N10, DAG, LegalOperations);
6659 // FSUB -> FMA combines:
6660 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6661 DAG.getTarget().Options.UnsafeFPMath) &&
6662 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6663 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6665 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6666 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6667 return DAG.getNode(ISD::FMA, dl, VT,
6668 N0.getOperand(0), N0.getOperand(1),
6669 DAG.getNode(ISD::FNEG, dl, VT, N1));
6671 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6672 // Note: Commutes FSUB operands.
6673 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6674 return DAG.getNode(ISD::FMA, dl, VT,
6675 DAG.getNode(ISD::FNEG, dl, VT,
6677 N1.getOperand(1), N0);
6679 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6680 if (N0.getOpcode() == ISD::FNEG &&
6681 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6682 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6683 SDValue N00 = N0.getOperand(0).getOperand(0);
6684 SDValue N01 = N0.getOperand(0).getOperand(1);
6685 return DAG.getNode(ISD::FMA, dl, VT,
6686 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6687 DAG.getNode(ISD::FNEG, dl, VT, N1));
6694 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6695 SDValue N0 = N->getOperand(0);
6696 SDValue N1 = N->getOperand(1);
6697 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6698 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6699 EVT VT = N->getValueType(0);
6700 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6703 if (VT.isVector()) {
6704 SDValue FoldedVOp = SimplifyVBinOp(N);
6705 if (FoldedVOp.getNode()) return FoldedVOp;
6708 // fold (fmul c1, c2) -> c1*c2
6710 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6711 // canonicalize constant to RHS
6712 if (N0CFP && !N1CFP)
6713 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6714 // fold (fmul A, 0) -> 0
6715 if (DAG.getTarget().Options.UnsafeFPMath &&
6716 N1CFP && N1CFP->getValueAPF().isZero())
6718 // fold (fmul A, 0) -> 0, vector edition.
6719 if (DAG.getTarget().Options.UnsafeFPMath &&
6720 ISD::isBuildVectorAllZeros(N1.getNode()))
6722 // fold (fmul A, 1.0) -> A
6723 if (N1CFP && N1CFP->isExactlyValue(1.0))
6725 // fold (fmul X, 2.0) -> (fadd X, X)
6726 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6727 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6728 // fold (fmul X, -1.0) -> (fneg X)
6729 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6730 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6731 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6733 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6734 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6735 &DAG.getTarget().Options)) {
6736 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6737 &DAG.getTarget().Options)) {
6738 // Both can be negated for free, check to see if at least one is cheaper
6740 if (LHSNeg == 2 || RHSNeg == 2)
6741 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6742 GetNegatedExpression(N0, DAG, LegalOperations),
6743 GetNegatedExpression(N1, DAG, LegalOperations));
6747 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6748 if (DAG.getTarget().Options.UnsafeFPMath &&
6749 N1CFP && N0.getOpcode() == ISD::FMUL &&
6750 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6751 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6752 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6753 N0.getOperand(1), N1));
6758 SDValue DAGCombiner::visitFMA(SDNode *N) {
6759 SDValue N0 = N->getOperand(0);
6760 SDValue N1 = N->getOperand(1);
6761 SDValue N2 = N->getOperand(2);
6762 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6763 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6764 EVT VT = N->getValueType(0);
6767 if (DAG.getTarget().Options.UnsafeFPMath) {
6768 if (N0CFP && N0CFP->isZero())
6770 if (N1CFP && N1CFP->isZero())
6773 if (N0CFP && N0CFP->isExactlyValue(1.0))
6774 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6775 if (N1CFP && N1CFP->isExactlyValue(1.0))
6776 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6778 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6779 if (N0CFP && !N1CFP)
6780 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6782 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6783 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6784 N2.getOpcode() == ISD::FMUL &&
6785 N0 == N2.getOperand(0) &&
6786 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6787 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6788 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6792 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6793 if (DAG.getTarget().Options.UnsafeFPMath &&
6794 N0.getOpcode() == ISD::FMUL && N1CFP &&
6795 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6796 return DAG.getNode(ISD::FMA, dl, VT,
6798 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6802 // (fma x, 1, y) -> (fadd x, y)
6803 // (fma x, -1, y) -> (fadd (fneg x), y)
6805 if (N1CFP->isExactlyValue(1.0))
6806 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6808 if (N1CFP->isExactlyValue(-1.0) &&
6809 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6810 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6811 AddToWorkList(RHSNeg.getNode());
6812 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6816 // (fma x, c, x) -> (fmul x, (c+1))
6817 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6818 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6819 DAG.getNode(ISD::FADD, dl, VT,
6820 N1, DAG.getConstantFP(1.0, VT)));
6822 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6823 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6824 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6825 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6826 DAG.getNode(ISD::FADD, dl, VT,
6827 N1, DAG.getConstantFP(-1.0, VT)));
6833 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6834 SDValue N0 = N->getOperand(0);
6835 SDValue N1 = N->getOperand(1);
6836 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6837 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6838 EVT VT = N->getValueType(0);
6839 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6842 if (VT.isVector()) {
6843 SDValue FoldedVOp = SimplifyVBinOp(N);
6844 if (FoldedVOp.getNode()) return FoldedVOp;
6847 // fold (fdiv c1, c2) -> c1/c2
6849 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6851 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6852 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6853 // Compute the reciprocal 1.0 / c2.
6854 APFloat N1APF = N1CFP->getValueAPF();
6855 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6856 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6857 // Only do the transform if the reciprocal is a legal fp immediate that
6858 // isn't too nasty (eg NaN, denormal, ...).
6859 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6860 (!LegalOperations ||
6861 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6862 // backend)... we should handle this gracefully after Legalize.
6863 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6864 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6865 TLI.isFPImmLegal(Recip, VT)))
6866 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6867 DAG.getConstantFP(Recip, VT));
6870 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6871 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6872 &DAG.getTarget().Options)) {
6873 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6874 &DAG.getTarget().Options)) {
6875 // Both can be negated for free, check to see if at least one is cheaper
6877 if (LHSNeg == 2 || RHSNeg == 2)
6878 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6879 GetNegatedExpression(N0, DAG, LegalOperations),
6880 GetNegatedExpression(N1, DAG, LegalOperations));
6887 SDValue DAGCombiner::visitFREM(SDNode *N) {
6888 SDValue N0 = N->getOperand(0);
6889 SDValue N1 = N->getOperand(1);
6890 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6891 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6892 EVT VT = N->getValueType(0);
6894 // fold (frem c1, c2) -> fmod(c1,c2)
6896 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6901 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6902 SDValue N0 = N->getOperand(0);
6903 SDValue N1 = N->getOperand(1);
6904 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6905 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6906 EVT VT = N->getValueType(0);
6908 if (N0CFP && N1CFP) // Constant fold
6909 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6912 const APFloat& V = N1CFP->getValueAPF();
6913 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6914 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6915 if (!V.isNegative()) {
6916 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6917 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6919 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6920 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6921 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6925 // copysign(fabs(x), y) -> copysign(x, y)
6926 // copysign(fneg(x), y) -> copysign(x, y)
6927 // copysign(copysign(x,z), y) -> copysign(x, y)
6928 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6929 N0.getOpcode() == ISD::FCOPYSIGN)
6930 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6931 N0.getOperand(0), N1);
6933 // copysign(x, abs(y)) -> abs(x)
6934 if (N1.getOpcode() == ISD::FABS)
6935 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6937 // copysign(x, copysign(y,z)) -> copysign(x, z)
6938 if (N1.getOpcode() == ISD::FCOPYSIGN)
6939 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6940 N0, N1.getOperand(1));
6942 // copysign(x, fp_extend(y)) -> copysign(x, y)
6943 // copysign(x, fp_round(y)) -> copysign(x, y)
6944 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6945 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6946 N0, N1.getOperand(0));
6951 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6952 SDValue N0 = N->getOperand(0);
6953 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6954 EVT VT = N->getValueType(0);
6955 EVT OpVT = N0.getValueType();
6957 // fold (sint_to_fp c1) -> c1fp
6959 // ...but only if the target supports immediate floating-point values
6960 (!LegalOperations ||
6961 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6962 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6964 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6965 // but UINT_TO_FP is legal on this target, try to convert.
6966 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6967 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6968 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6969 if (DAG.SignBitIsZero(N0))
6970 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6973 // The next optimizations are desirable only if SELECT_CC can be lowered.
6974 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6975 // having to say they don't support SELECT_CC on every type the DAG knows
6976 // about, since there is no way to mark an opcode illegal at all value types
6977 // (See also visitSELECT)
6978 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6979 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6980 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6982 (!LegalOperations ||
6983 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6985 { N0.getOperand(0), N0.getOperand(1),
6986 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6988 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6991 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6992 // (select_cc x, y, 1.0, 0.0,, cc)
6993 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6994 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6995 (!LegalOperations ||
6996 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6998 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6999 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7000 N0.getOperand(0).getOperand(2) };
7001 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7008 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7009 SDValue N0 = N->getOperand(0);
7010 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7011 EVT VT = N->getValueType(0);
7012 EVT OpVT = N0.getValueType();
7014 // fold (uint_to_fp c1) -> c1fp
7016 // ...but only if the target supports immediate floating-point values
7017 (!LegalOperations ||
7018 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7019 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7021 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7022 // but SINT_TO_FP is legal on this target, try to convert.
7023 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7024 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7025 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7026 if (DAG.SignBitIsZero(N0))
7027 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7030 // The next optimizations are desirable only if SELECT_CC can be lowered.
7031 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7032 // having to say they don't support SELECT_CC on every type the DAG knows
7033 // about, since there is no way to mark an opcode illegal at all value types
7034 // (See also visitSELECT)
7035 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7036 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7038 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7039 (!LegalOperations ||
7040 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7042 { N0.getOperand(0), N0.getOperand(1),
7043 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7045 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7052 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7053 SDValue N0 = N->getOperand(0);
7054 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7055 EVT VT = N->getValueType(0);
7057 // fold (fp_to_sint c1fp) -> c1
7059 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7064 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7065 SDValue N0 = N->getOperand(0);
7066 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7067 EVT VT = N->getValueType(0);
7069 // fold (fp_to_uint c1fp) -> c1
7071 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7076 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7077 SDValue N0 = N->getOperand(0);
7078 SDValue N1 = N->getOperand(1);
7079 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7080 EVT VT = N->getValueType(0);
7082 // fold (fp_round c1fp) -> c1fp
7084 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7086 // fold (fp_round (fp_extend x)) -> x
7087 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7088 return N0.getOperand(0);
7090 // fold (fp_round (fp_round x)) -> (fp_round x)
7091 if (N0.getOpcode() == ISD::FP_ROUND) {
7092 // This is a value preserving truncation if both round's are.
7093 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7094 N0.getNode()->getConstantOperandVal(1) == 1;
7095 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7096 DAG.getIntPtrConstant(IsTrunc));
7099 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7100 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7101 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7102 N0.getOperand(0), N1);
7103 AddToWorkList(Tmp.getNode());
7104 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7105 Tmp, N0.getOperand(1));
7111 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7112 SDValue N0 = N->getOperand(0);
7113 EVT VT = N->getValueType(0);
7114 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7115 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7117 // fold (fp_round_inreg c1fp) -> c1fp
7118 if (N0CFP && isTypeLegal(EVT)) {
7119 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7120 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7126 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7127 SDValue N0 = N->getOperand(0);
7128 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7129 EVT VT = N->getValueType(0);
7131 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7132 if (N->hasOneUse() &&
7133 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7136 // fold (fp_extend c1fp) -> c1fp
7138 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7140 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7142 if (N0.getOpcode() == ISD::FP_ROUND
7143 && N0.getNode()->getConstantOperandVal(1) == 1) {
7144 SDValue In = N0.getOperand(0);
7145 if (In.getValueType() == VT) return In;
7146 if (VT.bitsLT(In.getValueType()))
7147 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7148 In, N0.getOperand(1));
7149 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7152 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7153 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7154 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7155 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7156 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7157 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7159 LN0->getBasePtr(), N0.getValueType(),
7160 LN0->getMemOperand());
7161 CombineTo(N, ExtLoad);
7162 CombineTo(N0.getNode(),
7163 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7164 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7165 ExtLoad.getValue(1));
7166 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7172 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7173 SDValue N0 = N->getOperand(0);
7174 EVT VT = N->getValueType(0);
7176 if (VT.isVector()) {
7177 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7178 if (FoldedVOp.getNode()) return FoldedVOp;
7181 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7182 &DAG.getTarget().Options))
7183 return GetNegatedExpression(N0, DAG, LegalOperations);
7185 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7186 // constant pool values.
7187 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7189 N0.getNode()->hasOneUse() &&
7190 N0.getOperand(0).getValueType().isInteger()) {
7191 SDValue Int = N0.getOperand(0);
7192 EVT IntVT = Int.getValueType();
7193 if (IntVT.isInteger() && !IntVT.isVector()) {
7194 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7195 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7196 AddToWorkList(Int.getNode());
7197 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7202 // (fneg (fmul c, x)) -> (fmul -c, x)
7203 if (N0.getOpcode() == ISD::FMUL) {
7204 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7206 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7208 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7215 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7216 SDValue N0 = N->getOperand(0);
7217 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7218 EVT VT = N->getValueType(0);
7220 // fold (fceil c1) -> fceil(c1)
7222 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7227 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7228 SDValue N0 = N->getOperand(0);
7229 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7230 EVT VT = N->getValueType(0);
7232 // fold (ftrunc c1) -> ftrunc(c1)
7234 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7239 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7240 SDValue N0 = N->getOperand(0);
7241 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7242 EVT VT = N->getValueType(0);
7244 // fold (ffloor c1) -> ffloor(c1)
7246 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7251 SDValue DAGCombiner::visitFABS(SDNode *N) {
7252 SDValue N0 = N->getOperand(0);
7253 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7254 EVT VT = N->getValueType(0);
7256 if (VT.isVector()) {
7257 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7258 if (FoldedVOp.getNode()) return FoldedVOp;
7261 // fold (fabs c1) -> fabs(c1)
7263 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7264 // fold (fabs (fabs x)) -> (fabs x)
7265 if (N0.getOpcode() == ISD::FABS)
7266 return N->getOperand(0);
7267 // fold (fabs (fneg x)) -> (fabs x)
7268 // fold (fabs (fcopysign x, y)) -> (fabs x)
7269 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7270 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7272 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7273 // constant pool values.
7274 if (!TLI.isFAbsFree(VT) &&
7275 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7276 N0.getOperand(0).getValueType().isInteger() &&
7277 !N0.getOperand(0).getValueType().isVector()) {
7278 SDValue Int = N0.getOperand(0);
7279 EVT IntVT = Int.getValueType();
7280 if (IntVT.isInteger() && !IntVT.isVector()) {
7281 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7282 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7283 AddToWorkList(Int.getNode());
7284 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7285 N->getValueType(0), Int);
7292 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7293 SDValue Chain = N->getOperand(0);
7294 SDValue N1 = N->getOperand(1);
7295 SDValue N2 = N->getOperand(2);
7297 // If N is a constant we could fold this into a fallthrough or unconditional
7298 // branch. However that doesn't happen very often in normal code, because
7299 // Instcombine/SimplifyCFG should have handled the available opportunities.
7300 // If we did this folding here, it would be necessary to update the
7301 // MachineBasicBlock CFG, which is awkward.
7303 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7305 if (N1.getOpcode() == ISD::SETCC &&
7306 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7307 N1.getOperand(0).getValueType())) {
7308 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7309 Chain, N1.getOperand(2),
7310 N1.getOperand(0), N1.getOperand(1), N2);
7313 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7314 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7315 (N1.getOperand(0).hasOneUse() &&
7316 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7317 SDNode *Trunc = nullptr;
7318 if (N1.getOpcode() == ISD::TRUNCATE) {
7319 // Look pass the truncate.
7320 Trunc = N1.getNode();
7321 N1 = N1.getOperand(0);
7324 // Match this pattern so that we can generate simpler code:
7327 // %b = and i32 %a, 2
7328 // %c = srl i32 %b, 1
7329 // brcond i32 %c ...
7334 // %b = and i32 %a, 2
7335 // %c = setcc eq %b, 0
7338 // This applies only when the AND constant value has one bit set and the
7339 // SRL constant is equal to the log2 of the AND constant. The back-end is
7340 // smart enough to convert the result into a TEST/JMP sequence.
7341 SDValue Op0 = N1.getOperand(0);
7342 SDValue Op1 = N1.getOperand(1);
7344 if (Op0.getOpcode() == ISD::AND &&
7345 Op1.getOpcode() == ISD::Constant) {
7346 SDValue AndOp1 = Op0.getOperand(1);
7348 if (AndOp1.getOpcode() == ISD::Constant) {
7349 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7351 if (AndConst.isPowerOf2() &&
7352 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7354 DAG.getSetCC(SDLoc(N),
7355 getSetCCResultType(Op0.getValueType()),
7356 Op0, DAG.getConstant(0, Op0.getValueType()),
7359 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7360 MVT::Other, Chain, SetCC, N2);
7361 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7362 // will convert it back to (X & C1) >> C2.
7363 CombineTo(N, NewBRCond, false);
7364 // Truncate is dead.
7366 removeFromWorkList(Trunc);
7367 DAG.DeleteNode(Trunc);
7369 // Replace the uses of SRL with SETCC
7370 WorkListRemover DeadNodes(*this);
7371 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7372 removeFromWorkList(N1.getNode());
7373 DAG.DeleteNode(N1.getNode());
7374 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7380 // Restore N1 if the above transformation doesn't match.
7381 N1 = N->getOperand(1);
7384 // Transform br(xor(x, y)) -> br(x != y)
7385 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7386 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7387 SDNode *TheXor = N1.getNode();
7388 SDValue Op0 = TheXor->getOperand(0);
7389 SDValue Op1 = TheXor->getOperand(1);
7390 if (Op0.getOpcode() == Op1.getOpcode()) {
7391 // Avoid missing important xor optimizations.
7392 SDValue Tmp = visitXOR(TheXor);
7393 if (Tmp.getNode()) {
7394 if (Tmp.getNode() != TheXor) {
7395 DEBUG(dbgs() << "\nReplacing.8 ";
7397 dbgs() << "\nWith: ";
7398 Tmp.getNode()->dump(&DAG);
7400 WorkListRemover DeadNodes(*this);
7401 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7402 removeFromWorkList(TheXor);
7403 DAG.DeleteNode(TheXor);
7404 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7405 MVT::Other, Chain, Tmp, N2);
7408 // visitXOR has changed XOR's operands or replaced the XOR completely,
7410 return SDValue(N, 0);
7414 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7416 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7417 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7418 Op0.getOpcode() == ISD::XOR) {
7419 TheXor = Op0.getNode();
7423 EVT SetCCVT = N1.getValueType();
7425 SetCCVT = getSetCCResultType(SetCCVT);
7426 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7429 Equal ? ISD::SETEQ : ISD::SETNE);
7430 // Replace the uses of XOR with SETCC
7431 WorkListRemover DeadNodes(*this);
7432 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7433 removeFromWorkList(N1.getNode());
7434 DAG.DeleteNode(N1.getNode());
7435 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7436 MVT::Other, Chain, SetCC, N2);
7443 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7445 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7446 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7447 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7449 // If N is a constant we could fold this into a fallthrough or unconditional
7450 // branch. However that doesn't happen very often in normal code, because
7451 // Instcombine/SimplifyCFG should have handled the available opportunities.
7452 // If we did this folding here, it would be necessary to update the
7453 // MachineBasicBlock CFG, which is awkward.
7455 // Use SimplifySetCC to simplify SETCC's.
7456 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7457 CondLHS, CondRHS, CC->get(), SDLoc(N),
7459 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7461 // fold to a simpler setcc
7462 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7463 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7464 N->getOperand(0), Simp.getOperand(2),
7465 Simp.getOperand(0), Simp.getOperand(1),
7471 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7472 /// uses N as its base pointer and that N may be folded in the load / store
7473 /// addressing mode.
7474 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7476 const TargetLowering &TLI) {
7478 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7479 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7481 VT = Use->getValueType(0);
7482 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7483 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7485 VT = ST->getValue().getValueType();
7489 TargetLowering::AddrMode AM;
7490 if (N->getOpcode() == ISD::ADD) {
7491 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7494 AM.BaseOffs = Offset->getSExtValue();
7498 } else if (N->getOpcode() == ISD::SUB) {
7499 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7502 AM.BaseOffs = -Offset->getSExtValue();
7509 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7512 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7513 /// pre-indexed load / store when the base pointer is an add or subtract
7514 /// and it has other uses besides the load / store. After the
7515 /// transformation, the new indexed load / store has effectively folded
7516 /// the add / subtract in and all of its other uses are redirected to the
7517 /// new load / store.
7518 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7519 if (Level < AfterLegalizeDAG)
7525 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7526 if (LD->isIndexed())
7528 VT = LD->getMemoryVT();
7529 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7530 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7532 Ptr = LD->getBasePtr();
7533 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7534 if (ST->isIndexed())
7536 VT = ST->getMemoryVT();
7537 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7538 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7540 Ptr = ST->getBasePtr();
7546 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7547 // out. There is no reason to make this a preinc/predec.
7548 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7549 Ptr.getNode()->hasOneUse())
7552 // Ask the target to do addressing mode selection.
7555 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7556 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7559 // Backends without true r+i pre-indexed forms may need to pass a
7560 // constant base with a variable offset so that constant coercion
7561 // will work with the patterns in canonical form.
7562 bool Swapped = false;
7563 if (isa<ConstantSDNode>(BasePtr)) {
7564 std::swap(BasePtr, Offset);
7568 // Don't create a indexed load / store with zero offset.
7569 if (isa<ConstantSDNode>(Offset) &&
7570 cast<ConstantSDNode>(Offset)->isNullValue())
7573 // Try turning it into a pre-indexed load / store except when:
7574 // 1) The new base ptr is a frame index.
7575 // 2) If N is a store and the new base ptr is either the same as or is a
7576 // predecessor of the value being stored.
7577 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7578 // that would create a cycle.
7579 // 4) All uses are load / store ops that use it as old base ptr.
7581 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7582 // (plus the implicit offset) to a register to preinc anyway.
7583 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7588 SDValue Val = cast<StoreSDNode>(N)->getValue();
7589 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7593 // If the offset is a constant, there may be other adds of constants that
7594 // can be folded with this one. We should do this to avoid having to keep
7595 // a copy of the original base pointer.
7596 SmallVector<SDNode *, 16> OtherUses;
7597 if (isa<ConstantSDNode>(Offset))
7598 for (SDNode *Use : BasePtr.getNode()->uses()) {
7599 if (Use == Ptr.getNode())
7602 if (Use->isPredecessorOf(N))
7605 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7610 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7611 if (Op1.getNode() == BasePtr.getNode())
7612 std::swap(Op0, Op1);
7613 assert(Op0.getNode() == BasePtr.getNode() &&
7614 "Use of ADD/SUB but not an operand");
7616 if (!isa<ConstantSDNode>(Op1)) {
7621 // FIXME: In some cases, we can be smarter about this.
7622 if (Op1.getValueType() != Offset.getValueType()) {
7627 OtherUses.push_back(Use);
7631 std::swap(BasePtr, Offset);
7633 // Now check for #3 and #4.
7634 bool RealUse = false;
7636 // Caches for hasPredecessorHelper
7637 SmallPtrSet<const SDNode *, 32> Visited;
7638 SmallVector<const SDNode *, 16> Worklist;
7640 for (SDNode *Use : Ptr.getNode()->uses()) {
7643 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7646 // If Ptr may be folded in addressing mode of other use, then it's
7647 // not profitable to do this transformation.
7648 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7657 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7658 BasePtr, Offset, AM);
7660 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7661 BasePtr, Offset, AM);
7664 DEBUG(dbgs() << "\nReplacing.4 ";
7666 dbgs() << "\nWith: ";
7667 Result.getNode()->dump(&DAG);
7669 WorkListRemover DeadNodes(*this);
7671 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7672 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7674 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7677 // Finally, since the node is now dead, remove it from the graph.
7681 std::swap(BasePtr, Offset);
7683 // Replace other uses of BasePtr that can be updated to use Ptr
7684 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7685 unsigned OffsetIdx = 1;
7686 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7688 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7689 BasePtr.getNode() && "Expected BasePtr operand");
7691 // We need to replace ptr0 in the following expression:
7692 // x0 * offset0 + y0 * ptr0 = t0
7694 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7696 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7697 // indexed load/store and the expresion that needs to be re-written.
7699 // Therefore, we have:
7700 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7702 ConstantSDNode *CN =
7703 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7705 APInt Offset0 = CN->getAPIntValue();
7706 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7708 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7709 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7710 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7711 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7713 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7715 APInt CNV = Offset0;
7716 if (X0 < 0) CNV = -CNV;
7717 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7718 else CNV = CNV - Offset1;
7720 // We can now generate the new expression.
7721 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7722 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7724 SDValue NewUse = DAG.getNode(Opcode,
7725 SDLoc(OtherUses[i]),
7726 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7727 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7728 removeFromWorkList(OtherUses[i]);
7729 DAG.DeleteNode(OtherUses[i]);
7732 // Replace the uses of Ptr with uses of the updated base value.
7733 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7734 removeFromWorkList(Ptr.getNode());
7735 DAG.DeleteNode(Ptr.getNode());
7740 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7741 /// add / sub of the base pointer node into a post-indexed load / store.
7742 /// The transformation folded the add / subtract into the new indexed
7743 /// load / store effectively and all of its uses are redirected to the
7744 /// new load / store.
7745 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7746 if (Level < AfterLegalizeDAG)
7752 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7753 if (LD->isIndexed())
7755 VT = LD->getMemoryVT();
7756 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7757 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7759 Ptr = LD->getBasePtr();
7760 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7761 if (ST->isIndexed())
7763 VT = ST->getMemoryVT();
7764 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7765 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7767 Ptr = ST->getBasePtr();
7773 if (Ptr.getNode()->hasOneUse())
7776 for (SDNode *Op : Ptr.getNode()->uses()) {
7778 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7783 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7784 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7785 // Don't create a indexed load / store with zero offset.
7786 if (isa<ConstantSDNode>(Offset) &&
7787 cast<ConstantSDNode>(Offset)->isNullValue())
7790 // Try turning it into a post-indexed load / store except when
7791 // 1) All uses are load / store ops that use it as base ptr (and
7792 // it may be folded as addressing mmode).
7793 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7794 // nor a successor of N. Otherwise, if Op is folded that would
7797 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7801 bool TryNext = false;
7802 for (SDNode *Use : BasePtr.getNode()->uses()) {
7803 if (Use == Ptr.getNode())
7806 // If all the uses are load / store addresses, then don't do the
7808 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7809 bool RealUse = false;
7810 for (SDNode *UseUse : Use->uses()) {
7811 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7826 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7827 SDValue Result = isLoad
7828 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7829 BasePtr, Offset, AM)
7830 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7831 BasePtr, Offset, AM);
7834 DEBUG(dbgs() << "\nReplacing.5 ";
7836 dbgs() << "\nWith: ";
7837 Result.getNode()->dump(&DAG);
7839 WorkListRemover DeadNodes(*this);
7841 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7842 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7844 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7847 // Finally, since the node is now dead, remove it from the graph.
7850 // Replace the uses of Use with uses of the updated base value.
7851 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7852 Result.getValue(isLoad ? 1 : 0));
7853 removeFromWorkList(Op);
7863 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7864 LoadSDNode *LD = cast<LoadSDNode>(N);
7865 SDValue Chain = LD->getChain();
7866 SDValue Ptr = LD->getBasePtr();
7868 // If load is not volatile and there are no uses of the loaded value (and
7869 // the updated indexed value in case of indexed loads), change uses of the
7870 // chain value into uses of the chain input (i.e. delete the dead load).
7871 if (!LD->isVolatile()) {
7872 if (N->getValueType(1) == MVT::Other) {
7874 if (!N->hasAnyUseOfValue(0)) {
7875 // It's not safe to use the two value CombineTo variant here. e.g.
7876 // v1, chain2 = load chain1, loc
7877 // v2, chain3 = load chain2, loc
7879 // Now we replace use of chain2 with chain1. This makes the second load
7880 // isomorphic to the one we are deleting, and thus makes this load live.
7881 DEBUG(dbgs() << "\nReplacing.6 ";
7883 dbgs() << "\nWith chain: ";
7884 Chain.getNode()->dump(&DAG);
7886 WorkListRemover DeadNodes(*this);
7887 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7889 if (N->use_empty()) {
7890 removeFromWorkList(N);
7894 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7898 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7899 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7900 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7901 DEBUG(dbgs() << "\nReplacing.7 ";
7903 dbgs() << "\nWith: ";
7904 Undef.getNode()->dump(&DAG);
7905 dbgs() << " and 2 other values\n");
7906 WorkListRemover DeadNodes(*this);
7907 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7908 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7909 DAG.getUNDEF(N->getValueType(1)));
7910 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7911 removeFromWorkList(N);
7913 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7918 // If this load is directly stored, replace the load value with the stored
7920 // TODO: Handle store large -> read small portion.
7921 // TODO: Handle TRUNCSTORE/LOADEXT
7922 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7923 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7924 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7925 if (PrevST->getBasePtr() == Ptr &&
7926 PrevST->getValue().getValueType() == N->getValueType(0))
7927 return CombineTo(N, Chain.getOperand(1), Chain);
7931 // Try to infer better alignment information than the load already has.
7932 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7933 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7934 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7936 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7937 LD->getValueType(0),
7938 Chain, Ptr, LD->getPointerInfo(),
7940 LD->isVolatile(), LD->isNonTemporal(), Align,
7942 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7947 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7948 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7950 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7951 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7954 if (UseAA && LD->isUnindexed()) {
7955 // Walk up chain skipping non-aliasing memory nodes.
7956 SDValue BetterChain = FindBetterChain(N, Chain);
7958 // If there is a better chain.
7959 if (Chain != BetterChain) {
7962 // Replace the chain to void dependency.
7963 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7964 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7965 BetterChain, Ptr, LD->getMemOperand());
7967 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7968 LD->getValueType(0),
7969 BetterChain, Ptr, LD->getMemoryVT(),
7970 LD->getMemOperand());
7973 // Create token factor to keep old chain connected.
7974 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7975 MVT::Other, Chain, ReplLoad.getValue(1));
7977 // Make sure the new and old chains are cleaned up.
7978 AddToWorkList(Token.getNode());
7980 // Replace uses with load result and token factor. Don't add users
7982 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7986 // Try transforming N to an indexed load.
7987 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7988 return SDValue(N, 0);
7990 // Try to slice up N to more direct loads if the slices are mapped to
7991 // different register banks or pairing can take place.
7993 return SDValue(N, 0);
7999 /// \brief Helper structure used to slice a load in smaller loads.
8000 /// Basically a slice is obtained from the following sequence:
8001 /// Origin = load Ty1, Base
8002 /// Shift = srl Ty1 Origin, CstTy Amount
8003 /// Inst = trunc Shift to Ty2
8005 /// Then, it will be rewriten into:
8006 /// Slice = load SliceTy, Base + SliceOffset
8007 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8009 /// SliceTy is deduced from the number of bits that are actually used to
8011 struct LoadedSlice {
8012 /// \brief Helper structure used to compute the cost of a slice.
8014 /// Are we optimizing for code size.
8019 unsigned CrossRegisterBanksCopies;
8023 Cost(bool ForCodeSize = false)
8024 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8025 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8027 /// \brief Get the cost of one isolated slice.
8028 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8029 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8030 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8031 EVT TruncType = LS.Inst->getValueType(0);
8032 EVT LoadedType = LS.getLoadedType();
8033 if (TruncType != LoadedType &&
8034 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8038 /// \brief Account for slicing gain in the current cost.
8039 /// Slicing provide a few gains like removing a shift or a
8040 /// truncate. This method allows to grow the cost of the original
8041 /// load with the gain from this slice.
8042 void addSliceGain(const LoadedSlice &LS) {
8043 // Each slice saves a truncate.
8044 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8045 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8046 LS.Inst->getOperand(0).getValueType()))
8048 // If there is a shift amount, this slice gets rid of it.
8051 // If this slice can merge a cross register bank copy, account for it.
8052 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8053 ++CrossRegisterBanksCopies;
8056 Cost &operator+=(const Cost &RHS) {
8058 Truncates += RHS.Truncates;
8059 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8065 bool operator==(const Cost &RHS) const {
8066 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8067 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8068 ZExts == RHS.ZExts && Shift == RHS.Shift;
8071 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8073 bool operator<(const Cost &RHS) const {
8074 // Assume cross register banks copies are as expensive as loads.
8075 // FIXME: Do we want some more target hooks?
8076 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8077 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8078 // Unless we are optimizing for code size, consider the
8079 // expensive operation first.
8080 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8081 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8082 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8083 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8086 bool operator>(const Cost &RHS) const { return RHS < *this; }
8088 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8090 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8092 // The last instruction that represent the slice. This should be a
8093 // truncate instruction.
8095 // The original load instruction.
8097 // The right shift amount in bits from the original load.
8099 // The DAG from which Origin came from.
8100 // This is used to get some contextual information about legal types, etc.
8103 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8104 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8105 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8107 LoadedSlice(const LoadedSlice &LS)
8108 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8110 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8111 /// \return Result is \p BitWidth and has used bits set to 1 and
8112 /// not used bits set to 0.
8113 APInt getUsedBits() const {
8114 // Reproduce the trunc(lshr) sequence:
8115 // - Start from the truncated value.
8116 // - Zero extend to the desired bit width.
8118 assert(Origin && "No original load to compare against.");
8119 unsigned BitWidth = Origin->getValueSizeInBits(0);
8120 assert(Inst && "This slice is not bound to an instruction");
8121 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8122 "Extracted slice is bigger than the whole type!");
8123 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8124 UsedBits.setAllBits();
8125 UsedBits = UsedBits.zext(BitWidth);
8130 /// \brief Get the size of the slice to be loaded in bytes.
8131 unsigned getLoadedSize() const {
8132 unsigned SliceSize = getUsedBits().countPopulation();
8133 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8134 return SliceSize / 8;
8137 /// \brief Get the type that will be loaded for this slice.
8138 /// Note: This may not be the final type for the slice.
8139 EVT getLoadedType() const {
8140 assert(DAG && "Missing context");
8141 LLVMContext &Ctxt = *DAG->getContext();
8142 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8145 /// \brief Get the alignment of the load used for this slice.
8146 unsigned getAlignment() const {
8147 unsigned Alignment = Origin->getAlignment();
8148 unsigned Offset = getOffsetFromBase();
8150 Alignment = MinAlign(Alignment, Alignment + Offset);
8154 /// \brief Check if this slice can be rewritten with legal operations.
8155 bool isLegal() const {
8156 // An invalid slice is not legal.
8157 if (!Origin || !Inst || !DAG)
8160 // Offsets are for indexed load only, we do not handle that.
8161 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8164 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8166 // Check that the type is legal.
8167 EVT SliceType = getLoadedType();
8168 if (!TLI.isTypeLegal(SliceType))
8171 // Check that the load is legal for this type.
8172 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8175 // Check that the offset can be computed.
8176 // 1. Check its type.
8177 EVT PtrType = Origin->getBasePtr().getValueType();
8178 if (PtrType == MVT::Untyped || PtrType.isExtended())
8181 // 2. Check that it fits in the immediate.
8182 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8185 // 3. Check that the computation is legal.
8186 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8189 // Check that the zext is legal if it needs one.
8190 EVT TruncateType = Inst->getValueType(0);
8191 if (TruncateType != SliceType &&
8192 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8198 /// \brief Get the offset in bytes of this slice in the original chunk of
8200 /// \pre DAG != nullptr.
8201 uint64_t getOffsetFromBase() const {
8202 assert(DAG && "Missing context.");
8204 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8205 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8206 uint64_t Offset = Shift / 8;
8207 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8208 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8209 "The size of the original loaded type is not a multiple of a"
8211 // If Offset is bigger than TySizeInBytes, it means we are loading all
8212 // zeros. This should have been optimized before in the process.
8213 assert(TySizeInBytes > Offset &&
8214 "Invalid shift amount for given loaded size");
8216 Offset = TySizeInBytes - Offset - getLoadedSize();
8220 /// \brief Generate the sequence of instructions to load the slice
8221 /// represented by this object and redirect the uses of this slice to
8222 /// this new sequence of instructions.
8223 /// \pre this->Inst && this->Origin are valid Instructions and this
8224 /// object passed the legal check: LoadedSlice::isLegal returned true.
8225 /// \return The last instruction of the sequence used to load the slice.
8226 SDValue loadSlice() const {
8227 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8228 const SDValue &OldBaseAddr = Origin->getBasePtr();
8229 SDValue BaseAddr = OldBaseAddr;
8230 // Get the offset in that chunk of bytes w.r.t. the endianess.
8231 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8232 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8234 // BaseAddr = BaseAddr + Offset.
8235 EVT ArithType = BaseAddr.getValueType();
8236 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8237 DAG->getConstant(Offset, ArithType));
8240 // Create the type of the loaded slice according to its size.
8241 EVT SliceType = getLoadedType();
8243 // Create the load for the slice.
8244 SDValue LastInst = DAG->getLoad(
8245 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8246 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8247 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8248 // If the final type is not the same as the loaded type, this means that
8249 // we have to pad with zero. Create a zero extend for that.
8250 EVT FinalType = Inst->getValueType(0);
8251 if (SliceType != FinalType)
8253 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8257 /// \brief Check if this slice can be merged with an expensive cross register
8258 /// bank copy. E.g.,
8260 /// f = bitcast i32 i to float
8261 bool canMergeExpensiveCrossRegisterBankCopy() const {
8262 if (!Inst || !Inst->hasOneUse())
8264 SDNode *Use = *Inst->use_begin();
8265 if (Use->getOpcode() != ISD::BITCAST)
8267 assert(DAG && "Missing context");
8268 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8269 EVT ResVT = Use->getValueType(0);
8270 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8271 const TargetRegisterClass *ArgRC =
8272 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8273 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8276 // At this point, we know that we perform a cross-register-bank copy.
8277 // Check if it is expensive.
8278 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8279 // Assume bitcasts are cheap, unless both register classes do not
8280 // explicitly share a common sub class.
8281 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8284 // Check if it will be merged with the load.
8285 // 1. Check the alignment constraint.
8286 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8287 ResVT.getTypeForEVT(*DAG->getContext()));
8289 if (RequiredAlignment > getAlignment())
8292 // 2. Check that the load is a legal operation for that type.
8293 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8296 // 3. Check that we do not have a zext in the way.
8297 if (Inst->getValueType(0) != getLoadedType())
8305 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8306 /// \p UsedBits looks like 0..0 1..1 0..0.
8307 static bool areUsedBitsDense(const APInt &UsedBits) {
8308 // If all the bits are one, this is dense!
8309 if (UsedBits.isAllOnesValue())
8312 // Get rid of the unused bits on the right.
8313 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8314 // Get rid of the unused bits on the left.
8315 if (NarrowedUsedBits.countLeadingZeros())
8316 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8317 // Check that the chunk of bits is completely used.
8318 return NarrowedUsedBits.isAllOnesValue();
8321 /// \brief Check whether or not \p First and \p Second are next to each other
8322 /// in memory. This means that there is no hole between the bits loaded
8323 /// by \p First and the bits loaded by \p Second.
8324 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8325 const LoadedSlice &Second) {
8326 assert(First.Origin == Second.Origin && First.Origin &&
8327 "Unable to match different memory origins.");
8328 APInt UsedBits = First.getUsedBits();
8329 assert((UsedBits & Second.getUsedBits()) == 0 &&
8330 "Slices are not supposed to overlap.");
8331 UsedBits |= Second.getUsedBits();
8332 return areUsedBitsDense(UsedBits);
8335 /// \brief Adjust the \p GlobalLSCost according to the target
8336 /// paring capabilities and the layout of the slices.
8337 /// \pre \p GlobalLSCost should account for at least as many loads as
8338 /// there is in the slices in \p LoadedSlices.
8339 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8340 LoadedSlice::Cost &GlobalLSCost) {
8341 unsigned NumberOfSlices = LoadedSlices.size();
8342 // If there is less than 2 elements, no pairing is possible.
8343 if (NumberOfSlices < 2)
8346 // Sort the slices so that elements that are likely to be next to each
8347 // other in memory are next to each other in the list.
8348 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8349 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8350 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8351 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8353 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8354 // First (resp. Second) is the first (resp. Second) potentially candidate
8355 // to be placed in a paired load.
8356 const LoadedSlice *First = nullptr;
8357 const LoadedSlice *Second = nullptr;
8358 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8359 // Set the beginning of the pair.
8362 Second = &LoadedSlices[CurrSlice];
8364 // If First is NULL, it means we start a new pair.
8365 // Get to the next slice.
8369 EVT LoadedType = First->getLoadedType();
8371 // If the types of the slices are different, we cannot pair them.
8372 if (LoadedType != Second->getLoadedType())
8375 // Check if the target supplies paired loads for this type.
8376 unsigned RequiredAlignment = 0;
8377 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8378 // move to the next pair, this type is hopeless.
8382 // Check if we meet the alignment requirement.
8383 if (RequiredAlignment > First->getAlignment())
8386 // Check that both loads are next to each other in memory.
8387 if (!areSlicesNextToEachOther(*First, *Second))
8390 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8391 --GlobalLSCost.Loads;
8392 // Move to the next pair.
8397 /// \brief Check the profitability of all involved LoadedSlice.
8398 /// Currently, it is considered profitable if there is exactly two
8399 /// involved slices (1) which are (2) next to each other in memory, and
8400 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8402 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8403 /// the elements themselves.
8405 /// FIXME: When the cost model will be mature enough, we can relax
8406 /// constraints (1) and (2).
8407 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8408 const APInt &UsedBits, bool ForCodeSize) {
8409 unsigned NumberOfSlices = LoadedSlices.size();
8410 if (StressLoadSlicing)
8411 return NumberOfSlices > 1;
8414 if (NumberOfSlices != 2)
8418 if (!areUsedBitsDense(UsedBits))
8422 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8423 // The original code has one big load.
8425 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8426 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8427 // Accumulate the cost of all the slices.
8428 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8429 GlobalSlicingCost += SliceCost;
8431 // Account as cost in the original configuration the gain obtained
8432 // with the current slices.
8433 OrigCost.addSliceGain(LS);
8436 // If the target supports paired load, adjust the cost accordingly.
8437 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8438 return OrigCost > GlobalSlicingCost;
8441 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8442 /// operations, split it in the various pieces being extracted.
8444 /// This sort of thing is introduced by SROA.
8445 /// This slicing takes care not to insert overlapping loads.
8446 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8447 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8448 if (Level < AfterLegalizeDAG)
8451 LoadSDNode *LD = cast<LoadSDNode>(N);
8452 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8453 !LD->getValueType(0).isInteger())
8456 // Keep track of already used bits to detect overlapping values.
8457 // In that case, we will just abort the transformation.
8458 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8460 SmallVector<LoadedSlice, 4> LoadedSlices;
8462 // Check if this load is used as several smaller chunks of bits.
8463 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8464 // of computation for each trunc.
8465 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8466 UI != UIEnd; ++UI) {
8467 // Skip the uses of the chain.
8468 if (UI.getUse().getResNo() != 0)
8474 // Check if this is a trunc(lshr).
8475 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8476 isa<ConstantSDNode>(User->getOperand(1))) {
8477 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8478 User = *User->use_begin();
8481 // At this point, User is a Truncate, iff we encountered, trunc or
8483 if (User->getOpcode() != ISD::TRUNCATE)
8486 // The width of the type must be a power of 2 and greater than 8-bits.
8487 // Otherwise the load cannot be represented in LLVM IR.
8488 // Moreover, if we shifted with a non-8-bits multiple, the slice
8489 // will be across several bytes. We do not support that.
8490 unsigned Width = User->getValueSizeInBits(0);
8491 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8494 // Build the slice for this chain of computations.
8495 LoadedSlice LS(User, LD, Shift, &DAG);
8496 APInt CurrentUsedBits = LS.getUsedBits();
8498 // Check if this slice overlaps with another.
8499 if ((CurrentUsedBits & UsedBits) != 0)
8501 // Update the bits used globally.
8502 UsedBits |= CurrentUsedBits;
8504 // Check if the new slice would be legal.
8508 // Record the slice.
8509 LoadedSlices.push_back(LS);
8512 // Abort slicing if it does not seem to be profitable.
8513 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8518 // Rewrite each chain to use an independent load.
8519 // By construction, each chain can be represented by a unique load.
8521 // Prepare the argument for the new token factor for all the slices.
8522 SmallVector<SDValue, 8> ArgChains;
8523 for (SmallVectorImpl<LoadedSlice>::const_iterator
8524 LSIt = LoadedSlices.begin(),
8525 LSItEnd = LoadedSlices.end();
8526 LSIt != LSItEnd; ++LSIt) {
8527 SDValue SliceInst = LSIt->loadSlice();
8528 CombineTo(LSIt->Inst, SliceInst, true);
8529 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8530 SliceInst = SliceInst.getOperand(0);
8531 assert(SliceInst->getOpcode() == ISD::LOAD &&
8532 "It takes more than a zext to get to the loaded slice!!");
8533 ArgChains.push_back(SliceInst.getValue(1));
8536 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8537 &ArgChains[0], ArgChains.size());
8538 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8542 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8543 /// load is having specific bytes cleared out. If so, return the byte size
8544 /// being masked out and the shift amount.
8545 static std::pair<unsigned, unsigned>
8546 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8547 std::pair<unsigned, unsigned> Result(0, 0);
8549 // Check for the structure we're looking for.
8550 if (V->getOpcode() != ISD::AND ||
8551 !isa<ConstantSDNode>(V->getOperand(1)) ||
8552 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8555 // Check the chain and pointer.
8556 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8557 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8559 // The store should be chained directly to the load or be an operand of a
8561 if (LD == Chain.getNode())
8563 else if (Chain->getOpcode() != ISD::TokenFactor)
8564 return Result; // Fail.
8567 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8568 if (Chain->getOperand(i).getNode() == LD) {
8572 if (!isOk) return Result;
8575 // This only handles simple types.
8576 if (V.getValueType() != MVT::i16 &&
8577 V.getValueType() != MVT::i32 &&
8578 V.getValueType() != MVT::i64)
8581 // Check the constant mask. Invert it so that the bits being masked out are
8582 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8583 // follow the sign bit for uniformity.
8584 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8585 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8586 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8587 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8588 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8589 if (NotMaskLZ == 64) return Result; // All zero mask.
8591 // See if we have a continuous run of bits. If so, we have 0*1+0*
8592 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8595 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8596 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8597 NotMaskLZ -= 64-V.getValueSizeInBits();
8599 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8600 switch (MaskedBytes) {
8604 default: return Result; // All one mask, or 5-byte mask.
8607 // Verify that the first bit starts at a multiple of mask so that the access
8608 // is aligned the same as the access width.
8609 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8611 Result.first = MaskedBytes;
8612 Result.second = NotMaskTZ/8;
8617 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8618 /// provides a value as specified by MaskInfo. If so, replace the specified
8619 /// store with a narrower store of truncated IVal.
8621 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8622 SDValue IVal, StoreSDNode *St,
8624 unsigned NumBytes = MaskInfo.first;
8625 unsigned ByteShift = MaskInfo.second;
8626 SelectionDAG &DAG = DC->getDAG();
8628 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8629 // that uses this. If not, this is not a replacement.
8630 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8631 ByteShift*8, (ByteShift+NumBytes)*8);
8632 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8634 // Check that it is legal on the target to do this. It is legal if the new
8635 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8637 MVT VT = MVT::getIntegerVT(NumBytes*8);
8638 if (!DC->isTypeLegal(VT))
8641 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8642 // shifted by ByteShift and truncated down to NumBytes.
8644 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8645 DAG.getConstant(ByteShift*8,
8646 DC->getShiftAmountTy(IVal.getValueType())));
8648 // Figure out the offset for the store and the alignment of the access.
8650 unsigned NewAlign = St->getAlignment();
8652 if (DAG.getTargetLoweringInfo().isLittleEndian())
8653 StOffset = ByteShift;
8655 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8657 SDValue Ptr = St->getBasePtr();
8659 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8660 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8661 NewAlign = MinAlign(NewAlign, StOffset);
8664 // Truncate down to the new size.
8665 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8668 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8669 St->getPointerInfo().getWithOffset(StOffset),
8670 false, false, NewAlign).getNode();
8674 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8675 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8676 /// of the loaded bits, try narrowing the load and store if it would end up
8677 /// being a win for performance or code size.
8678 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8679 StoreSDNode *ST = cast<StoreSDNode>(N);
8680 if (ST->isVolatile())
8683 SDValue Chain = ST->getChain();
8684 SDValue Value = ST->getValue();
8685 SDValue Ptr = ST->getBasePtr();
8686 EVT VT = Value.getValueType();
8688 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8691 unsigned Opc = Value.getOpcode();
8693 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8694 // is a byte mask indicating a consecutive number of bytes, check to see if
8695 // Y is known to provide just those bytes. If so, we try to replace the
8696 // load + replace + store sequence with a single (narrower) store, which makes
8698 if (Opc == ISD::OR) {
8699 std::pair<unsigned, unsigned> MaskedLoad;
8700 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8701 if (MaskedLoad.first)
8702 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8703 Value.getOperand(1), ST,this))
8704 return SDValue(NewST, 0);
8706 // Or is commutative, so try swapping X and Y.
8707 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8708 if (MaskedLoad.first)
8709 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8710 Value.getOperand(0), ST,this))
8711 return SDValue(NewST, 0);
8714 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8715 Value.getOperand(1).getOpcode() != ISD::Constant)
8718 SDValue N0 = Value.getOperand(0);
8719 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8720 Chain == SDValue(N0.getNode(), 1)) {
8721 LoadSDNode *LD = cast<LoadSDNode>(N0);
8722 if (LD->getBasePtr() != Ptr ||
8723 LD->getPointerInfo().getAddrSpace() !=
8724 ST->getPointerInfo().getAddrSpace())
8727 // Find the type to narrow it the load / op / store to.
8728 SDValue N1 = Value.getOperand(1);
8729 unsigned BitWidth = N1.getValueSizeInBits();
8730 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8731 if (Opc == ISD::AND)
8732 Imm ^= APInt::getAllOnesValue(BitWidth);
8733 if (Imm == 0 || Imm.isAllOnesValue())
8735 unsigned ShAmt = Imm.countTrailingZeros();
8736 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8737 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8738 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8739 while (NewBW < BitWidth &&
8740 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8741 TLI.isNarrowingProfitable(VT, NewVT))) {
8742 NewBW = NextPowerOf2(NewBW);
8743 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8745 if (NewBW >= BitWidth)
8748 // If the lsb changed does not start at the type bitwidth boundary,
8749 // start at the previous one.
8751 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8752 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8753 std::min(BitWidth, ShAmt + NewBW));
8754 if ((Imm & Mask) == Imm) {
8755 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8756 if (Opc == ISD::AND)
8757 NewImm ^= APInt::getAllOnesValue(NewBW);
8758 uint64_t PtrOff = ShAmt / 8;
8759 // For big endian targets, we need to adjust the offset to the pointer to
8760 // load the correct bytes.
8761 if (TLI.isBigEndian())
8762 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8764 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8765 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8766 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8769 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8770 Ptr.getValueType(), Ptr,
8771 DAG.getConstant(PtrOff, Ptr.getValueType()));
8772 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8773 LD->getChain(), NewPtr,
8774 LD->getPointerInfo().getWithOffset(PtrOff),
8775 LD->isVolatile(), LD->isNonTemporal(),
8776 LD->isInvariant(), NewAlign,
8778 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8779 DAG.getConstant(NewImm, NewVT));
8780 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8782 ST->getPointerInfo().getWithOffset(PtrOff),
8783 false, false, NewAlign);
8785 AddToWorkList(NewPtr.getNode());
8786 AddToWorkList(NewLD.getNode());
8787 AddToWorkList(NewVal.getNode());
8788 WorkListRemover DeadNodes(*this);
8789 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8798 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8799 /// if the load value isn't used by any other operations, then consider
8800 /// transforming the pair to integer load / store operations if the target
8801 /// deems the transformation profitable.
8802 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8803 StoreSDNode *ST = cast<StoreSDNode>(N);
8804 SDValue Chain = ST->getChain();
8805 SDValue Value = ST->getValue();
8806 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8807 Value.hasOneUse() &&
8808 Chain == SDValue(Value.getNode(), 1)) {
8809 LoadSDNode *LD = cast<LoadSDNode>(Value);
8810 EVT VT = LD->getMemoryVT();
8811 if (!VT.isFloatingPoint() ||
8812 VT != ST->getMemoryVT() ||
8813 LD->isNonTemporal() ||
8814 ST->isNonTemporal() ||
8815 LD->getPointerInfo().getAddrSpace() != 0 ||
8816 ST->getPointerInfo().getAddrSpace() != 0)
8819 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8820 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8821 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8822 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8823 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8826 unsigned LDAlign = LD->getAlignment();
8827 unsigned STAlign = ST->getAlignment();
8828 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8829 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8830 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8833 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8834 LD->getChain(), LD->getBasePtr(),
8835 LD->getPointerInfo(),
8836 false, false, false, LDAlign);
8838 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8839 NewLD, ST->getBasePtr(),
8840 ST->getPointerInfo(),
8841 false, false, STAlign);
8843 AddToWorkList(NewLD.getNode());
8844 AddToWorkList(NewST.getNode());
8845 WorkListRemover DeadNodes(*this);
8846 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8854 /// Helper struct to parse and store a memory address as base + index + offset.
8855 /// We ignore sign extensions when it is safe to do so.
8856 /// The following two expressions are not equivalent. To differentiate we need
8857 /// to store whether there was a sign extension involved in the index
8859 /// (load (i64 add (i64 copyfromreg %c)
8860 /// (i64 signextend (add (i8 load %index)
8864 /// (load (i64 add (i64 copyfromreg %c)
8865 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8867 struct BaseIndexOffset {
8871 bool IsIndexSignExt;
8873 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8875 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8876 bool IsIndexSignExt) :
8877 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8879 bool equalBaseIndex(const BaseIndexOffset &Other) {
8880 return Other.Base == Base && Other.Index == Index &&
8881 Other.IsIndexSignExt == IsIndexSignExt;
8884 /// Parses tree in Ptr for base, index, offset addresses.
8885 static BaseIndexOffset match(SDValue Ptr) {
8886 bool IsIndexSignExt = false;
8888 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8889 // instruction, then it could be just the BASE or everything else we don't
8890 // know how to handle. Just use Ptr as BASE and give up.
8891 if (Ptr->getOpcode() != ISD::ADD)
8892 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8894 // We know that we have at least an ADD instruction. Try to pattern match
8895 // the simple case of BASE + OFFSET.
8896 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8897 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8898 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8902 // Inside a loop the current BASE pointer is calculated using an ADD and a
8903 // MUL instruction. In this case Ptr is the actual BASE pointer.
8904 // (i64 add (i64 %array_ptr)
8905 // (i64 mul (i64 %induction_var)
8906 // (i64 %element_size)))
8907 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8908 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8910 // Look at Base + Index + Offset cases.
8911 SDValue Base = Ptr->getOperand(0);
8912 SDValue IndexOffset = Ptr->getOperand(1);
8914 // Skip signextends.
8915 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8916 IndexOffset = IndexOffset->getOperand(0);
8917 IsIndexSignExt = true;
8920 // Either the case of Base + Index (no offset) or something else.
8921 if (IndexOffset->getOpcode() != ISD::ADD)
8922 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8924 // Now we have the case of Base + Index + offset.
8925 SDValue Index = IndexOffset->getOperand(0);
8926 SDValue Offset = IndexOffset->getOperand(1);
8928 if (!isa<ConstantSDNode>(Offset))
8929 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8931 // Ignore signextends.
8932 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8933 Index = Index->getOperand(0);
8934 IsIndexSignExt = true;
8935 } else IsIndexSignExt = false;
8937 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8938 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8942 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8943 /// is located in a sequence of memory operations connected by a chain.
8945 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8946 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8947 // Ptr to the mem node.
8948 LSBaseSDNode *MemNode;
8949 // Offset from the base ptr.
8950 int64_t OffsetFromBase;
8951 // What is the sequence number of this mem node.
8952 // Lowest mem operand in the DAG starts at zero.
8953 unsigned SequenceNum;
8956 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8957 EVT MemVT = St->getMemoryVT();
8958 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8959 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8960 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8962 // Don't merge vectors into wider inputs.
8963 if (MemVT.isVector() || !MemVT.isSimple())
8966 // Perform an early exit check. Do not bother looking at stored values that
8967 // are not constants or loads.
8968 SDValue StoredVal = St->getValue();
8969 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8970 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8974 // Only look at ends of store sequences.
8975 SDValue Chain = SDValue(St, 1);
8976 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8979 // This holds the base pointer, index, and the offset in bytes from the base
8981 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8983 // We must have a base and an offset.
8984 if (!BasePtr.Base.getNode())
8987 // Do not handle stores to undef base pointers.
8988 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8991 // Save the LoadSDNodes that we find in the chain.
8992 // We need to make sure that these nodes do not interfere with
8993 // any of the store nodes.
8994 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8996 // Save the StoreSDNodes that we find in the chain.
8997 SmallVector<MemOpLink, 8> StoreNodes;
8999 // Walk up the chain and look for nodes with offsets from the same
9000 // base pointer. Stop when reaching an instruction with a different kind
9001 // or instruction which has a different base pointer.
9003 StoreSDNode *Index = St;
9005 // If the chain has more than one use, then we can't reorder the mem ops.
9006 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9009 // Find the base pointer and offset for this memory node.
9010 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9012 // Check that the base pointer is the same as the original one.
9013 if (!Ptr.equalBaseIndex(BasePtr))
9016 // Check that the alignment is the same.
9017 if (Index->getAlignment() != St->getAlignment())
9020 // The memory operands must not be volatile.
9021 if (Index->isVolatile() || Index->isIndexed())
9025 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9026 if (St->isTruncatingStore())
9029 // The stored memory type must be the same.
9030 if (Index->getMemoryVT() != MemVT)
9033 // We do not allow unaligned stores because we want to prevent overriding
9035 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9038 // We found a potential memory operand to merge.
9039 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9041 // Find the next memory operand in the chain. If the next operand in the
9042 // chain is a store then move up and continue the scan with the next
9043 // memory operand. If the next operand is a load save it and use alias
9044 // information to check if it interferes with anything.
9045 SDNode *NextInChain = Index->getChain().getNode();
9047 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9048 // We found a store node. Use it for the next iteration.
9051 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9052 if (Ldn->isVolatile()) {
9057 // Save the load node for later. Continue the scan.
9058 AliasLoadNodes.push_back(Ldn);
9059 NextInChain = Ldn->getChain().getNode();
9068 // Check if there is anything to merge.
9069 if (StoreNodes.size() < 2)
9072 // Sort the memory operands according to their distance from the base pointer.
9073 std::sort(StoreNodes.begin(), StoreNodes.end(),
9074 [](MemOpLink LHS, MemOpLink RHS) {
9075 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9076 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9077 LHS.SequenceNum > RHS.SequenceNum);
9080 // Scan the memory operations on the chain and find the first non-consecutive
9081 // store memory address.
9082 unsigned LastConsecutiveStore = 0;
9083 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9084 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9086 // Check that the addresses are consecutive starting from the second
9087 // element in the list of stores.
9089 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9090 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9095 // Check if this store interferes with any of the loads that we found.
9096 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9097 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9101 // We found a load that alias with this store. Stop the sequence.
9105 // Mark this node as useful.
9106 LastConsecutiveStore = i;
9109 // The node with the lowest store address.
9110 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9112 // Store the constants into memory as one consecutive store.
9114 unsigned LastLegalType = 0;
9115 unsigned LastLegalVectorType = 0;
9116 bool NonZero = false;
9117 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9118 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9119 SDValue StoredVal = St->getValue();
9121 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9122 NonZero |= !C->isNullValue();
9123 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9124 NonZero |= !C->getConstantFPValue()->isNullValue();
9130 // Find a legal type for the constant store.
9131 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9132 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9133 if (TLI.isTypeLegal(StoreTy))
9134 LastLegalType = i+1;
9135 // Or check whether a truncstore is legal.
9136 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9137 TargetLowering::TypePromoteInteger) {
9138 EVT LegalizedStoredValueTy =
9139 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9140 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9141 LastLegalType = i+1;
9144 // Find a legal type for the vector store.
9145 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9146 if (TLI.isTypeLegal(Ty))
9147 LastLegalVectorType = i + 1;
9150 // We only use vectors if the constant is known to be zero and the
9151 // function is not marked with the noimplicitfloat attribute.
9152 if (NonZero || NoVectors)
9153 LastLegalVectorType = 0;
9155 // Check if we found a legal integer type to store.
9156 if (LastLegalType == 0 && LastLegalVectorType == 0)
9159 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9160 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9162 // Make sure we have something to merge.
9166 unsigned EarliestNodeUsed = 0;
9167 for (unsigned i=0; i < NumElem; ++i) {
9168 // Find a chain for the new wide-store operand. Notice that some
9169 // of the store nodes that we found may not be selected for inclusion
9170 // in the wide store. The chain we use needs to be the chain of the
9171 // earliest store node which is *used* and replaced by the wide store.
9172 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9173 EarliestNodeUsed = i;
9176 // The earliest Node in the DAG.
9177 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9178 SDLoc DL(StoreNodes[0].MemNode);
9182 // Find a legal type for the vector store.
9183 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9184 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9185 StoredVal = DAG.getConstant(0, Ty);
9187 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9188 APInt StoreInt(StoreBW, 0);
9190 // Construct a single integer constant which is made of the smaller
9192 bool IsLE = TLI.isLittleEndian();
9193 for (unsigned i = 0; i < NumElem ; ++i) {
9194 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9195 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9196 SDValue Val = St->getValue();
9197 StoreInt<<=ElementSizeBytes*8;
9198 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9199 StoreInt|=C->getAPIntValue().zext(StoreBW);
9200 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9201 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9203 assert(false && "Invalid constant element type");
9207 // Create the new Load and Store operations.
9208 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9209 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9212 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9213 FirstInChain->getBasePtr(),
9214 FirstInChain->getPointerInfo(),
9216 FirstInChain->getAlignment());
9218 // Replace the first store with the new store
9219 CombineTo(EarliestOp, NewStore);
9220 // Erase all other stores.
9221 for (unsigned i = 0; i < NumElem ; ++i) {
9222 if (StoreNodes[i].MemNode == EarliestOp)
9224 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9225 // ReplaceAllUsesWith will replace all uses that existed when it was
9226 // called, but graph optimizations may cause new ones to appear. For
9227 // example, the case in pr14333 looks like
9229 // St's chain -> St -> another store -> X
9231 // And the only difference from St to the other store is the chain.
9232 // When we change it's chain to be St's chain they become identical,
9233 // get CSEed and the net result is that X is now a use of St.
9234 // Since we know that St is redundant, just iterate.
9235 while (!St->use_empty())
9236 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9237 removeFromWorkList(St);
9244 // Below we handle the case of multiple consecutive stores that
9245 // come from multiple consecutive loads. We merge them into a single
9246 // wide load and a single wide store.
9248 // Look for load nodes which are used by the stored values.
9249 SmallVector<MemOpLink, 8> LoadNodes;
9251 // Find acceptable loads. Loads need to have the same chain (token factor),
9252 // must not be zext, volatile, indexed, and they must be consecutive.
9253 BaseIndexOffset LdBasePtr;
9254 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9255 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9256 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9259 // Loads must only have one use.
9260 if (!Ld->hasNUsesOfValue(1, 0))
9263 // Check that the alignment is the same as the stores.
9264 if (Ld->getAlignment() != St->getAlignment())
9267 // The memory operands must not be volatile.
9268 if (Ld->isVolatile() || Ld->isIndexed())
9271 // We do not accept ext loads.
9272 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9275 // The stored memory type must be the same.
9276 if (Ld->getMemoryVT() != MemVT)
9279 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9280 // If this is not the first ptr that we check.
9281 if (LdBasePtr.Base.getNode()) {
9282 // The base ptr must be the same.
9283 if (!LdPtr.equalBaseIndex(LdBasePtr))
9286 // Check that all other base pointers are the same as this one.
9290 // We found a potential memory operand to merge.
9291 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9294 if (LoadNodes.size() < 2)
9297 // Scan the memory operations on the chain and find the first non-consecutive
9298 // load memory address. These variables hold the index in the store node
9300 unsigned LastConsecutiveLoad = 0;
9301 // This variable refers to the size and not index in the array.
9302 unsigned LastLegalVectorType = 0;
9303 unsigned LastLegalIntegerType = 0;
9304 StartAddress = LoadNodes[0].OffsetFromBase;
9305 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9306 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9307 // All loads much share the same chain.
9308 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9311 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9312 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9314 LastConsecutiveLoad = i;
9316 // Find a legal type for the vector store.
9317 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9318 if (TLI.isTypeLegal(StoreTy))
9319 LastLegalVectorType = i + 1;
9321 // Find a legal type for the integer store.
9322 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9323 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9324 if (TLI.isTypeLegal(StoreTy))
9325 LastLegalIntegerType = i + 1;
9326 // Or check whether a truncstore and extload is legal.
9327 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9328 TargetLowering::TypePromoteInteger) {
9329 EVT LegalizedStoredValueTy =
9330 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9331 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9332 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9333 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9334 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9335 LastLegalIntegerType = i+1;
9339 // Only use vector types if the vector type is larger than the integer type.
9340 // If they are the same, use integers.
9341 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9342 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9344 // We add +1 here because the LastXXX variables refer to location while
9345 // the NumElem refers to array/index size.
9346 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9347 NumElem = std::min(LastLegalType, NumElem);
9352 // The earliest Node in the DAG.
9353 unsigned EarliestNodeUsed = 0;
9354 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9355 for (unsigned i=1; i<NumElem; ++i) {
9356 // Find a chain for the new wide-store operand. Notice that some
9357 // of the store nodes that we found may not be selected for inclusion
9358 // in the wide store. The chain we use needs to be the chain of the
9359 // earliest store node which is *used* and replaced by the wide store.
9360 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9361 EarliestNodeUsed = i;
9364 // Find if it is better to use vectors or integers to load and store
9368 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9370 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9371 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9374 SDLoc LoadDL(LoadNodes[0].MemNode);
9375 SDLoc StoreDL(StoreNodes[0].MemNode);
9377 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9378 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9379 FirstLoad->getChain(),
9380 FirstLoad->getBasePtr(),
9381 FirstLoad->getPointerInfo(),
9382 false, false, false,
9383 FirstLoad->getAlignment());
9385 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9386 FirstInChain->getBasePtr(),
9387 FirstInChain->getPointerInfo(), false, false,
9388 FirstInChain->getAlignment());
9390 // Replace one of the loads with the new load.
9391 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9392 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9393 SDValue(NewLoad.getNode(), 1));
9395 // Remove the rest of the load chains.
9396 for (unsigned i = 1; i < NumElem ; ++i) {
9397 // Replace all chain users of the old load nodes with the chain of the new
9399 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9400 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9403 // Replace the first store with the new store.
9404 CombineTo(EarliestOp, NewStore);
9405 // Erase all other stores.
9406 for (unsigned i = 0; i < NumElem ; ++i) {
9407 // Remove all Store nodes.
9408 if (StoreNodes[i].MemNode == EarliestOp)
9410 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9411 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9412 removeFromWorkList(St);
9419 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9420 StoreSDNode *ST = cast<StoreSDNode>(N);
9421 SDValue Chain = ST->getChain();
9422 SDValue Value = ST->getValue();
9423 SDValue Ptr = ST->getBasePtr();
9425 // If this is a store of a bit convert, store the input value if the
9426 // resultant store does not need a higher alignment than the original.
9427 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9428 ST->isUnindexed()) {
9429 unsigned OrigAlign = ST->getAlignment();
9430 EVT SVT = Value.getOperand(0).getValueType();
9431 unsigned Align = TLI.getDataLayout()->
9432 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9433 if (Align <= OrigAlign &&
9434 ((!LegalOperations && !ST->isVolatile()) ||
9435 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9436 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9437 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9438 ST->isNonTemporal(), OrigAlign,
9442 // Turn 'store undef, Ptr' -> nothing.
9443 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9446 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9447 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9448 // NOTE: If the original store is volatile, this transform must not increase
9449 // the number of stores. For example, on x86-32 an f64 can be stored in one
9450 // processor operation but an i64 (which is not legal) requires two. So the
9451 // transform should not be done in this case.
9452 if (Value.getOpcode() != ISD::TargetConstantFP) {
9454 switch (CFP->getSimpleValueType(0).SimpleTy) {
9455 default: llvm_unreachable("Unknown FP type");
9456 case MVT::f16: // We don't do this for these yet.
9462 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9463 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9464 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9465 bitcastToAPInt().getZExtValue(), MVT::i32);
9466 return DAG.getStore(Chain, SDLoc(N), Tmp,
9467 Ptr, ST->getMemOperand());
9471 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9472 !ST->isVolatile()) ||
9473 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9474 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9475 getZExtValue(), MVT::i64);
9476 return DAG.getStore(Chain, SDLoc(N), Tmp,
9477 Ptr, ST->getMemOperand());
9480 if (!ST->isVolatile() &&
9481 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9482 // Many FP stores are not made apparent until after legalize, e.g. for
9483 // argument passing. Since this is so common, custom legalize the
9484 // 64-bit integer store into two 32-bit stores.
9485 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9486 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9487 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9488 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9490 unsigned Alignment = ST->getAlignment();
9491 bool isVolatile = ST->isVolatile();
9492 bool isNonTemporal = ST->isNonTemporal();
9493 const MDNode *TBAAInfo = ST->getTBAAInfo();
9495 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9496 Ptr, ST->getPointerInfo(),
9497 isVolatile, isNonTemporal,
9498 ST->getAlignment(), TBAAInfo);
9499 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9500 DAG.getConstant(4, Ptr.getValueType()));
9501 Alignment = MinAlign(Alignment, 4U);
9502 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9503 Ptr, ST->getPointerInfo().getWithOffset(4),
9504 isVolatile, isNonTemporal,
9505 Alignment, TBAAInfo);
9506 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9515 // Try to infer better alignment information than the store already has.
9516 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9517 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9518 if (Align > ST->getAlignment())
9519 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9520 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9521 ST->isVolatile(), ST->isNonTemporal(), Align,
9526 // Try transforming a pair floating point load / store ops to integer
9527 // load / store ops.
9528 SDValue NewST = TransformFPLoadStorePair(N);
9529 if (NewST.getNode())
9532 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9533 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9535 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9536 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9539 if (UseAA && ST->isUnindexed()) {
9540 // Walk up chain skipping non-aliasing memory nodes.
9541 SDValue BetterChain = FindBetterChain(N, Chain);
9543 // If there is a better chain.
9544 if (Chain != BetterChain) {
9547 // Replace the chain to avoid dependency.
9548 if (ST->isTruncatingStore()) {
9549 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9550 ST->getMemoryVT(), ST->getMemOperand());
9552 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9553 ST->getMemOperand());
9556 // Create token to keep both nodes around.
9557 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9558 MVT::Other, Chain, ReplStore);
9560 // Make sure the new and old chains are cleaned up.
9561 AddToWorkList(Token.getNode());
9563 // Don't add users to work list.
9564 return CombineTo(N, Token, false);
9568 // Try transforming N to an indexed store.
9569 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9570 return SDValue(N, 0);
9572 // FIXME: is there such a thing as a truncating indexed store?
9573 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9574 Value.getValueType().isInteger()) {
9575 // See if we can simplify the input to this truncstore with knowledge that
9576 // only the low bits are being used. For example:
9577 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9579 GetDemandedBits(Value,
9580 APInt::getLowBitsSet(
9581 Value.getValueType().getScalarType().getSizeInBits(),
9582 ST->getMemoryVT().getScalarType().getSizeInBits()));
9583 AddToWorkList(Value.getNode());
9584 if (Shorter.getNode())
9585 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9586 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9588 // Otherwise, see if we can simplify the operation with
9589 // SimplifyDemandedBits, which only works if the value has a single use.
9590 if (SimplifyDemandedBits(Value,
9591 APInt::getLowBitsSet(
9592 Value.getValueType().getScalarType().getSizeInBits(),
9593 ST->getMemoryVT().getScalarType().getSizeInBits())))
9594 return SDValue(N, 0);
9597 // If this is a load followed by a store to the same location, then the store
9599 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9600 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9601 ST->isUnindexed() && !ST->isVolatile() &&
9602 // There can't be any side effects between the load and store, such as
9604 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9605 // The store is dead, remove it.
9610 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9611 // truncating store. We can do this even if this is already a truncstore.
9612 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9613 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9614 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9615 ST->getMemoryVT())) {
9616 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9617 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9620 // Only perform this optimization before the types are legal, because we
9621 // don't want to perform this optimization on every DAGCombine invocation.
9623 bool EverChanged = false;
9626 // There can be multiple store sequences on the same chain.
9627 // Keep trying to merge store sequences until we are unable to do so
9628 // or until we merge the last store on the chain.
9629 bool Changed = MergeConsecutiveStores(ST);
9630 EverChanged |= Changed;
9631 if (!Changed) break;
9632 } while (ST->getOpcode() != ISD::DELETED_NODE);
9635 return SDValue(N, 0);
9638 return ReduceLoadOpStoreWidth(N);
9641 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9642 SDValue InVec = N->getOperand(0);
9643 SDValue InVal = N->getOperand(1);
9644 SDValue EltNo = N->getOperand(2);
9647 // If the inserted element is an UNDEF, just use the input vector.
9648 if (InVal.getOpcode() == ISD::UNDEF)
9651 EVT VT = InVec.getValueType();
9653 // If we can't generate a legal BUILD_VECTOR, exit
9654 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9657 // Check that we know which element is being inserted
9658 if (!isa<ConstantSDNode>(EltNo))
9660 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9662 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9663 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9665 SmallVector<SDValue, 8> Ops;
9666 // Do not combine these two vectors if the output vector will not replace
9667 // the input vector.
9668 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9669 Ops.append(InVec.getNode()->op_begin(),
9670 InVec.getNode()->op_end());
9671 } else if (InVec.getOpcode() == ISD::UNDEF) {
9672 unsigned NElts = VT.getVectorNumElements();
9673 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9678 // Insert the element
9679 if (Elt < Ops.size()) {
9680 // All the operands of BUILD_VECTOR must have the same type;
9681 // we enforce that here.
9682 EVT OpVT = Ops[0].getValueType();
9683 if (InVal.getValueType() != OpVT)
9684 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9685 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9686 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9690 // Return the new vector
9691 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9692 VT, &Ops[0], Ops.size());
9695 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9696 // (vextract (scalar_to_vector val, 0) -> val
9697 SDValue InVec = N->getOperand(0);
9698 EVT VT = InVec.getValueType();
9699 EVT NVT = N->getValueType(0);
9701 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9702 // Check if the result type doesn't match the inserted element type. A
9703 // SCALAR_TO_VECTOR may truncate the inserted element and the
9704 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9705 SDValue InOp = InVec.getOperand(0);
9706 if (InOp.getValueType() != NVT) {
9707 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9708 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9713 SDValue EltNo = N->getOperand(1);
9714 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9716 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9717 // We only perform this optimization before the op legalization phase because
9718 // we may introduce new vector instructions which are not backed by TD
9719 // patterns. For example on AVX, extracting elements from a wide vector
9720 // without using extract_subvector. However, if we can find an underlying
9721 // scalar value, then we can always use that.
9722 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9724 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9725 int NumElem = VT.getVectorNumElements();
9726 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9727 // Find the new index to extract from.
9728 int OrigElt = SVOp->getMaskElt(Elt);
9730 // Extracting an undef index is undef.
9732 return DAG.getUNDEF(NVT);
9734 // Select the right vector half to extract from.
9736 if (OrigElt < NumElem) {
9737 SVInVec = InVec->getOperand(0);
9739 SVInVec = InVec->getOperand(1);
9743 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9744 SDValue InOp = SVInVec.getOperand(OrigElt);
9745 if (InOp.getValueType() != NVT) {
9746 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9747 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9753 // FIXME: We should handle recursing on other vector shuffles and
9754 // scalar_to_vector here as well.
9756 if (!LegalOperations) {
9757 EVT IndexTy = TLI.getVectorIdxTy();
9758 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9759 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9763 // Perform only after legalization to ensure build_vector / vector_shuffle
9764 // optimizations have already been done.
9765 if (!LegalOperations) return SDValue();
9767 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9768 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9769 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9772 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9773 bool NewLoad = false;
9774 bool BCNumEltsChanged = false;
9775 EVT ExtVT = VT.getVectorElementType();
9778 // If the result of load has to be truncated, then it's not necessarily
9780 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9783 if (InVec.getOpcode() == ISD::BITCAST) {
9784 // Don't duplicate a load with other uses.
9785 if (!InVec.hasOneUse())
9788 EVT BCVT = InVec.getOperand(0).getValueType();
9789 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9791 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9792 BCNumEltsChanged = true;
9793 InVec = InVec.getOperand(0);
9794 ExtVT = BCVT.getVectorElementType();
9798 LoadSDNode *LN0 = nullptr;
9799 const ShuffleVectorSDNode *SVN = nullptr;
9800 if (ISD::isNormalLoad(InVec.getNode())) {
9801 LN0 = cast<LoadSDNode>(InVec);
9802 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9803 InVec.getOperand(0).getValueType() == ExtVT &&
9804 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9805 // Don't duplicate a load with other uses.
9806 if (!InVec.hasOneUse())
9809 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9810 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9811 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9813 // (load $addr+1*size)
9815 // Don't duplicate a load with other uses.
9816 if (!InVec.hasOneUse())
9819 // If the bit convert changed the number of elements, it is unsafe
9820 // to examine the mask.
9821 if (BCNumEltsChanged)
9824 // Select the input vector, guarding against out of range extract vector.
9825 unsigned NumElems = VT.getVectorNumElements();
9826 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9827 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9829 if (InVec.getOpcode() == ISD::BITCAST) {
9830 // Don't duplicate a load with other uses.
9831 if (!InVec.hasOneUse())
9834 InVec = InVec.getOperand(0);
9836 if (ISD::isNormalLoad(InVec.getNode())) {
9837 LN0 = cast<LoadSDNode>(InVec);
9838 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9842 // Make sure we found a non-volatile load and the extractelement is
9844 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9847 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9849 return DAG.getUNDEF(LVT);
9851 unsigned Align = LN0->getAlignment();
9853 // Check the resultant load doesn't need a higher alignment than the
9857 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9859 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9865 SDValue NewPtr = LN0->getBasePtr();
9866 unsigned PtrOff = 0;
9869 PtrOff = LVT.getSizeInBits() * Elt / 8;
9870 EVT PtrType = NewPtr.getValueType();
9871 if (TLI.isBigEndian())
9872 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9873 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9874 DAG.getConstant(PtrOff, PtrType));
9877 // The replacement we need to do here is a little tricky: we need to
9878 // replace an extractelement of a load with a load.
9879 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9880 // Note that this replacement assumes that the extractvalue is the only
9881 // use of the load; that's okay because we don't want to perform this
9882 // transformation in other cases anyway.
9885 if (NVT.bitsGT(LVT)) {
9886 // If the result type of vextract is wider than the load, then issue an
9887 // extending load instead.
9888 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9889 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9890 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9891 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9892 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9893 Align, LN0->getTBAAInfo());
9894 Chain = Load.getValue(1);
9896 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9897 LN0->getPointerInfo().getWithOffset(PtrOff),
9898 LN0->isVolatile(), LN0->isNonTemporal(),
9899 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9900 Chain = Load.getValue(1);
9901 if (NVT.bitsLT(LVT))
9902 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9904 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9906 WorkListRemover DeadNodes(*this);
9907 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9908 SDValue To[] = { Load, Chain };
9909 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9910 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9911 // worklist explicitly as well.
9912 AddToWorkList(Load.getNode());
9913 AddUsersToWorkList(Load.getNode()); // Add users too
9914 // Make sure to revisit this node to clean it up; it will usually be dead.
9916 return SDValue(N, 0);
9922 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9923 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9924 // We perform this optimization post type-legalization because
9925 // the type-legalizer often scalarizes integer-promoted vectors.
9926 // Performing this optimization before may create bit-casts which
9927 // will be type-legalized to complex code sequences.
9928 // We perform this optimization only before the operation legalizer because we
9929 // may introduce illegal operations.
9930 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9933 unsigned NumInScalars = N->getNumOperands();
9935 EVT VT = N->getValueType(0);
9937 // Check to see if this is a BUILD_VECTOR of a bunch of values
9938 // which come from any_extend or zero_extend nodes. If so, we can create
9939 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9940 // optimizations. We do not handle sign-extend because we can't fill the sign
9942 EVT SourceType = MVT::Other;
9943 bool AllAnyExt = true;
9945 for (unsigned i = 0; i != NumInScalars; ++i) {
9946 SDValue In = N->getOperand(i);
9947 // Ignore undef inputs.
9948 if (In.getOpcode() == ISD::UNDEF) continue;
9950 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9951 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9953 // Abort if the element is not an extension.
9954 if (!ZeroExt && !AnyExt) {
9955 SourceType = MVT::Other;
9959 // The input is a ZeroExt or AnyExt. Check the original type.
9960 EVT InTy = In.getOperand(0).getValueType();
9962 // Check that all of the widened source types are the same.
9963 if (SourceType == MVT::Other)
9966 else if (InTy != SourceType) {
9967 // Multiple income types. Abort.
9968 SourceType = MVT::Other;
9972 // Check if all of the extends are ANY_EXTENDs.
9973 AllAnyExt &= AnyExt;
9976 // In order to have valid types, all of the inputs must be extended from the
9977 // same source type and all of the inputs must be any or zero extend.
9978 // Scalar sizes must be a power of two.
9979 EVT OutScalarTy = VT.getScalarType();
9980 bool ValidTypes = SourceType != MVT::Other &&
9981 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9982 isPowerOf2_32(SourceType.getSizeInBits());
9984 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9985 // turn into a single shuffle instruction.
9989 bool isLE = TLI.isLittleEndian();
9990 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9991 assert(ElemRatio > 1 && "Invalid element size ratio");
9992 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9993 DAG.getConstant(0, SourceType);
9995 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9996 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9998 // Populate the new build_vector
9999 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10000 SDValue Cast = N->getOperand(i);
10001 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10002 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10003 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10005 if (Cast.getOpcode() == ISD::UNDEF)
10006 In = DAG.getUNDEF(SourceType);
10008 In = Cast->getOperand(0);
10009 unsigned Index = isLE ? (i * ElemRatio) :
10010 (i * ElemRatio + (ElemRatio - 1));
10012 assert(Index < Ops.size() && "Invalid index");
10016 // The type of the new BUILD_VECTOR node.
10017 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10018 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10019 "Invalid vector size");
10020 // Check if the new vector type is legal.
10021 if (!isTypeLegal(VecVT)) return SDValue();
10023 // Make the new BUILD_VECTOR.
10024 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10026 // The new BUILD_VECTOR node has the potential to be further optimized.
10027 AddToWorkList(BV.getNode());
10028 // Bitcast to the desired type.
10029 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10032 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10033 EVT VT = N->getValueType(0);
10035 unsigned NumInScalars = N->getNumOperands();
10038 EVT SrcVT = MVT::Other;
10039 unsigned Opcode = ISD::DELETED_NODE;
10040 unsigned NumDefs = 0;
10042 for (unsigned i = 0; i != NumInScalars; ++i) {
10043 SDValue In = N->getOperand(i);
10044 unsigned Opc = In.getOpcode();
10046 if (Opc == ISD::UNDEF)
10049 // If all scalar values are floats and converted from integers.
10050 if (Opcode == ISD::DELETED_NODE &&
10051 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10058 EVT InVT = In.getOperand(0).getValueType();
10060 // If all scalar values are typed differently, bail out. It's chosen to
10061 // simplify BUILD_VECTOR of integer types.
10062 if (SrcVT == MVT::Other)
10069 // If the vector has just one element defined, it's not worth to fold it into
10070 // a vectorized one.
10074 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10075 && "Should only handle conversion from integer to float.");
10076 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10078 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10080 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10083 SmallVector<SDValue, 8> Opnds;
10084 for (unsigned i = 0; i != NumInScalars; ++i) {
10085 SDValue In = N->getOperand(i);
10087 if (In.getOpcode() == ISD::UNDEF)
10088 Opnds.push_back(DAG.getUNDEF(SrcVT));
10090 Opnds.push_back(In.getOperand(0));
10092 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10093 &Opnds[0], Opnds.size());
10094 AddToWorkList(BV.getNode());
10096 return DAG.getNode(Opcode, dl, VT, BV);
10099 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10100 unsigned NumInScalars = N->getNumOperands();
10102 EVT VT = N->getValueType(0);
10104 // A vector built entirely of undefs is undef.
10105 if (ISD::allOperandsUndef(N))
10106 return DAG.getUNDEF(VT);
10108 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10112 V = reduceBuildVecConvertToConvertBuildVec(N);
10116 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10117 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10118 // at most two distinct vectors, turn this into a shuffle node.
10120 // May only combine to shuffle after legalize if shuffle is legal.
10121 if (LegalOperations &&
10122 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10125 SDValue VecIn1, VecIn2;
10126 for (unsigned i = 0; i != NumInScalars; ++i) {
10127 // Ignore undef inputs.
10128 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10130 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10131 // constant index, bail out.
10132 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10133 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10134 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10138 // We allow up to two distinct input vectors.
10139 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10140 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10143 if (!VecIn1.getNode()) {
10144 VecIn1 = ExtractedFromVec;
10145 } else if (!VecIn2.getNode()) {
10146 VecIn2 = ExtractedFromVec;
10148 // Too many inputs.
10149 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10154 // If everything is good, we can make a shuffle operation.
10155 if (VecIn1.getNode()) {
10156 SmallVector<int, 8> Mask;
10157 for (unsigned i = 0; i != NumInScalars; ++i) {
10158 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10159 Mask.push_back(-1);
10163 // If extracting from the first vector, just use the index directly.
10164 SDValue Extract = N->getOperand(i);
10165 SDValue ExtVal = Extract.getOperand(1);
10166 if (Extract.getOperand(0) == VecIn1) {
10167 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10168 if (ExtIndex > VT.getVectorNumElements())
10171 Mask.push_back(ExtIndex);
10175 // Otherwise, use InIdx + VecSize
10176 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10177 Mask.push_back(Idx+NumInScalars);
10180 // We can't generate a shuffle node with mismatched input and output types.
10181 // Attempt to transform a single input vector to the correct type.
10182 if ((VT != VecIn1.getValueType())) {
10183 // We don't support shuffeling between TWO values of different types.
10184 if (VecIn2.getNode())
10187 // We only support widening of vectors which are half the size of the
10188 // output registers. For example XMM->YMM widening on X86 with AVX.
10189 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10192 // If the input vector type has a different base type to the output
10193 // vector type, bail out.
10194 if (VecIn1.getValueType().getVectorElementType() !=
10195 VT.getVectorElementType())
10198 // Widen the input vector by adding undef values.
10199 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10200 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10203 // If VecIn2 is unused then change it to undef.
10204 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10206 // Check that we were able to transform all incoming values to the same
10208 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10209 VecIn1.getValueType() != VT)
10212 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10213 if (!isTypeLegal(VT))
10216 // Return the new VECTOR_SHUFFLE node.
10220 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10226 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10227 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10228 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10229 // inputs come from at most two distinct vectors, turn this into a shuffle
10232 // If we only have one input vector, we don't need to do any concatenation.
10233 if (N->getNumOperands() == 1)
10234 return N->getOperand(0);
10236 // Check if all of the operands are undefs.
10237 EVT VT = N->getValueType(0);
10238 if (ISD::allOperandsUndef(N))
10239 return DAG.getUNDEF(VT);
10241 // Optimize concat_vectors where one of the vectors is undef.
10242 if (N->getNumOperands() == 2 &&
10243 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10244 SDValue In = N->getOperand(0);
10245 assert(In.getValueType().isVector() && "Must concat vectors");
10247 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10248 if (In->getOpcode() == ISD::BITCAST &&
10249 !In->getOperand(0)->getValueType(0).isVector()) {
10250 SDValue Scalar = In->getOperand(0);
10251 EVT SclTy = Scalar->getValueType(0);
10253 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10256 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10257 VT.getSizeInBits() / SclTy.getSizeInBits());
10258 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10261 SDLoc dl = SDLoc(N);
10262 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10263 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10267 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10268 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10269 if (N->getNumOperands() == 2 &&
10270 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10271 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10272 EVT VT = N->getValueType(0);
10273 SDValue N0 = N->getOperand(0);
10274 SDValue N1 = N->getOperand(1);
10275 SmallVector<SDValue, 8> Opnds;
10276 unsigned BuildVecNumElts = N0.getNumOperands();
10278 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10279 Opnds.push_back(N0.getOperand(i));
10280 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10281 Opnds.push_back(N1.getOperand(i));
10283 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10287 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10288 // nodes often generate nop CONCAT_VECTOR nodes.
10289 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10290 // place the incoming vectors at the exact same location.
10291 SDValue SingleSource = SDValue();
10292 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10294 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10295 SDValue Op = N->getOperand(i);
10297 if (Op.getOpcode() == ISD::UNDEF)
10300 // Check if this is the identity extract:
10301 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10304 // Find the single incoming vector for the extract_subvector.
10305 if (SingleSource.getNode()) {
10306 if (Op.getOperand(0) != SingleSource)
10309 SingleSource = Op.getOperand(0);
10311 // Check the source type is the same as the type of the result.
10312 // If not, this concat may extend the vector, so we can not
10313 // optimize it away.
10314 if (SingleSource.getValueType() != N->getValueType(0))
10318 unsigned IdentityIndex = i * PartNumElem;
10319 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10320 // The extract index must be constant.
10324 // Check that we are reading from the identity index.
10325 if (CS->getZExtValue() != IdentityIndex)
10329 if (SingleSource.getNode())
10330 return SingleSource;
10335 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10336 EVT NVT = N->getValueType(0);
10337 SDValue V = N->getOperand(0);
10339 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10341 // (extract_subvec (concat V1, V2, ...), i)
10344 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10346 if (V->getOperand(0).getValueType() != NVT)
10348 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10349 unsigned NumElems = NVT.getVectorNumElements();
10350 assert((Idx % NumElems) == 0 &&
10351 "IDX in concat is not a multiple of the result vector length.");
10352 return V->getOperand(Idx / NumElems);
10356 if (V->getOpcode() == ISD::BITCAST)
10357 V = V.getOperand(0);
10359 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10361 // Handle only simple case where vector being inserted and vector
10362 // being extracted are of same type, and are half size of larger vectors.
10363 EVT BigVT = V->getOperand(0).getValueType();
10364 EVT SmallVT = V->getOperand(1).getValueType();
10365 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10368 // Only handle cases where both indexes are constants with the same type.
10369 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10370 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10372 if (InsIdx && ExtIdx &&
10373 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10374 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10376 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10378 // indices are equal or bit offsets are equal => V1
10379 // otherwise => (extract_subvec V1, ExtIdx)
10380 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10381 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10382 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10383 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10384 DAG.getNode(ISD::BITCAST, dl,
10385 N->getOperand(0).getValueType(),
10386 V->getOperand(0)), N->getOperand(1));
10393 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10394 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10395 EVT VT = N->getValueType(0);
10396 unsigned NumElts = VT.getVectorNumElements();
10398 SDValue N0 = N->getOperand(0);
10399 SDValue N1 = N->getOperand(1);
10400 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10402 SmallVector<SDValue, 4> Ops;
10403 EVT ConcatVT = N0.getOperand(0).getValueType();
10404 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10405 unsigned NumConcats = NumElts / NumElemsPerConcat;
10407 // Look at every vector that's inserted. We're looking for exact
10408 // subvector-sized copies from a concatenated vector
10409 for (unsigned I = 0; I != NumConcats; ++I) {
10410 // Make sure we're dealing with a copy.
10411 unsigned Begin = I * NumElemsPerConcat;
10412 bool AllUndef = true, NoUndef = true;
10413 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10414 if (SVN->getMaskElt(J) >= 0)
10421 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10424 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10425 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10428 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10429 if (FirstElt < N0.getNumOperands())
10430 Ops.push_back(N0.getOperand(FirstElt));
10432 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10434 } else if (AllUndef) {
10435 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10436 } else { // Mixed with general masks and undefs, can't do optimization.
10441 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10445 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10446 EVT VT = N->getValueType(0);
10447 unsigned NumElts = VT.getVectorNumElements();
10449 SDValue N0 = N->getOperand(0);
10450 SDValue N1 = N->getOperand(1);
10452 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10454 // Canonicalize shuffle undef, undef -> undef
10455 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10456 return DAG.getUNDEF(VT);
10458 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10460 // Canonicalize shuffle v, v -> v, undef
10462 SmallVector<int, 8> NewMask;
10463 for (unsigned i = 0; i != NumElts; ++i) {
10464 int Idx = SVN->getMaskElt(i);
10465 if (Idx >= (int)NumElts) Idx -= NumElts;
10466 NewMask.push_back(Idx);
10468 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10472 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10473 if (N0.getOpcode() == ISD::UNDEF) {
10474 SmallVector<int, 8> NewMask;
10475 for (unsigned i = 0; i != NumElts; ++i) {
10476 int Idx = SVN->getMaskElt(i);
10478 if (Idx >= (int)NumElts)
10481 Idx = -1; // remove reference to lhs
10483 NewMask.push_back(Idx);
10485 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10489 // Remove references to rhs if it is undef
10490 if (N1.getOpcode() == ISD::UNDEF) {
10491 bool Changed = false;
10492 SmallVector<int, 8> NewMask;
10493 for (unsigned i = 0; i != NumElts; ++i) {
10494 int Idx = SVN->getMaskElt(i);
10495 if (Idx >= (int)NumElts) {
10499 NewMask.push_back(Idx);
10502 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10505 // If it is a splat, check if the argument vector is another splat or a
10506 // build_vector with all scalar elements the same.
10507 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10508 SDNode *V = N0.getNode();
10510 // If this is a bit convert that changes the element type of the vector but
10511 // not the number of vector elements, look through it. Be careful not to
10512 // look though conversions that change things like v4f32 to v2f64.
10513 if (V->getOpcode() == ISD::BITCAST) {
10514 SDValue ConvInput = V->getOperand(0);
10515 if (ConvInput.getValueType().isVector() &&
10516 ConvInput.getValueType().getVectorNumElements() == NumElts)
10517 V = ConvInput.getNode();
10520 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10521 assert(V->getNumOperands() == NumElts &&
10522 "BUILD_VECTOR has wrong number of operands");
10524 bool AllSame = true;
10525 for (unsigned i = 0; i != NumElts; ++i) {
10526 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10527 Base = V->getOperand(i);
10531 // Splat of <u, u, u, u>, return <u, u, u, u>
10532 if (!Base.getNode())
10534 for (unsigned i = 0; i != NumElts; ++i) {
10535 if (V->getOperand(i) != Base) {
10540 // Splat of <x, x, x, x>, return <x, x, x, x>
10546 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10547 Level < AfterLegalizeVectorOps &&
10548 (N1.getOpcode() == ISD::UNDEF ||
10549 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10550 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10551 SDValue V = partitionShuffleOfConcats(N, DAG);
10557 // If this shuffle node is simply a swizzle of another shuffle node,
10558 // and it reverses the swizzle of the previous shuffle then we can
10559 // optimize shuffle(shuffle(x, undef), undef) -> x.
10560 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10561 N1.getOpcode() == ISD::UNDEF) {
10563 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10565 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10566 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10569 // The incoming shuffle must be of the same type as the result of the
10570 // current shuffle.
10571 assert(OtherSV->getOperand(0).getValueType() == VT &&
10572 "Shuffle types don't match");
10574 for (unsigned i = 0; i != NumElts; ++i) {
10575 int Idx = SVN->getMaskElt(i);
10576 assert(Idx < (int)NumElts && "Index references undef operand");
10577 // Next, this index comes from the first value, which is the incoming
10578 // shuffle. Adopt the incoming index.
10580 Idx = OtherSV->getMaskElt(Idx);
10582 // The combined shuffle must map each index to itself.
10583 if (Idx >= 0 && (unsigned)Idx != i)
10587 return OtherSV->getOperand(0);
10593 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10594 SDValue N0 = N->getOperand(0);
10595 SDValue N2 = N->getOperand(2);
10597 // If the input vector is a concatenation, and the insert replaces
10598 // one of the halves, we can optimize into a single concat_vectors.
10599 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10600 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10601 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10602 EVT VT = N->getValueType(0);
10604 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10605 // (concat_vectors Z, Y)
10607 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10608 N->getOperand(1), N0.getOperand(1));
10610 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10611 // (concat_vectors X, Z)
10612 if (InsIdx == VT.getVectorNumElements()/2)
10613 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10614 N0.getOperand(0), N->getOperand(1));
10620 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10621 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10622 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10623 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10624 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10625 EVT VT = N->getValueType(0);
10627 SDValue LHS = N->getOperand(0);
10628 SDValue RHS = N->getOperand(1);
10629 if (N->getOpcode() == ISD::AND) {
10630 if (RHS.getOpcode() == ISD::BITCAST)
10631 RHS = RHS.getOperand(0);
10632 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10633 SmallVector<int, 8> Indices;
10634 unsigned NumElts = RHS.getNumOperands();
10635 for (unsigned i = 0; i != NumElts; ++i) {
10636 SDValue Elt = RHS.getOperand(i);
10637 if (!isa<ConstantSDNode>(Elt))
10640 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10641 Indices.push_back(i);
10642 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10643 Indices.push_back(NumElts);
10648 // Let's see if the target supports this vector_shuffle.
10649 EVT RVT = RHS.getValueType();
10650 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10653 // Return the new VECTOR_SHUFFLE node.
10654 EVT EltVT = RVT.getVectorElementType();
10655 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10656 DAG.getConstant(0, EltVT));
10657 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10658 RVT, &ZeroOps[0], ZeroOps.size());
10659 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10660 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10661 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10668 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10669 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10670 assert(N->getValueType(0).isVector() &&
10671 "SimplifyVBinOp only works on vectors!");
10673 SDValue LHS = N->getOperand(0);
10674 SDValue RHS = N->getOperand(1);
10675 SDValue Shuffle = XformToShuffleWithZero(N);
10676 if (Shuffle.getNode()) return Shuffle;
10678 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10680 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10681 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10682 // Check if both vectors are constants. If not bail out.
10683 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10684 cast<BuildVectorSDNode>(RHS)->isConstant()))
10687 SmallVector<SDValue, 8> Ops;
10688 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10689 SDValue LHSOp = LHS.getOperand(i);
10690 SDValue RHSOp = RHS.getOperand(i);
10692 // Can't fold divide by zero.
10693 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10694 N->getOpcode() == ISD::FDIV) {
10695 if ((RHSOp.getOpcode() == ISD::Constant &&
10696 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10697 (RHSOp.getOpcode() == ISD::ConstantFP &&
10698 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10702 EVT VT = LHSOp.getValueType();
10703 EVT RVT = RHSOp.getValueType();
10705 // Integer BUILD_VECTOR operands may have types larger than the element
10706 // size (e.g., when the element type is not legal). Prior to type
10707 // legalization, the types may not match between the two BUILD_VECTORS.
10708 // Truncate one of the operands to make them match.
10709 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10710 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10712 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10716 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10718 if (FoldOp.getOpcode() != ISD::UNDEF &&
10719 FoldOp.getOpcode() != ISD::Constant &&
10720 FoldOp.getOpcode() != ISD::ConstantFP)
10722 Ops.push_back(FoldOp);
10723 AddToWorkList(FoldOp.getNode());
10726 if (Ops.size() == LHS.getNumOperands())
10727 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10728 LHS.getValueType(), &Ops[0], Ops.size());
10734 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10735 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10736 assert(N->getValueType(0).isVector() &&
10737 "SimplifyVUnaryOp only works on vectors!");
10739 SDValue N0 = N->getOperand(0);
10741 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10744 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10745 SmallVector<SDValue, 8> Ops;
10746 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10747 SDValue Op = N0.getOperand(i);
10748 if (Op.getOpcode() != ISD::UNDEF &&
10749 Op.getOpcode() != ISD::ConstantFP)
10751 EVT EltVT = Op.getValueType();
10752 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10753 if (FoldOp.getOpcode() != ISD::UNDEF &&
10754 FoldOp.getOpcode() != ISD::ConstantFP)
10756 Ops.push_back(FoldOp);
10757 AddToWorkList(FoldOp.getNode());
10760 if (Ops.size() != N0.getNumOperands())
10763 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10764 N0.getValueType(), &Ops[0], Ops.size());
10767 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10768 SDValue N1, SDValue N2){
10769 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10771 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10772 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10774 // If we got a simplified select_cc node back from SimplifySelectCC, then
10775 // break it down into a new SETCC node, and a new SELECT node, and then return
10776 // the SELECT node, since we were called with a SELECT node.
10777 if (SCC.getNode()) {
10778 // Check to see if we got a select_cc back (to turn into setcc/select).
10779 // Otherwise, just return whatever node we got back, like fabs.
10780 if (SCC.getOpcode() == ISD::SELECT_CC) {
10781 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10783 SCC.getOperand(0), SCC.getOperand(1),
10784 SCC.getOperand(4));
10785 AddToWorkList(SETCC.getNode());
10786 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10787 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10795 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10796 /// are the two values being selected between, see if we can simplify the
10797 /// select. Callers of this should assume that TheSelect is deleted if this
10798 /// returns true. As such, they should return the appropriate thing (e.g. the
10799 /// node) back to the top-level of the DAG combiner loop to avoid it being
10801 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10804 // Cannot simplify select with vector condition
10805 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10807 // If this is a select from two identical things, try to pull the operation
10808 // through the select.
10809 if (LHS.getOpcode() != RHS.getOpcode() ||
10810 !LHS.hasOneUse() || !RHS.hasOneUse())
10813 // If this is a load and the token chain is identical, replace the select
10814 // of two loads with a load through a select of the address to load from.
10815 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10816 // constants have been dropped into the constant pool.
10817 if (LHS.getOpcode() == ISD::LOAD) {
10818 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10819 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10821 // Token chains must be identical.
10822 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10823 // Do not let this transformation reduce the number of volatile loads.
10824 LLD->isVolatile() || RLD->isVolatile() ||
10825 // If this is an EXTLOAD, the VT's must match.
10826 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10827 // If this is an EXTLOAD, the kind of extension must match.
10828 (LLD->getExtensionType() != RLD->getExtensionType() &&
10829 // The only exception is if one of the extensions is anyext.
10830 LLD->getExtensionType() != ISD::EXTLOAD &&
10831 RLD->getExtensionType() != ISD::EXTLOAD) ||
10832 // FIXME: this discards src value information. This is
10833 // over-conservative. It would be beneficial to be able to remember
10834 // both potential memory locations. Since we are discarding
10835 // src value info, don't do the transformation if the memory
10836 // locations are not in the default address space.
10837 LLD->getPointerInfo().getAddrSpace() != 0 ||
10838 RLD->getPointerInfo().getAddrSpace() != 0 ||
10839 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10840 LLD->getBasePtr().getValueType()))
10843 // Check that the select condition doesn't reach either load. If so,
10844 // folding this will induce a cycle into the DAG. If not, this is safe to
10845 // xform, so create a select of the addresses.
10847 if (TheSelect->getOpcode() == ISD::SELECT) {
10848 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10849 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10850 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10852 // The loads must not depend on one another.
10853 if (LLD->isPredecessorOf(RLD) ||
10854 RLD->isPredecessorOf(LLD))
10856 Addr = DAG.getSelect(SDLoc(TheSelect),
10857 LLD->getBasePtr().getValueType(),
10858 TheSelect->getOperand(0), LLD->getBasePtr(),
10859 RLD->getBasePtr());
10860 } else { // Otherwise SELECT_CC
10861 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10862 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10864 if ((LLD->hasAnyUseOfValue(1) &&
10865 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10866 (RLD->hasAnyUseOfValue(1) &&
10867 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10870 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10871 LLD->getBasePtr().getValueType(),
10872 TheSelect->getOperand(0),
10873 TheSelect->getOperand(1),
10874 LLD->getBasePtr(), RLD->getBasePtr(),
10875 TheSelect->getOperand(4));
10879 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10880 Load = DAG.getLoad(TheSelect->getValueType(0),
10882 // FIXME: Discards pointer and TBAA info.
10883 LLD->getChain(), Addr, MachinePointerInfo(),
10884 LLD->isVolatile(), LLD->isNonTemporal(),
10885 LLD->isInvariant(), LLD->getAlignment());
10887 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10888 RLD->getExtensionType() : LLD->getExtensionType(),
10890 TheSelect->getValueType(0),
10891 // FIXME: Discards pointer and TBAA info.
10892 LLD->getChain(), Addr, MachinePointerInfo(),
10893 LLD->getMemoryVT(), LLD->isVolatile(),
10894 LLD->isNonTemporal(), LLD->getAlignment());
10897 // Users of the select now use the result of the load.
10898 CombineTo(TheSelect, Load);
10900 // Users of the old loads now use the new load's chain. We know the
10901 // old-load value is dead now.
10902 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10903 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10910 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10911 /// where 'cond' is the comparison specified by CC.
10912 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10913 SDValue N2, SDValue N3,
10914 ISD::CondCode CC, bool NotExtCompare) {
10915 // (x ? y : y) -> y.
10916 if (N2 == N3) return N2;
10918 EVT VT = N2.getValueType();
10919 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10920 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10921 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10923 // Determine if the condition we're dealing with is constant
10924 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10925 N0, N1, CC, DL, false);
10926 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10927 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10929 // fold select_cc true, x, y -> x
10930 if (SCCC && !SCCC->isNullValue())
10932 // fold select_cc false, x, y -> y
10933 if (SCCC && SCCC->isNullValue())
10936 // Check to see if we can simplify the select into an fabs node
10937 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10938 // Allow either -0.0 or 0.0
10939 if (CFP->getValueAPF().isZero()) {
10940 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10941 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10942 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10943 N2 == N3.getOperand(0))
10944 return DAG.getNode(ISD::FABS, DL, VT, N0);
10946 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10947 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10948 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10949 N2.getOperand(0) == N3)
10950 return DAG.getNode(ISD::FABS, DL, VT, N3);
10954 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10955 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10956 // in it. This is a win when the constant is not otherwise available because
10957 // it replaces two constant pool loads with one. We only do this if the FP
10958 // type is known to be legal, because if it isn't, then we are before legalize
10959 // types an we want the other legalization to happen first (e.g. to avoid
10960 // messing with soft float) and if the ConstantFP is not legal, because if
10961 // it is legal, we may not need to store the FP constant in a constant pool.
10962 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10963 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10964 if (TLI.isTypeLegal(N2.getValueType()) &&
10965 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10966 TargetLowering::Legal) &&
10967 // If both constants have multiple uses, then we won't need to do an
10968 // extra load, they are likely around in registers for other users.
10969 (TV->hasOneUse() || FV->hasOneUse())) {
10970 Constant *Elts[] = {
10971 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10972 const_cast<ConstantFP*>(TV->getConstantFPValue())
10974 Type *FPTy = Elts[0]->getType();
10975 const DataLayout &TD = *TLI.getDataLayout();
10977 // Create a ConstantArray of the two constants.
10978 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10979 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10980 TD.getPrefTypeAlignment(FPTy));
10981 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10983 // Get the offsets to the 0 and 1 element of the array so that we can
10984 // select between them.
10985 SDValue Zero = DAG.getIntPtrConstant(0);
10986 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10987 SDValue One = DAG.getIntPtrConstant(EltSize);
10989 SDValue Cond = DAG.getSetCC(DL,
10990 getSetCCResultType(N0.getValueType()),
10992 AddToWorkList(Cond.getNode());
10993 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10995 AddToWorkList(CstOffset.getNode());
10996 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10998 AddToWorkList(CPIdx.getNode());
10999 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11000 MachinePointerInfo::getConstantPool(), false,
11001 false, false, Alignment);
11006 // Check to see if we can perform the "gzip trick", transforming
11007 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11008 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11009 (N1C->isNullValue() || // (a < 0) ? b : 0
11010 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11011 EVT XType = N0.getValueType();
11012 EVT AType = N2.getValueType();
11013 if (XType.bitsGE(AType)) {
11014 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11015 // single-bit constant.
11016 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11017 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11018 ShCtV = XType.getSizeInBits()-ShCtV-1;
11019 SDValue ShCt = DAG.getConstant(ShCtV,
11020 getShiftAmountTy(N0.getValueType()));
11021 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11023 AddToWorkList(Shift.getNode());
11025 if (XType.bitsGT(AType)) {
11026 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11027 AddToWorkList(Shift.getNode());
11030 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11033 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11035 DAG.getConstant(XType.getSizeInBits()-1,
11036 getShiftAmountTy(N0.getValueType())));
11037 AddToWorkList(Shift.getNode());
11039 if (XType.bitsGT(AType)) {
11040 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11041 AddToWorkList(Shift.getNode());
11044 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11048 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11049 // where y is has a single bit set.
11050 // A plaintext description would be, we can turn the SELECT_CC into an AND
11051 // when the condition can be materialized as an all-ones register. Any
11052 // single bit-test can be materialized as an all-ones register with
11053 // shift-left and shift-right-arith.
11054 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11055 N0->getValueType(0) == VT &&
11056 N1C && N1C->isNullValue() &&
11057 N2C && N2C->isNullValue()) {
11058 SDValue AndLHS = N0->getOperand(0);
11059 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11060 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11061 // Shift the tested bit over the sign bit.
11062 APInt AndMask = ConstAndRHS->getAPIntValue();
11064 DAG.getConstant(AndMask.countLeadingZeros(),
11065 getShiftAmountTy(AndLHS.getValueType()));
11066 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11068 // Now arithmetic right shift it all the way over, so the result is either
11069 // all-ones, or zero.
11071 DAG.getConstant(AndMask.getBitWidth()-1,
11072 getShiftAmountTy(Shl.getValueType()));
11073 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11075 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11079 // fold select C, 16, 0 -> shl C, 4
11080 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11081 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11082 TargetLowering::ZeroOrOneBooleanContent) {
11084 // If the caller doesn't want us to simplify this into a zext of a compare,
11086 if (NotExtCompare && N2C->getAPIntValue() == 1)
11089 // Get a SetCC of the condition
11090 // NOTE: Don't create a SETCC if it's not legal on this target.
11091 if (!LegalOperations ||
11092 TLI.isOperationLegal(ISD::SETCC,
11093 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11095 // cast from setcc result type to select result type
11097 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11099 if (N2.getValueType().bitsLT(SCC.getValueType()))
11100 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11101 N2.getValueType());
11103 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11104 N2.getValueType(), SCC);
11106 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11107 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11108 N2.getValueType(), SCC);
11111 AddToWorkList(SCC.getNode());
11112 AddToWorkList(Temp.getNode());
11114 if (N2C->getAPIntValue() == 1)
11117 // shl setcc result by log2 n2c
11118 return DAG.getNode(
11119 ISD::SHL, DL, N2.getValueType(), Temp,
11120 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11121 getShiftAmountTy(Temp.getValueType())));
11125 // Check to see if this is the equivalent of setcc
11126 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11127 // otherwise, go ahead with the folds.
11128 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11129 EVT XType = N0.getValueType();
11130 if (!LegalOperations ||
11131 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11132 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11133 if (Res.getValueType() != VT)
11134 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11138 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11139 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11140 (!LegalOperations ||
11141 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11142 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11143 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11144 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11145 getShiftAmountTy(Ctlz.getValueType())));
11147 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11148 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11149 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11150 XType, DAG.getConstant(0, XType), N0);
11151 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11152 return DAG.getNode(ISD::SRL, DL, XType,
11153 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11154 DAG.getConstant(XType.getSizeInBits()-1,
11155 getShiftAmountTy(XType)));
11157 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11158 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11159 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11160 DAG.getConstant(XType.getSizeInBits()-1,
11161 getShiftAmountTy(N0.getValueType())));
11162 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11166 // Check to see if this is an integer abs.
11167 // select_cc setg[te] X, 0, X, -X ->
11168 // select_cc setgt X, -1, X, -X ->
11169 // select_cc setl[te] X, 0, -X, X ->
11170 // select_cc setlt X, 1, -X, X ->
11171 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11173 ConstantSDNode *SubC = nullptr;
11174 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11175 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11176 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11177 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11178 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11179 (N1C->isOne() && CC == ISD::SETLT)) &&
11180 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11181 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11183 EVT XType = N0.getValueType();
11184 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11185 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11187 DAG.getConstant(XType.getSizeInBits()-1,
11188 getShiftAmountTy(N0.getValueType())));
11189 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11191 AddToWorkList(Shift.getNode());
11192 AddToWorkList(Add.getNode());
11193 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11200 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11201 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11202 SDValue N1, ISD::CondCode Cond,
11203 SDLoc DL, bool foldBooleans) {
11204 TargetLowering::DAGCombinerInfo
11205 DagCombineInfo(DAG, Level, false, this);
11206 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11209 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11210 /// return a DAG expression to select that will generate the same value by
11211 /// multiplying by a magic number. See:
11212 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11213 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11214 std::vector<SDNode*> Built;
11215 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11217 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11219 AddToWorkList(*ii);
11223 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11224 /// return a DAG expression to select that will generate the same value by
11225 /// multiplying by a magic number. See:
11226 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11227 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11228 std::vector<SDNode*> Built;
11229 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11231 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11233 AddToWorkList(*ii);
11237 /// FindBaseOffset - Return true if base is a frame index, which is known not
11238 // to alias with anything but itself. Provides base object and offset as
11240 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11241 const GlobalValue *&GV, const void *&CV) {
11242 // Assume it is a primitive operation.
11243 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11245 // If it's an adding a simple constant then integrate the offset.
11246 if (Base.getOpcode() == ISD::ADD) {
11247 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11248 Base = Base.getOperand(0);
11249 Offset += C->getZExtValue();
11253 // Return the underlying GlobalValue, and update the Offset. Return false
11254 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11255 // by multiple nodes with different offsets.
11256 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11257 GV = G->getGlobal();
11258 Offset += G->getOffset();
11262 // Return the underlying Constant value, and update the Offset. Return false
11263 // for ConstantSDNodes since the same constant pool entry may be represented
11264 // by multiple nodes with different offsets.
11265 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11266 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11267 : (const void *)C->getConstVal();
11268 Offset += C->getOffset();
11271 // If it's any of the following then it can't alias with anything but itself.
11272 return isa<FrameIndexSDNode>(Base);
11275 /// isAlias - Return true if there is any possibility that the two addresses
11277 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11278 // If they are the same then they must be aliases.
11279 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11281 // If they are both volatile then they cannot be reordered.
11282 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11284 // Gather base node and offset information.
11285 SDValue Base1, Base2;
11286 int64_t Offset1, Offset2;
11287 const GlobalValue *GV1, *GV2;
11288 const void *CV1, *CV2;
11289 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11290 Base1, Offset1, GV1, CV1);
11291 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11292 Base2, Offset2, GV2, CV2);
11294 // If they have a same base address then check to see if they overlap.
11295 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11296 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11297 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11299 // It is possible for different frame indices to alias each other, mostly
11300 // when tail call optimization reuses return address slots for arguments.
11301 // To catch this case, look up the actual index of frame indices to compute
11302 // the real alias relationship.
11303 if (isFrameIndex1 && isFrameIndex2) {
11304 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11305 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11306 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11307 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11308 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11311 // Otherwise, if we know what the bases are, and they aren't identical, then
11312 // we know they cannot alias.
11313 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11316 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11317 // compared to the size and offset of the access, we may be able to prove they
11318 // do not alias. This check is conservative for now to catch cases created by
11319 // splitting vector types.
11320 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11321 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11322 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11323 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11324 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11325 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11326 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11328 // There is no overlap between these relatively aligned accesses of similar
11329 // size, return no alias.
11330 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11331 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11335 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11336 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11338 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11339 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11343 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11344 // Use alias analysis information.
11345 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11346 Op1->getSrcValueOffset());
11347 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11348 Op0->getSrcValueOffset() - MinOffset;
11349 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11350 Op1->getSrcValueOffset() - MinOffset;
11351 AliasAnalysis::AliasResult AAResult =
11352 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11354 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11355 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11357 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11358 if (AAResult == AliasAnalysis::NoAlias)
11362 // Otherwise we have to assume they alias.
11366 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11367 /// looking for aliasing nodes and adding them to the Aliases vector.
11368 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11369 SmallVectorImpl<SDValue> &Aliases) {
11370 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11371 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11373 // Get alias information for node.
11374 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11377 Chains.push_back(OriginalChain);
11378 unsigned Depth = 0;
11380 // Look at each chain and determine if it is an alias. If so, add it to the
11381 // aliases list. If not, then continue up the chain looking for the next
11383 while (!Chains.empty()) {
11384 SDValue Chain = Chains.back();
11387 // For TokenFactor nodes, look at each operand and only continue up the
11388 // chain until we find two aliases. If we've seen two aliases, assume we'll
11389 // find more and revert to original chain since the xform is unlikely to be
11392 // FIXME: The depth check could be made to return the last non-aliasing
11393 // chain we found before we hit a tokenfactor rather than the original
11395 if (Depth > 6 || Aliases.size() == 2) {
11397 Aliases.push_back(OriginalChain);
11401 // Don't bother if we've been before.
11402 if (!Visited.insert(Chain.getNode()))
11405 switch (Chain.getOpcode()) {
11406 case ISD::EntryToken:
11407 // Entry token is ideal chain operand, but handled in FindBetterChain.
11412 // Get alias information for Chain.
11413 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11414 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11416 // If chain is alias then stop here.
11417 if (!(IsLoad && IsOpLoad) &&
11418 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11419 Aliases.push_back(Chain);
11421 // Look further up the chain.
11422 Chains.push_back(Chain.getOperand(0));
11428 case ISD::TokenFactor:
11429 // We have to check each of the operands of the token factor for "small"
11430 // token factors, so we queue them up. Adding the operands to the queue
11431 // (stack) in reverse order maintains the original order and increases the
11432 // likelihood that getNode will find a matching token factor (CSE.)
11433 if (Chain.getNumOperands() > 16) {
11434 Aliases.push_back(Chain);
11437 for (unsigned n = Chain.getNumOperands(); n;)
11438 Chains.push_back(Chain.getOperand(--n));
11443 // For all other instructions we will just have to take what we can get.
11444 Aliases.push_back(Chain);
11449 // We need to be careful here to also search for aliases through the
11450 // value operand of a store, etc. Consider the following situation:
11452 // L1 = load Token1, %52
11453 // S1 = store Token1, L1, %51
11454 // L2 = load Token1, %52+8
11455 // S2 = store Token1, L2, %51+8
11456 // Token2 = Token(S1, S2)
11457 // L3 = load Token2, %53
11458 // S3 = store Token2, L3, %52
11459 // L4 = load Token2, %53+8
11460 // S4 = store Token2, L4, %52+8
11461 // If we search for aliases of S3 (which loads address %52), and we look
11462 // only through the chain, then we'll miss the trivial dependence on L1
11463 // (which also loads from %52). We then might change all loads and
11464 // stores to use Token1 as their chain operand, which could result in
11465 // copying %53 into %52 before copying %52 into %51 (which should
11468 // The problem is, however, that searching for such data dependencies
11469 // can become expensive, and the cost is not directly related to the
11470 // chain depth. Instead, we'll rule out such configurations here by
11471 // insisting that we've visited all chain users (except for users
11472 // of the original chain, which is not necessary). When doing this,
11473 // we need to look through nodes we don't care about (otherwise, things
11474 // like register copies will interfere with trivial cases).
11476 SmallVector<const SDNode *, 16> Worklist;
11477 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11478 IE = Visited.end(); I != IE; ++I)
11479 if (*I != OriginalChain.getNode())
11480 Worklist.push_back(*I);
11482 while (!Worklist.empty()) {
11483 const SDNode *M = Worklist.pop_back_val();
11485 // We have already visited M, and want to make sure we've visited any uses
11486 // of M that we care about. For uses that we've not visisted, and don't
11487 // care about, queue them to the worklist.
11489 for (SDNode::use_iterator UI = M->use_begin(),
11490 UIE = M->use_end(); UI != UIE; ++UI)
11491 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11492 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11493 // We've not visited this use, and we care about it (it could have an
11494 // ordering dependency with the original node).
11496 Aliases.push_back(OriginalChain);
11500 // We've not visited this use, but we don't care about it. Mark it as
11501 // visited and enqueue it to the worklist.
11502 Worklist.push_back(*UI);
11507 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11508 /// for a better chain (aliasing node.)
11509 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11510 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11512 // Accumulate all the aliases to this node.
11513 GatherAllAliases(N, OldChain, Aliases);
11515 // If no operands then chain to entry token.
11516 if (Aliases.size() == 0)
11517 return DAG.getEntryNode();
11519 // If a single operand then chain to it. We don't need to revisit it.
11520 if (Aliases.size() == 1)
11523 // Construct a custom tailored token factor.
11524 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11525 &Aliases[0], Aliases.size());
11528 // SelectionDAG::Combine - This is the entry point for the file.
11530 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11531 CodeGenOpt::Level OptLevel) {
11532 /// run - This is the main entry point to this class.
11534 DAGCombiner(*this, AA, OptLevel).Run(Level);