1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
42 #define DEBUG_TYPE "dagcombine"
44 STATISTIC(NodesCombined , "Number of dag nodes combined");
45 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
47 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
48 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
49 STATISTIC(SlicedLoads, "Number of load sliced");
53 CombinerAA("combiner-alias-analysis", cl::Hidden,
54 cl::desc("Enable DAG combiner alias-analysis heuristics"));
57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58 cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62 cl::desc("Enable DAG combiner's use of TBAA"));
65 static cl::opt<std::string>
66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67 cl::desc("Only use DAG-combiner alias analysis in this"
71 /// Hidden option to stress test load slicing, i.e., when this option
72 /// is enabled, load slicing bypasses most of its profitability guards.
74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75 cl::desc("Bypass the profitability model of load "
79 //------------------------------ DAGCombiner ---------------------------------//
83 const TargetLowering &TLI;
85 CodeGenOpt::Level OptLevel;
90 // Worklist of all of the nodes that need to be simplified.
92 // This has the semantics that when adding to the worklist,
93 // the item added must be next to be processed. It should
94 // also only appear once. The naive approach to this takes
97 // To reduce the insert/remove time to logarithmic, we use
98 // a set and a vector to maintain our worklist.
100 // The set contains the items on the worklist, but does not
101 // maintain the order they should be visited.
103 // The vector maintains the order nodes should be visited, but may
104 // contain duplicate or removed nodes. When choosing a node to
105 // visit, we pop off the order stack until we find an item that is
106 // also in the contents set. All operations are O(log N).
107 SmallPtrSet<SDNode*, 64> WorkListContents;
108 SmallVector<SDNode*, 64> WorkListOrder;
110 // AA - Used for DAG load/store alias analysis.
113 /// AddUsersToWorkList - When an instruction is simplified, add all users of
114 /// the instruction to the work lists because they might get more simplified
117 void AddUsersToWorkList(SDNode *N) {
118 for (SDNode *Node : N->uses())
122 /// visit - call the node-specific routine that knows how to fold each
123 /// particular type of node.
124 SDValue visit(SDNode *N);
127 /// AddToWorkList - Add to the work list making sure its instance is at the
128 /// back (next to be processed.)
129 void AddToWorkList(SDNode *N) {
130 // Skip handle nodes as they can't usefully be combined and confuse the
131 // zero-use deletion strategy.
132 if (N->getOpcode() == ISD::HANDLENODE)
135 WorkListContents.insert(N);
136 WorkListOrder.push_back(N);
139 /// removeFromWorkList - remove all instances of N from the worklist.
141 void removeFromWorkList(SDNode *N) {
142 WorkListContents.erase(N);
145 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
148 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
149 return CombineTo(N, &Res, 1, AddTo);
152 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
154 SDValue To[] = { Res0, Res1 };
155 return CombineTo(N, To, 2, AddTo);
158 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
162 /// SimplifyDemandedBits - Check the specified integer node value to see if
163 /// it can be simplified or if things it uses can be simplified by bit
164 /// propagation. If so, return true.
165 bool SimplifyDemandedBits(SDValue Op) {
166 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
167 APInt Demanded = APInt::getAllOnesValue(BitWidth);
168 return SimplifyDemandedBits(Op, Demanded);
171 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
173 bool CombineToPreIndexedLoadStore(SDNode *N);
174 bool CombineToPostIndexedLoadStore(SDNode *N);
175 bool SliceUpLoad(SDNode *N);
177 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
178 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
179 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
180 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
181 SDValue PromoteIntBinOp(SDValue Op);
182 SDValue PromoteIntShiftOp(SDValue Op);
183 SDValue PromoteExtend(SDValue Op);
184 bool PromoteLoad(SDValue Op);
186 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
187 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
188 ISD::NodeType ExtType);
190 /// combine - call the node-specific routine that knows how to fold each
191 /// particular type of node. If that doesn't do anything, try the
192 /// target-specific DAG combines.
193 SDValue combine(SDNode *N);
195 // Visitation implementation - Implement dag node combining for different
196 // node types. The semantics are as follows:
198 // SDValue.getNode() == 0 - No change was made
199 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
200 // otherwise - N should be replaced by the returned Operand.
202 SDValue visitTokenFactor(SDNode *N);
203 SDValue visitMERGE_VALUES(SDNode *N);
204 SDValue visitADD(SDNode *N);
205 SDValue visitSUB(SDNode *N);
206 SDValue visitADDC(SDNode *N);
207 SDValue visitSUBC(SDNode *N);
208 SDValue visitADDE(SDNode *N);
209 SDValue visitSUBE(SDNode *N);
210 SDValue visitMUL(SDNode *N);
211 SDValue visitSDIV(SDNode *N);
212 SDValue visitUDIV(SDNode *N);
213 SDValue visitSREM(SDNode *N);
214 SDValue visitUREM(SDNode *N);
215 SDValue visitMULHU(SDNode *N);
216 SDValue visitMULHS(SDNode *N);
217 SDValue visitSMUL_LOHI(SDNode *N);
218 SDValue visitUMUL_LOHI(SDNode *N);
219 SDValue visitSMULO(SDNode *N);
220 SDValue visitUMULO(SDNode *N);
221 SDValue visitSDIVREM(SDNode *N);
222 SDValue visitUDIVREM(SDNode *N);
223 SDValue visitAND(SDNode *N);
224 SDValue visitOR(SDNode *N);
225 SDValue visitXOR(SDNode *N);
226 SDValue SimplifyVBinOp(SDNode *N);
227 SDValue SimplifyVUnaryOp(SDNode *N);
228 SDValue visitSHL(SDNode *N);
229 SDValue visitSRA(SDNode *N);
230 SDValue visitSRL(SDNode *N);
231 SDValue visitRotate(SDNode *N);
232 SDValue visitCTLZ(SDNode *N);
233 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
234 SDValue visitCTTZ(SDNode *N);
235 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
236 SDValue visitCTPOP(SDNode *N);
237 SDValue visitSELECT(SDNode *N);
238 SDValue visitVSELECT(SDNode *N);
239 SDValue visitSELECT_CC(SDNode *N);
240 SDValue visitSETCC(SDNode *N);
241 SDValue visitSIGN_EXTEND(SDNode *N);
242 SDValue visitZERO_EXTEND(SDNode *N);
243 SDValue visitANY_EXTEND(SDNode *N);
244 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
245 SDValue visitTRUNCATE(SDNode *N);
246 SDValue visitBITCAST(SDNode *N);
247 SDValue visitBUILD_PAIR(SDNode *N);
248 SDValue visitFADD(SDNode *N);
249 SDValue visitFSUB(SDNode *N);
250 SDValue visitFMUL(SDNode *N);
251 SDValue visitFMA(SDNode *N);
252 SDValue visitFDIV(SDNode *N);
253 SDValue visitFREM(SDNode *N);
254 SDValue visitFCOPYSIGN(SDNode *N);
255 SDValue visitSINT_TO_FP(SDNode *N);
256 SDValue visitUINT_TO_FP(SDNode *N);
257 SDValue visitFP_TO_SINT(SDNode *N);
258 SDValue visitFP_TO_UINT(SDNode *N);
259 SDValue visitFP_ROUND(SDNode *N);
260 SDValue visitFP_ROUND_INREG(SDNode *N);
261 SDValue visitFP_EXTEND(SDNode *N);
262 SDValue visitFNEG(SDNode *N);
263 SDValue visitFABS(SDNode *N);
264 SDValue visitFCEIL(SDNode *N);
265 SDValue visitFTRUNC(SDNode *N);
266 SDValue visitFFLOOR(SDNode *N);
267 SDValue visitBRCOND(SDNode *N);
268 SDValue visitBR_CC(SDNode *N);
269 SDValue visitLOAD(SDNode *N);
270 SDValue visitSTORE(SDNode *N);
271 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
272 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
273 SDValue visitBUILD_VECTOR(SDNode *N);
274 SDValue visitCONCAT_VECTORS(SDNode *N);
275 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
276 SDValue visitVECTOR_SHUFFLE(SDNode *N);
277 SDValue visitINSERT_SUBVECTOR(SDNode *N);
279 SDValue XformToShuffleWithZero(SDNode *N);
280 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
282 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
284 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
285 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
286 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
287 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
288 SDValue N3, ISD::CondCode CC,
289 bool NotExtCompare = false);
290 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
291 SDLoc DL, bool foldBooleans = true);
293 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
295 bool isOneUseSetCC(SDValue N) const;
297 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
299 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
300 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
301 SDValue BuildSDIV(SDNode *N);
302 SDValue BuildUDIV(SDNode *N);
303 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
304 bool DemandHighBits = true);
305 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
306 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
307 SDValue InnerPos, SDValue InnerNeg,
308 unsigned PosOpcode, unsigned NegOpcode,
310 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
311 SDValue ReduceLoadWidth(SDNode *N);
312 SDValue ReduceLoadOpStoreWidth(SDNode *N);
313 SDValue TransformFPLoadStorePair(SDNode *N);
314 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
315 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
317 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
319 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
320 /// looking for aliasing nodes and adding them to the Aliases vector.
321 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
322 SmallVectorImpl<SDValue> &Aliases);
324 /// isAlias - Return true if there is any possibility that the two addresses
326 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
328 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
329 /// looking for a better chain (aliasing node.)
330 SDValue FindBetterChain(SDNode *N, SDValue Chain);
332 /// Merge consecutive store operations into a wide store.
333 /// This optimization uses wide integers or vectors when possible.
334 /// \return True if some memory operations were changed.
335 bool MergeConsecutiveStores(StoreSDNode *N);
337 /// \brief Try to transform a truncation where C is a constant:
338 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
340 /// \p N needs to be a truncation and its first operand an AND. Other
341 /// requirements are checked by the function (e.g. that trunc is
342 /// single-use) and if missed an empty SDValue is returned.
343 SDValue distributeTruncateThroughAnd(SDNode *N);
346 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
347 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
348 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
349 AttributeSet FnAttrs =
350 DAG.getMachineFunction().getFunction()->getAttributes();
352 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
353 Attribute::OptimizeForSize) ||
354 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
357 /// Run - runs the dag combiner on all nodes in the work list
358 void Run(CombineLevel AtLevel);
360 SelectionDAG &getDAG() const { return DAG; }
362 /// getShiftAmountTy - Returns a type large enough to hold any valid
363 /// shift amount - before type legalization these can be huge.
364 EVT getShiftAmountTy(EVT LHSTy) {
365 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
366 if (LHSTy.isVector())
368 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
369 : TLI.getPointerTy();
372 /// isTypeLegal - This method returns true if we are running before type
373 /// legalization or if the specified VT is legal.
374 bool isTypeLegal(const EVT &VT) {
375 if (!LegalTypes) return true;
376 return TLI.isTypeLegal(VT);
379 /// getSetCCResultType - Convenience wrapper around
380 /// TargetLowering::getSetCCResultType
381 EVT getSetCCResultType(EVT VT) const {
382 return TLI.getSetCCResultType(*DAG.getContext(), VT);
389 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
390 /// nodes from the worklist.
391 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
394 explicit WorkListRemover(DAGCombiner &dc)
395 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
397 void NodeDeleted(SDNode *N, SDNode *E) override {
398 DC.removeFromWorkList(N);
403 //===----------------------------------------------------------------------===//
404 // TargetLowering::DAGCombinerInfo implementation
405 //===----------------------------------------------------------------------===//
407 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
408 ((DAGCombiner*)DC)->AddToWorkList(N);
411 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
412 ((DAGCombiner*)DC)->removeFromWorkList(N);
415 SDValue TargetLowering::DAGCombinerInfo::
416 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
417 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
420 SDValue TargetLowering::DAGCombinerInfo::
421 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
422 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
426 SDValue TargetLowering::DAGCombinerInfo::
427 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
428 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
431 void TargetLowering::DAGCombinerInfo::
432 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
433 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
436 //===----------------------------------------------------------------------===//
438 //===----------------------------------------------------------------------===//
440 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
441 /// specified expression for the same cost as the expression itself, or 2 if we
442 /// can compute the negated form more cheaply than the expression itself.
443 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
444 const TargetLowering &TLI,
445 const TargetOptions *Options,
446 unsigned Depth = 0) {
447 // fneg is removable even if it has multiple uses.
448 if (Op.getOpcode() == ISD::FNEG) return 2;
450 // Don't allow anything with multiple uses.
451 if (!Op.hasOneUse()) return 0;
453 // Don't recurse exponentially.
454 if (Depth > 6) return 0;
456 switch (Op.getOpcode()) {
457 default: return false;
458 case ISD::ConstantFP:
459 // Don't invert constant FP values after legalize. The negated constant
460 // isn't necessarily legal.
461 return LegalOperations ? 0 : 1;
463 // FIXME: determine better conditions for this xform.
464 if (!Options->UnsafeFPMath) return 0;
466 // After operation legalization, it might not be legal to create new FSUBs.
467 if (LegalOperations &&
468 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
471 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
472 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
475 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
476 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
479 // We can't turn -(A-B) into B-A when we honor signed zeros.
480 if (!Options->UnsafeFPMath) return 0;
482 // fold (fneg (fsub A, B)) -> (fsub B, A)
487 if (Options->HonorSignDependentRoundingFPMath()) return 0;
489 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
490 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
494 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
500 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
505 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
506 /// returns the newly negated expression.
507 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
508 bool LegalOperations, unsigned Depth = 0) {
509 // fneg is removable even if it has multiple uses.
510 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
512 // Don't allow anything with multiple uses.
513 assert(Op.hasOneUse() && "Unknown reuse!");
515 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
516 switch (Op.getOpcode()) {
517 default: llvm_unreachable("Unknown code");
518 case ISD::ConstantFP: {
519 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
521 return DAG.getConstantFP(V, Op.getValueType());
524 // FIXME: determine better conditions for this xform.
525 assert(DAG.getTarget().Options.UnsafeFPMath);
527 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
528 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
529 DAG.getTargetLoweringInfo(),
530 &DAG.getTarget().Options, Depth+1))
531 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
532 GetNegatedExpression(Op.getOperand(0), DAG,
533 LegalOperations, Depth+1),
535 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
536 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
537 GetNegatedExpression(Op.getOperand(1), DAG,
538 LegalOperations, Depth+1),
541 // We can't turn -(A-B) into B-A when we honor signed zeros.
542 assert(DAG.getTarget().Options.UnsafeFPMath);
544 // fold (fneg (fsub 0, B)) -> B
545 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
546 if (N0CFP->getValueAPF().isZero())
547 return Op.getOperand(1);
549 // fold (fneg (fsub A, B)) -> (fsub B, A)
550 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
551 Op.getOperand(1), Op.getOperand(0));
555 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
557 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
558 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
559 DAG.getTargetLoweringInfo(),
560 &DAG.getTarget().Options, Depth+1))
561 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
562 GetNegatedExpression(Op.getOperand(0), DAG,
563 LegalOperations, Depth+1),
566 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
567 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
569 GetNegatedExpression(Op.getOperand(1), DAG,
570 LegalOperations, Depth+1));
574 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
575 GetNegatedExpression(Op.getOperand(0), DAG,
576 LegalOperations, Depth+1));
578 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
579 GetNegatedExpression(Op.getOperand(0), DAG,
580 LegalOperations, Depth+1),
585 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
586 // that selects between the target values used for true and false, making it
587 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
588 // the appropriate nodes based on the type of node we are checking. This
589 // simplifies life a bit for the callers.
590 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
592 if (N.getOpcode() == ISD::SETCC) {
593 LHS = N.getOperand(0);
594 RHS = N.getOperand(1);
595 CC = N.getOperand(2);
599 if (N.getOpcode() != ISD::SELECT_CC ||
600 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
601 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
604 LHS = N.getOperand(0);
605 RHS = N.getOperand(1);
606 CC = N.getOperand(4);
610 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
611 // one use. If this is true, it allows the users to invert the operation for
612 // free when it is profitable to do so.
613 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
615 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
620 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
621 /// elements are all the same constant or undefined.
622 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
623 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
628 unsigned SplatBitSize;
630 EVT EltVT = N->getValueType(0).getVectorElementType();
631 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
633 EltVT.getSizeInBits() >= SplatBitSize);
636 // \brief Returns the SDNode if it is a constant BuildVector or constant.
637 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
638 if (isa<ConstantSDNode>(N))
640 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
641 if(BV && BV->isConstant())
646 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
648 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
649 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
652 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
653 BitVector UndefElements;
654 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
656 // BuildVectors can truncate their operands. Ignore that case here.
657 // FIXME: We blindly ignore splats which include undef which is overly
659 if (CN && UndefElements.none() &&
660 CN->getValueType(0) == N.getValueType().getScalarType())
667 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
668 SDValue N0, SDValue N1) {
669 EVT VT = N0.getValueType();
670 if (N0.getOpcode() == Opc) {
671 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
672 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
673 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
674 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
675 if (!OpNode.getNode())
677 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
679 if (N0.hasOneUse()) {
680 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
682 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
683 if (!OpNode.getNode())
685 AddToWorkList(OpNode.getNode());
686 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
691 if (N1.getOpcode() == Opc) {
692 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
693 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
694 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
695 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
696 if (!OpNode.getNode())
698 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
700 if (N1.hasOneUse()) {
701 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
703 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
704 if (!OpNode.getNode())
706 AddToWorkList(OpNode.getNode());
707 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
715 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
717 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
719 DEBUG(dbgs() << "\nReplacing.1 ";
721 dbgs() << "\nWith: ";
722 To[0].getNode()->dump(&DAG);
723 dbgs() << " and " << NumTo-1 << " other values\n";
724 for (unsigned i = 0, e = NumTo; i != e; ++i)
725 assert((!To[i].getNode() ||
726 N->getValueType(i) == To[i].getValueType()) &&
727 "Cannot combine value to value of different type!"));
728 WorkListRemover DeadNodes(*this);
729 DAG.ReplaceAllUsesWith(N, To);
731 // Push the new nodes and any users onto the worklist
732 for (unsigned i = 0, e = NumTo; i != e; ++i) {
733 if (To[i].getNode()) {
734 AddToWorkList(To[i].getNode());
735 AddUsersToWorkList(To[i].getNode());
740 // Finally, if the node is now dead, remove it from the graph. The node
741 // may not be dead if the replacement process recursively simplified to
742 // something else needing this node.
743 if (N->use_empty()) {
744 // Nodes can be reintroduced into the worklist. Make sure we do not
745 // process a node that has been replaced.
746 removeFromWorkList(N);
748 // Finally, since the node is now dead, remove it from the graph.
751 return SDValue(N, 0);
755 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
756 // Replace all uses. If any nodes become isomorphic to other nodes and
757 // are deleted, make sure to remove them from our worklist.
758 WorkListRemover DeadNodes(*this);
759 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
761 // Push the new node and any (possibly new) users onto the worklist.
762 AddToWorkList(TLO.New.getNode());
763 AddUsersToWorkList(TLO.New.getNode());
765 // Finally, if the node is now dead, remove it from the graph. The node
766 // may not be dead if the replacement process recursively simplified to
767 // something else needing this node.
768 if (TLO.Old.getNode()->use_empty()) {
769 removeFromWorkList(TLO.Old.getNode());
771 // If the operands of this node are only used by the node, they will now
772 // be dead. Make sure to visit them first to delete dead nodes early.
773 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
774 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
775 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
777 DAG.DeleteNode(TLO.Old.getNode());
781 /// SimplifyDemandedBits - Check the specified integer node value to see if
782 /// it can be simplified or if things it uses can be simplified by bit
783 /// propagation. If so, return true.
784 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
785 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
786 APInt KnownZero, KnownOne;
787 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
791 AddToWorkList(Op.getNode());
793 // Replace the old value with the new one.
795 DEBUG(dbgs() << "\nReplacing.2 ";
796 TLO.Old.getNode()->dump(&DAG);
797 dbgs() << "\nWith: ";
798 TLO.New.getNode()->dump(&DAG);
801 CommitTargetLoweringOpt(TLO);
805 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
807 EVT VT = Load->getValueType(0);
808 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
810 DEBUG(dbgs() << "\nReplacing.9 ";
812 dbgs() << "\nWith: ";
813 Trunc.getNode()->dump(&DAG);
815 WorkListRemover DeadNodes(*this);
816 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
817 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
818 removeFromWorkList(Load);
819 DAG.DeleteNode(Load);
820 AddToWorkList(Trunc.getNode());
823 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
826 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
827 EVT MemVT = LD->getMemoryVT();
828 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
829 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
831 : LD->getExtensionType();
833 return DAG.getExtLoad(ExtType, dl, PVT,
834 LD->getChain(), LD->getBasePtr(),
835 MemVT, LD->getMemOperand());
838 unsigned Opc = Op.getOpcode();
841 case ISD::AssertSext:
842 return DAG.getNode(ISD::AssertSext, dl, PVT,
843 SExtPromoteOperand(Op.getOperand(0), PVT),
845 case ISD::AssertZext:
846 return DAG.getNode(ISD::AssertZext, dl, PVT,
847 ZExtPromoteOperand(Op.getOperand(0), PVT),
849 case ISD::Constant: {
851 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
852 return DAG.getNode(ExtOpc, dl, PVT, Op);
856 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
858 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
861 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
862 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 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.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
875 DAG.getValueType(OldVT));
878 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
879 EVT OldVT = Op.getValueType();
881 bool Replace = false;
882 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
883 if (!NewOp.getNode())
885 AddToWorkList(NewOp.getNode());
888 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
889 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
892 /// PromoteIntBinOp - Promote the specified integer binary operation if the
893 /// target indicates it is beneficial. e.g. On x86, it's usually better to
894 /// promote i16 operations to i32 since i16 instructions are longer.
895 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
896 if (!LegalOperations)
899 EVT VT = Op.getValueType();
900 if (VT.isVector() || !VT.isInteger())
903 // If operation type is 'undesirable', e.g. i16 on x86, consider
905 unsigned Opc = Op.getOpcode();
906 if (TLI.isTypeDesirableForOp(Opc, VT))
910 // Consult target whether it is a good idea to promote this operation and
911 // what's the right type to promote it to.
912 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
913 assert(PVT != VT && "Don't know what type to promote to!");
915 bool Replace0 = false;
916 SDValue N0 = Op.getOperand(0);
917 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
921 bool Replace1 = false;
922 SDValue N1 = Op.getOperand(1);
927 NN1 = PromoteOperand(N1, PVT, Replace1);
932 AddToWorkList(NN0.getNode());
934 AddToWorkList(NN1.getNode());
937 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
939 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
941 DEBUG(dbgs() << "\nPromoting ";
942 Op.getNode()->dump(&DAG));
944 return DAG.getNode(ISD::TRUNCATE, dl, VT,
945 DAG.getNode(Opc, dl, PVT, NN0, NN1));
950 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
951 /// target indicates it is beneficial. e.g. On x86, it's usually better to
952 /// promote i16 operations to i32 since i16 instructions are longer.
953 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
954 if (!LegalOperations)
957 EVT VT = Op.getValueType();
958 if (VT.isVector() || !VT.isInteger())
961 // If operation type is 'undesirable', e.g. i16 on x86, consider
963 unsigned Opc = Op.getOpcode();
964 if (TLI.isTypeDesirableForOp(Opc, VT))
968 // Consult target whether it is a good idea to promote this operation and
969 // what's the right type to promote it to.
970 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
971 assert(PVT != VT && "Don't know what type to promote to!");
973 bool Replace = false;
974 SDValue N0 = Op.getOperand(0);
976 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
977 else if (Opc == ISD::SRL)
978 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
980 N0 = PromoteOperand(N0, PVT, Replace);
984 AddToWorkList(N0.getNode());
986 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
988 DEBUG(dbgs() << "\nPromoting ";
989 Op.getNode()->dump(&DAG));
991 return DAG.getNode(ISD::TRUNCATE, dl, VT,
992 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
997 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
998 if (!LegalOperations)
1001 EVT VT = Op.getValueType();
1002 if (VT.isVector() || !VT.isInteger())
1005 // If operation type is 'undesirable', e.g. i16 on x86, consider
1007 unsigned Opc = Op.getOpcode();
1008 if (TLI.isTypeDesirableForOp(Opc, VT))
1012 // Consult target whether it is a good idea to promote this operation and
1013 // what's the right type to promote it to.
1014 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1015 assert(PVT != VT && "Don't know what type to promote to!");
1016 // fold (aext (aext x)) -> (aext x)
1017 // fold (aext (zext x)) -> (zext x)
1018 // fold (aext (sext x)) -> (sext x)
1019 DEBUG(dbgs() << "\nPromoting ";
1020 Op.getNode()->dump(&DAG));
1021 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1026 bool DAGCombiner::PromoteLoad(SDValue Op) {
1027 if (!LegalOperations)
1030 EVT VT = Op.getValueType();
1031 if (VT.isVector() || !VT.isInteger())
1034 // If operation type is 'undesirable', e.g. i16 on x86, consider
1036 unsigned Opc = Op.getOpcode();
1037 if (TLI.isTypeDesirableForOp(Opc, VT))
1041 // Consult target whether it is a good idea to promote this operation and
1042 // what's the right type to promote it to.
1043 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1044 assert(PVT != VT && "Don't know what type to promote to!");
1047 SDNode *N = Op.getNode();
1048 LoadSDNode *LD = cast<LoadSDNode>(N);
1049 EVT MemVT = LD->getMemoryVT();
1050 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1051 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1053 : LD->getExtensionType();
1054 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1055 LD->getChain(), LD->getBasePtr(),
1056 MemVT, LD->getMemOperand());
1057 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1059 DEBUG(dbgs() << "\nPromoting ";
1062 Result.getNode()->dump(&DAG);
1064 WorkListRemover DeadNodes(*this);
1065 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1066 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1067 removeFromWorkList(N);
1069 AddToWorkList(Result.getNode());
1076 //===----------------------------------------------------------------------===//
1077 // Main DAG Combiner implementation
1078 //===----------------------------------------------------------------------===//
1080 void DAGCombiner::Run(CombineLevel AtLevel) {
1081 // set the instance variables, so that the various visit routines may use it.
1083 LegalOperations = Level >= AfterLegalizeVectorOps;
1084 LegalTypes = Level >= AfterLegalizeTypes;
1086 // Add all the dag nodes to the worklist.
1087 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1088 E = DAG.allnodes_end(); I != E; ++I)
1091 // Create a dummy node (which is not added to allnodes), that adds a reference
1092 // to the root node, preventing it from being deleted, and tracking any
1093 // changes of the root.
1094 HandleSDNode Dummy(DAG.getRoot());
1096 // The root of the dag may dangle to deleted nodes until the dag combiner is
1097 // done. Set it to null to avoid confusion.
1098 DAG.setRoot(SDValue());
1100 // while the worklist isn't empty, find a node and
1101 // try and combine it.
1102 while (!WorkListContents.empty()) {
1104 // The WorkListOrder holds the SDNodes in order, but it may contain
1106 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1107 // worklist *should* contain, and check the node we want to visit is should
1108 // actually be visited.
1110 N = WorkListOrder.pop_back_val();
1111 } while (!WorkListContents.erase(N));
1113 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1114 // N is deleted from the DAG, since they too may now be dead or may have a
1115 // reduced number of uses, allowing other xforms.
1116 if (N->use_empty()) {
1117 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1118 AddToWorkList(N->getOperand(i).getNode());
1124 SDValue RV = combine(N);
1131 // If we get back the same node we passed in, rather than a new node or
1132 // zero, we know that the node must have defined multiple values and
1133 // CombineTo was used. Since CombineTo takes care of the worklist
1134 // mechanics for us, we have no work to do in this case.
1135 if (RV.getNode() == N)
1138 assert(N->getOpcode() != ISD::DELETED_NODE &&
1139 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1140 "Node was deleted but visit returned new node!");
1142 DEBUG(dbgs() << "\nReplacing.3 ";
1144 dbgs() << "\nWith: ";
1145 RV.getNode()->dump(&DAG);
1148 // Transfer debug value.
1149 DAG.TransferDbgValues(SDValue(N, 0), RV);
1150 WorkListRemover DeadNodes(*this);
1151 if (N->getNumValues() == RV.getNode()->getNumValues())
1152 DAG.ReplaceAllUsesWith(N, RV.getNode());
1154 assert(N->getValueType(0) == RV.getValueType() &&
1155 N->getNumValues() == 1 && "Type mismatch");
1157 DAG.ReplaceAllUsesWith(N, &OpV);
1160 // Push the new node and any users onto the worklist
1161 AddToWorkList(RV.getNode());
1162 AddUsersToWorkList(RV.getNode());
1164 // Add any uses of the old node to the worklist in case this node is the
1165 // last one that uses them. They may become dead after this node is
1167 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1168 AddToWorkList(N->getOperand(i).getNode());
1170 // Finally, if the node is now dead, remove it from the graph. The node
1171 // may not be dead if the replacement process recursively simplified to
1172 // something else needing this node.
1173 if (N->use_empty()) {
1174 // Nodes can be reintroduced into the worklist. Make sure we do not
1175 // process a node that has been replaced.
1176 removeFromWorkList(N);
1178 // Finally, since the node is now dead, remove it from the graph.
1183 // If the root changed (e.g. it was a dead load, update the root).
1184 DAG.setRoot(Dummy.getValue());
1185 DAG.RemoveDeadNodes();
1188 SDValue DAGCombiner::visit(SDNode *N) {
1189 switch (N->getOpcode()) {
1191 case ISD::TokenFactor: return visitTokenFactor(N);
1192 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1193 case ISD::ADD: return visitADD(N);
1194 case ISD::SUB: return visitSUB(N);
1195 case ISD::ADDC: return visitADDC(N);
1196 case ISD::SUBC: return visitSUBC(N);
1197 case ISD::ADDE: return visitADDE(N);
1198 case ISD::SUBE: return visitSUBE(N);
1199 case ISD::MUL: return visitMUL(N);
1200 case ISD::SDIV: return visitSDIV(N);
1201 case ISD::UDIV: return visitUDIV(N);
1202 case ISD::SREM: return visitSREM(N);
1203 case ISD::UREM: return visitUREM(N);
1204 case ISD::MULHU: return visitMULHU(N);
1205 case ISD::MULHS: return visitMULHS(N);
1206 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1207 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1208 case ISD::SMULO: return visitSMULO(N);
1209 case ISD::UMULO: return visitUMULO(N);
1210 case ISD::SDIVREM: return visitSDIVREM(N);
1211 case ISD::UDIVREM: return visitUDIVREM(N);
1212 case ISD::AND: return visitAND(N);
1213 case ISD::OR: return visitOR(N);
1214 case ISD::XOR: return visitXOR(N);
1215 case ISD::SHL: return visitSHL(N);
1216 case ISD::SRA: return visitSRA(N);
1217 case ISD::SRL: return visitSRL(N);
1219 case ISD::ROTL: return visitRotate(N);
1220 case ISD::CTLZ: return visitCTLZ(N);
1221 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1222 case ISD::CTTZ: return visitCTTZ(N);
1223 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1224 case ISD::CTPOP: return visitCTPOP(N);
1225 case ISD::SELECT: return visitSELECT(N);
1226 case ISD::VSELECT: return visitVSELECT(N);
1227 case ISD::SELECT_CC: return visitSELECT_CC(N);
1228 case ISD::SETCC: return visitSETCC(N);
1229 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1230 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1231 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1232 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1233 case ISD::TRUNCATE: return visitTRUNCATE(N);
1234 case ISD::BITCAST: return visitBITCAST(N);
1235 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1236 case ISD::FADD: return visitFADD(N);
1237 case ISD::FSUB: return visitFSUB(N);
1238 case ISD::FMUL: return visitFMUL(N);
1239 case ISD::FMA: return visitFMA(N);
1240 case ISD::FDIV: return visitFDIV(N);
1241 case ISD::FREM: return visitFREM(N);
1242 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1243 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1244 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1245 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1246 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1247 case ISD::FP_ROUND: return visitFP_ROUND(N);
1248 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1249 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1250 case ISD::FNEG: return visitFNEG(N);
1251 case ISD::FABS: return visitFABS(N);
1252 case ISD::FFLOOR: return visitFFLOOR(N);
1253 case ISD::FCEIL: return visitFCEIL(N);
1254 case ISD::FTRUNC: return visitFTRUNC(N);
1255 case ISD::BRCOND: return visitBRCOND(N);
1256 case ISD::BR_CC: return visitBR_CC(N);
1257 case ISD::LOAD: return visitLOAD(N);
1258 case ISD::STORE: return visitSTORE(N);
1259 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1260 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1261 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1262 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1263 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1264 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1265 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1270 SDValue DAGCombiner::combine(SDNode *N) {
1271 SDValue RV = visit(N);
1273 // If nothing happened, try a target-specific DAG combine.
1274 if (!RV.getNode()) {
1275 assert(N->getOpcode() != ISD::DELETED_NODE &&
1276 "Node was deleted but visit returned NULL!");
1278 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1279 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1281 // Expose the DAG combiner to the target combiner impls.
1282 TargetLowering::DAGCombinerInfo
1283 DagCombineInfo(DAG, Level, false, this);
1285 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1289 // If nothing happened still, try promoting the operation.
1290 if (!RV.getNode()) {
1291 switch (N->getOpcode()) {
1299 RV = PromoteIntBinOp(SDValue(N, 0));
1304 RV = PromoteIntShiftOp(SDValue(N, 0));
1306 case ISD::SIGN_EXTEND:
1307 case ISD::ZERO_EXTEND:
1308 case ISD::ANY_EXTEND:
1309 RV = PromoteExtend(SDValue(N, 0));
1312 if (PromoteLoad(SDValue(N, 0)))
1318 // If N is a commutative binary node, try commuting it to enable more
1320 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1321 N->getNumValues() == 1) {
1322 SDValue N0 = N->getOperand(0);
1323 SDValue N1 = N->getOperand(1);
1325 // Constant operands are canonicalized to RHS.
1326 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1327 SDValue Ops[] = {N1, N0};
1329 if (const BinaryWithFlagsSDNode *BinNode =
1330 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1331 CSENode = DAG.getNodeIfExists(
1332 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1333 BinNode->hasNoSignedWrap(), BinNode->isExact());
1335 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1338 return SDValue(CSENode, 0);
1345 /// getInputChainForNode - Given a node, return its input chain if it has one,
1346 /// otherwise return a null sd operand.
1347 static SDValue getInputChainForNode(SDNode *N) {
1348 if (unsigned NumOps = N->getNumOperands()) {
1349 if (N->getOperand(0).getValueType() == MVT::Other)
1350 return N->getOperand(0);
1351 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1352 return N->getOperand(NumOps-1);
1353 for (unsigned i = 1; i < NumOps-1; ++i)
1354 if (N->getOperand(i).getValueType() == MVT::Other)
1355 return N->getOperand(i);
1360 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1361 // If N has two operands, where one has an input chain equal to the other,
1362 // the 'other' chain is redundant.
1363 if (N->getNumOperands() == 2) {
1364 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1365 return N->getOperand(0);
1366 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1367 return N->getOperand(1);
1370 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1371 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1372 SmallPtrSet<SDNode*, 16> SeenOps;
1373 bool Changed = false; // If we should replace this token factor.
1375 // Start out with this token factor.
1378 // Iterate through token factors. The TFs grows when new token factors are
1380 for (unsigned i = 0; i < TFs.size(); ++i) {
1381 SDNode *TF = TFs[i];
1383 // Check each of the operands.
1384 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1385 SDValue Op = TF->getOperand(i);
1387 switch (Op.getOpcode()) {
1388 case ISD::EntryToken:
1389 // Entry tokens don't need to be added to the list. They are
1394 case ISD::TokenFactor:
1395 if (Op.hasOneUse() &&
1396 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1397 // Queue up for processing.
1398 TFs.push_back(Op.getNode());
1399 // Clean up in case the token factor is removed.
1400 AddToWorkList(Op.getNode());
1407 // Only add if it isn't already in the list.
1408 if (SeenOps.insert(Op.getNode()))
1419 // If we've change things around then replace token factor.
1422 // The entry token is the only possible outcome.
1423 Result = DAG.getEntryNode();
1425 // New and improved token factor.
1426 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1429 // Don't add users to work list.
1430 return CombineTo(N, Result, false);
1436 /// MERGE_VALUES can always be eliminated.
1437 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1438 WorkListRemover DeadNodes(*this);
1439 // Replacing results may cause a different MERGE_VALUES to suddenly
1440 // be CSE'd with N, and carry its uses with it. Iterate until no
1441 // uses remain, to ensure that the node can be safely deleted.
1442 // First add the users of this node to the work list so that they
1443 // can be tried again once they have new operands.
1444 AddUsersToWorkList(N);
1446 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1447 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1448 } while (!N->use_empty());
1449 removeFromWorkList(N);
1451 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1455 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1456 SelectionDAG &DAG) {
1457 EVT VT = N0.getValueType();
1458 SDValue N00 = N0.getOperand(0);
1459 SDValue N01 = N0.getOperand(1);
1460 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1462 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1463 isa<ConstantSDNode>(N00.getOperand(1))) {
1464 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1465 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1466 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1467 N00.getOperand(0), N01),
1468 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1469 N00.getOperand(1), N01));
1470 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1476 SDValue DAGCombiner::visitADD(SDNode *N) {
1477 SDValue N0 = N->getOperand(0);
1478 SDValue N1 = N->getOperand(1);
1479 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1480 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1481 EVT VT = N0.getValueType();
1484 if (VT.isVector()) {
1485 SDValue FoldedVOp = SimplifyVBinOp(N);
1486 if (FoldedVOp.getNode()) return FoldedVOp;
1488 // fold (add x, 0) -> x, vector edition
1489 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1491 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1495 // fold (add x, undef) -> undef
1496 if (N0.getOpcode() == ISD::UNDEF)
1498 if (N1.getOpcode() == ISD::UNDEF)
1500 // fold (add c1, c2) -> c1+c2
1502 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1503 // canonicalize constant to RHS
1505 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1506 // fold (add x, 0) -> x
1507 if (N1C && N1C->isNullValue())
1509 // fold (add Sym, c) -> Sym+c
1510 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1511 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1512 GA->getOpcode() == ISD::GlobalAddress)
1513 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1515 (uint64_t)N1C->getSExtValue());
1516 // fold ((c1-A)+c2) -> (c1+c2)-A
1517 if (N1C && N0.getOpcode() == ISD::SUB)
1518 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1519 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1520 DAG.getConstant(N1C->getAPIntValue()+
1521 N0C->getAPIntValue(), VT),
1524 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1527 // fold ((0-A) + B) -> B-A
1528 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1529 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1530 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1531 // fold (A + (0-B)) -> A-B
1532 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1533 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1534 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1535 // fold (A+(B-A)) -> B
1536 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1537 return N1.getOperand(0);
1538 // fold ((B-A)+A) -> B
1539 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1540 return N0.getOperand(0);
1541 // fold (A+(B-(A+C))) to (B-C)
1542 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1543 N0 == N1.getOperand(1).getOperand(0))
1544 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1545 N1.getOperand(1).getOperand(1));
1546 // fold (A+(B-(C+A))) to (B-C)
1547 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1548 N0 == N1.getOperand(1).getOperand(1))
1549 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1550 N1.getOperand(1).getOperand(0));
1551 // fold (A+((B-A)+or-C)) to (B+or-C)
1552 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1553 N1.getOperand(0).getOpcode() == ISD::SUB &&
1554 N0 == N1.getOperand(0).getOperand(1))
1555 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1556 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1558 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1559 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1560 SDValue N00 = N0.getOperand(0);
1561 SDValue N01 = N0.getOperand(1);
1562 SDValue N10 = N1.getOperand(0);
1563 SDValue N11 = N1.getOperand(1);
1565 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1566 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1567 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1568 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1571 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1572 return SDValue(N, 0);
1574 // fold (a+b) -> (a|b) iff a and b share no bits.
1575 if (VT.isInteger() && !VT.isVector()) {
1576 APInt LHSZero, LHSOne;
1577 APInt RHSZero, RHSOne;
1578 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1580 if (LHSZero.getBoolValue()) {
1581 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1583 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1584 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1585 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1586 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1587 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1592 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1593 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1594 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1595 if (Result.getNode()) return Result;
1597 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1598 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1599 if (Result.getNode()) return Result;
1602 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1603 if (N1.getOpcode() == ISD::SHL &&
1604 N1.getOperand(0).getOpcode() == ISD::SUB)
1605 if (ConstantSDNode *C =
1606 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1607 if (C->getAPIntValue() == 0)
1608 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1609 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1610 N1.getOperand(0).getOperand(1),
1612 if (N0.getOpcode() == ISD::SHL &&
1613 N0.getOperand(0).getOpcode() == ISD::SUB)
1614 if (ConstantSDNode *C =
1615 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1616 if (C->getAPIntValue() == 0)
1617 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1618 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1619 N0.getOperand(0).getOperand(1),
1622 if (N1.getOpcode() == ISD::AND) {
1623 SDValue AndOp0 = N1.getOperand(0);
1624 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1625 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1626 unsigned DestBits = VT.getScalarType().getSizeInBits();
1628 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1629 // and similar xforms where the inner op is either ~0 or 0.
1630 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1632 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1636 // add (sext i1), X -> sub X, (zext i1)
1637 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1638 N0.getOperand(0).getValueType() == MVT::i1 &&
1639 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1641 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1642 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1648 SDValue DAGCombiner::visitADDC(SDNode *N) {
1649 SDValue N0 = N->getOperand(0);
1650 SDValue N1 = N->getOperand(1);
1651 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1652 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1653 EVT VT = N0.getValueType();
1655 // If the flag result is dead, turn this into an ADD.
1656 if (!N->hasAnyUseOfValue(1))
1657 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1658 DAG.getNode(ISD::CARRY_FALSE,
1659 SDLoc(N), MVT::Glue));
1661 // canonicalize constant to RHS.
1663 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1665 // fold (addc x, 0) -> x + no carry out
1666 if (N1C && N1C->isNullValue())
1667 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1668 SDLoc(N), MVT::Glue));
1670 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1671 APInt LHSZero, LHSOne;
1672 APInt RHSZero, RHSOne;
1673 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1675 if (LHSZero.getBoolValue()) {
1676 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1678 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1679 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1680 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1681 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1682 DAG.getNode(ISD::CARRY_FALSE,
1683 SDLoc(N), MVT::Glue));
1689 SDValue DAGCombiner::visitADDE(SDNode *N) {
1690 SDValue N0 = N->getOperand(0);
1691 SDValue N1 = N->getOperand(1);
1692 SDValue CarryIn = N->getOperand(2);
1693 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1694 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1696 // canonicalize constant to RHS
1698 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1701 // fold (adde x, y, false) -> (addc x, y)
1702 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1703 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1708 // Since it may not be valid to emit a fold to zero for vector initializers
1709 // check if we can before folding.
1710 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1712 bool LegalOperations, bool LegalTypes) {
1714 return DAG.getConstant(0, VT);
1715 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1716 return DAG.getConstant(0, VT);
1720 SDValue DAGCombiner::visitSUB(SDNode *N) {
1721 SDValue N0 = N->getOperand(0);
1722 SDValue N1 = N->getOperand(1);
1723 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1724 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1725 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1726 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1727 EVT VT = N0.getValueType();
1730 if (VT.isVector()) {
1731 SDValue FoldedVOp = SimplifyVBinOp(N);
1732 if (FoldedVOp.getNode()) return FoldedVOp;
1734 // fold (sub x, 0) -> x, vector edition
1735 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1739 // fold (sub x, x) -> 0
1740 // FIXME: Refactor this and xor and other similar operations together.
1742 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1743 // fold (sub c1, c2) -> c1-c2
1745 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1746 // fold (sub x, c) -> (add x, -c)
1748 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1749 DAG.getConstant(-N1C->getAPIntValue(), VT));
1750 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1751 if (N0C && N0C->isAllOnesValue())
1752 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1753 // fold A-(A-B) -> B
1754 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1755 return N1.getOperand(1);
1756 // fold (A+B)-A -> B
1757 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1758 return N0.getOperand(1);
1759 // fold (A+B)-B -> A
1760 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1761 return N0.getOperand(0);
1762 // fold C2-(A+C1) -> (C2-C1)-A
1763 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1764 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1766 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1769 // fold ((A+(B+or-C))-B) -> A+or-C
1770 if (N0.getOpcode() == ISD::ADD &&
1771 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1772 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1773 N0.getOperand(1).getOperand(0) == N1)
1774 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1775 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1776 // fold ((A+(C+B))-B) -> A+C
1777 if (N0.getOpcode() == ISD::ADD &&
1778 N0.getOperand(1).getOpcode() == ISD::ADD &&
1779 N0.getOperand(1).getOperand(1) == N1)
1780 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1781 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1782 // fold ((A-(B-C))-C) -> A-B
1783 if (N0.getOpcode() == ISD::SUB &&
1784 N0.getOperand(1).getOpcode() == ISD::SUB &&
1785 N0.getOperand(1).getOperand(1) == N1)
1786 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1787 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1789 // If either operand of a sub is undef, the result is undef
1790 if (N0.getOpcode() == ISD::UNDEF)
1792 if (N1.getOpcode() == ISD::UNDEF)
1795 // If the relocation model supports it, consider symbol offsets.
1796 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1797 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1798 // fold (sub Sym, c) -> Sym-c
1799 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1800 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1802 (uint64_t)N1C->getSExtValue());
1803 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1804 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1805 if (GA->getGlobal() == GB->getGlobal())
1806 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1813 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1814 SDValue N0 = N->getOperand(0);
1815 SDValue N1 = N->getOperand(1);
1816 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1817 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1818 EVT VT = N0.getValueType();
1820 // If the flag result is dead, turn this into an SUB.
1821 if (!N->hasAnyUseOfValue(1))
1822 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1823 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1826 // fold (subc x, x) -> 0 + no borrow
1828 return CombineTo(N, DAG.getConstant(0, VT),
1829 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1832 // fold (subc x, 0) -> x + no borrow
1833 if (N1C && N1C->isNullValue())
1834 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1837 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1838 if (N0C && N0C->isAllOnesValue())
1839 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1840 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1846 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1847 SDValue N0 = N->getOperand(0);
1848 SDValue N1 = N->getOperand(1);
1849 SDValue CarryIn = N->getOperand(2);
1851 // fold (sube x, y, false) -> (subc x, y)
1852 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1853 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1858 SDValue DAGCombiner::visitMUL(SDNode *N) {
1859 SDValue N0 = N->getOperand(0);
1860 SDValue N1 = N->getOperand(1);
1861 EVT VT = N0.getValueType();
1863 // fold (mul x, undef) -> 0
1864 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1865 return DAG.getConstant(0, VT);
1867 bool N0IsConst = false;
1868 bool N1IsConst = false;
1869 APInt ConstValue0, ConstValue1;
1871 if (VT.isVector()) {
1872 SDValue FoldedVOp = SimplifyVBinOp(N);
1873 if (FoldedVOp.getNode()) return FoldedVOp;
1875 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1876 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1878 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1879 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1881 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1882 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1886 // fold (mul c1, c2) -> c1*c2
1887 if (N0IsConst && N1IsConst)
1888 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1890 // canonicalize constant to RHS
1891 if (N0IsConst && !N1IsConst)
1892 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1893 // fold (mul x, 0) -> 0
1894 if (N1IsConst && ConstValue1 == 0)
1896 // We require a splat of the entire scalar bit width for non-contiguous
1899 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1900 // fold (mul x, 1) -> x
1901 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1903 // fold (mul x, -1) -> 0-x
1904 if (N1IsConst && ConstValue1.isAllOnesValue())
1905 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1906 DAG.getConstant(0, VT), N0);
1907 // fold (mul x, (1 << c)) -> x << c
1908 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1909 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1910 DAG.getConstant(ConstValue1.logBase2(),
1911 getShiftAmountTy(N0.getValueType())));
1912 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1913 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1914 unsigned Log2Val = (-ConstValue1).logBase2();
1915 // FIXME: If the input is something that is easily negated (e.g. a
1916 // single-use add), we should put the negate there.
1917 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1918 DAG.getConstant(0, VT),
1919 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1920 DAG.getConstant(Log2Val,
1921 getShiftAmountTy(N0.getValueType()))));
1925 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1926 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1927 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1928 isa<ConstantSDNode>(N0.getOperand(1)))) {
1929 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1930 N1, N0.getOperand(1));
1931 AddToWorkList(C3.getNode());
1932 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1933 N0.getOperand(0), C3);
1936 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1939 SDValue Sh(nullptr,0), Y(nullptr,0);
1940 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1941 if (N0.getOpcode() == ISD::SHL &&
1942 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1943 isa<ConstantSDNode>(N0.getOperand(1))) &&
1944 N0.getNode()->hasOneUse()) {
1946 } else if (N1.getOpcode() == ISD::SHL &&
1947 isa<ConstantSDNode>(N1.getOperand(1)) &&
1948 N1.getNode()->hasOneUse()) {
1953 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1954 Sh.getOperand(0), Y);
1955 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1956 Mul, Sh.getOperand(1));
1960 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1961 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1962 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1963 isa<ConstantSDNode>(N0.getOperand(1))))
1964 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1965 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1966 N0.getOperand(0), N1),
1967 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1968 N0.getOperand(1), N1));
1971 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1978 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1979 SDValue N0 = N->getOperand(0);
1980 SDValue N1 = N->getOperand(1);
1981 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1982 ConstantSDNode *N1C = isConstOrConstSplat(N1);
1983 EVT VT = N->getValueType(0);
1986 if (VT.isVector()) {
1987 SDValue FoldedVOp = SimplifyVBinOp(N);
1988 if (FoldedVOp.getNode()) return FoldedVOp;
1991 // fold (sdiv c1, c2) -> c1/c2
1992 if (N0C && N1C && !N1C->isNullValue())
1993 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1994 // fold (sdiv X, 1) -> X
1995 if (N1C && N1C->getAPIntValue() == 1LL)
1997 // fold (sdiv X, -1) -> 0-X
1998 if (N1C && N1C->isAllOnesValue())
1999 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2000 DAG.getConstant(0, VT), N0);
2001 // If we know the sign bits of both operands are zero, strength reduce to a
2002 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2003 if (!VT.isVector()) {
2004 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2005 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2009 // fold (sdiv X, pow2) -> simple ops after legalize
2010 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2011 (-N1C->getAPIntValue()).isPowerOf2())) {
2012 // If dividing by powers of two is cheap, then don't perform the following
2014 if (TLI.isPow2DivCheap())
2017 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2019 // Splat the sign bit into the register
2021 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2022 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2023 getShiftAmountTy(N0.getValueType())));
2024 AddToWorkList(SGN.getNode());
2026 // Add (N0 < 0) ? abs2 - 1 : 0;
2028 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2029 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2030 getShiftAmountTy(SGN.getValueType())));
2031 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2032 AddToWorkList(SRL.getNode());
2033 AddToWorkList(ADD.getNode()); // Divide by pow2
2034 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2035 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2037 // If we're dividing by a positive value, we're done. Otherwise, we must
2038 // negate the result.
2039 if (N1C->getAPIntValue().isNonNegative())
2042 AddToWorkList(SRA.getNode());
2043 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2046 // if integer divide is expensive and we satisfy the requirements, emit an
2047 // alternate sequence.
2048 if (N1C && !TLI.isIntDivCheap()) {
2049 SDValue Op = BuildSDIV(N);
2050 if (Op.getNode()) return Op;
2054 if (N0.getOpcode() == ISD::UNDEF)
2055 return DAG.getConstant(0, VT);
2056 // X / undef -> undef
2057 if (N1.getOpcode() == ISD::UNDEF)
2063 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2064 SDValue N0 = N->getOperand(0);
2065 SDValue N1 = N->getOperand(1);
2066 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2067 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2068 EVT VT = N->getValueType(0);
2071 if (VT.isVector()) {
2072 SDValue FoldedVOp = SimplifyVBinOp(N);
2073 if (FoldedVOp.getNode()) return FoldedVOp;
2076 // fold (udiv c1, c2) -> c1/c2
2077 if (N0C && N1C && !N1C->isNullValue())
2078 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2079 // fold (udiv x, (1 << c)) -> x >>u c
2080 if (N1C && N1C->getAPIntValue().isPowerOf2())
2081 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2082 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2083 getShiftAmountTy(N0.getValueType())));
2084 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2085 if (N1.getOpcode() == ISD::SHL) {
2086 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2087 if (SHC->getAPIntValue().isPowerOf2()) {
2088 EVT ADDVT = N1.getOperand(1).getValueType();
2089 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2091 DAG.getConstant(SHC->getAPIntValue()
2094 AddToWorkList(Add.getNode());
2095 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2099 // fold (udiv x, c) -> alternate
2100 if (N1C && !TLI.isIntDivCheap()) {
2101 SDValue Op = BuildUDIV(N);
2102 if (Op.getNode()) return Op;
2106 if (N0.getOpcode() == ISD::UNDEF)
2107 return DAG.getConstant(0, VT);
2108 // X / undef -> undef
2109 if (N1.getOpcode() == ISD::UNDEF)
2115 SDValue DAGCombiner::visitSREM(SDNode *N) {
2116 SDValue N0 = N->getOperand(0);
2117 SDValue N1 = N->getOperand(1);
2118 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2119 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2120 EVT VT = N->getValueType(0);
2122 // fold (srem c1, c2) -> c1%c2
2123 if (N0C && N1C && !N1C->isNullValue())
2124 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2125 // If we know the sign bits of both operands are zero, strength reduce to a
2126 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2127 if (!VT.isVector()) {
2128 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2129 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2132 // If X/C can be simplified by the division-by-constant logic, lower
2133 // X%C to the equivalent of X-X/C*C.
2134 if (N1C && !N1C->isNullValue()) {
2135 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2136 AddToWorkList(Div.getNode());
2137 SDValue OptimizedDiv = combine(Div.getNode());
2138 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2139 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2141 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2142 AddToWorkList(Mul.getNode());
2148 if (N0.getOpcode() == ISD::UNDEF)
2149 return DAG.getConstant(0, VT);
2150 // X % undef -> undef
2151 if (N1.getOpcode() == ISD::UNDEF)
2157 SDValue DAGCombiner::visitUREM(SDNode *N) {
2158 SDValue N0 = N->getOperand(0);
2159 SDValue N1 = N->getOperand(1);
2160 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2161 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2162 EVT VT = N->getValueType(0);
2164 // fold (urem c1, c2) -> c1%c2
2165 if (N0C && N1C && !N1C->isNullValue())
2166 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2167 // fold (urem x, pow2) -> (and x, pow2-1)
2168 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2169 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2170 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2171 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2172 if (N1.getOpcode() == ISD::SHL) {
2173 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2174 if (SHC->getAPIntValue().isPowerOf2()) {
2176 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2177 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2179 AddToWorkList(Add.getNode());
2180 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2185 // If X/C can be simplified by the division-by-constant logic, lower
2186 // X%C to the equivalent of X-X/C*C.
2187 if (N1C && !N1C->isNullValue()) {
2188 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2189 AddToWorkList(Div.getNode());
2190 SDValue OptimizedDiv = combine(Div.getNode());
2191 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2192 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2194 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2195 AddToWorkList(Mul.getNode());
2201 if (N0.getOpcode() == ISD::UNDEF)
2202 return DAG.getConstant(0, VT);
2203 // X % undef -> undef
2204 if (N1.getOpcode() == ISD::UNDEF)
2210 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2211 SDValue N0 = N->getOperand(0);
2212 SDValue N1 = N->getOperand(1);
2213 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2214 EVT VT = N->getValueType(0);
2217 // fold (mulhs x, 0) -> 0
2218 if (N1C && N1C->isNullValue())
2220 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2221 if (N1C && N1C->getAPIntValue() == 1)
2222 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2223 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2224 getShiftAmountTy(N0.getValueType())));
2225 // fold (mulhs x, undef) -> 0
2226 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2227 return DAG.getConstant(0, VT);
2229 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2231 if (VT.isSimple() && !VT.isVector()) {
2232 MVT Simple = VT.getSimpleVT();
2233 unsigned SimpleSize = Simple.getSizeInBits();
2234 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2235 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2236 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2237 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2238 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2239 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2240 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2241 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2248 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2249 SDValue N0 = N->getOperand(0);
2250 SDValue N1 = N->getOperand(1);
2251 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2252 EVT VT = N->getValueType(0);
2255 // fold (mulhu x, 0) -> 0
2256 if (N1C && N1C->isNullValue())
2258 // fold (mulhu x, 1) -> 0
2259 if (N1C && N1C->getAPIntValue() == 1)
2260 return DAG.getConstant(0, N0.getValueType());
2261 // fold (mulhu x, undef) -> 0
2262 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2263 return DAG.getConstant(0, VT);
2265 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2267 if (VT.isSimple() && !VT.isVector()) {
2268 MVT Simple = VT.getSimpleVT();
2269 unsigned SimpleSize = Simple.getSizeInBits();
2270 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2271 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2272 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2273 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2274 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2275 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2276 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2277 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2284 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2285 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2286 /// that are being performed. Return true if a simplification was made.
2288 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2290 // If the high half is not needed, just compute the low half.
2291 bool HiExists = N->hasAnyUseOfValue(1);
2293 (!LegalOperations ||
2294 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2295 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2296 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2297 return CombineTo(N, Res, Res);
2300 // If the low half is not needed, just compute the high half.
2301 bool LoExists = N->hasAnyUseOfValue(0);
2303 (!LegalOperations ||
2304 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2305 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2306 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2307 return CombineTo(N, Res, Res);
2310 // If both halves are used, return as it is.
2311 if (LoExists && HiExists)
2314 // If the two computed results can be simplified separately, separate them.
2316 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2317 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2318 AddToWorkList(Lo.getNode());
2319 SDValue LoOpt = combine(Lo.getNode());
2320 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2321 (!LegalOperations ||
2322 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2323 return CombineTo(N, LoOpt, LoOpt);
2327 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2328 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2329 AddToWorkList(Hi.getNode());
2330 SDValue HiOpt = combine(Hi.getNode());
2331 if (HiOpt.getNode() && HiOpt != Hi &&
2332 (!LegalOperations ||
2333 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2334 return CombineTo(N, HiOpt, HiOpt);
2340 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2341 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2342 if (Res.getNode()) return Res;
2344 EVT VT = N->getValueType(0);
2347 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2349 if (VT.isSimple() && !VT.isVector()) {
2350 MVT Simple = VT.getSimpleVT();
2351 unsigned SimpleSize = Simple.getSizeInBits();
2352 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2353 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2354 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2355 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2356 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2357 // Compute the high part as N1.
2358 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2359 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2360 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2361 // Compute the low part as N0.
2362 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2363 return CombineTo(N, Lo, Hi);
2370 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2371 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2372 if (Res.getNode()) return Res;
2374 EVT VT = N->getValueType(0);
2377 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2379 if (VT.isSimple() && !VT.isVector()) {
2380 MVT Simple = VT.getSimpleVT();
2381 unsigned SimpleSize = Simple.getSizeInBits();
2382 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2383 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2384 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2385 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2386 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2387 // Compute the high part as N1.
2388 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2389 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2390 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2391 // Compute the low part as N0.
2392 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2393 return CombineTo(N, Lo, Hi);
2400 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2401 // (smulo x, 2) -> (saddo x, x)
2402 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2403 if (C2->getAPIntValue() == 2)
2404 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2405 N->getOperand(0), N->getOperand(0));
2410 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2411 // (umulo x, 2) -> (uaddo x, x)
2412 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2413 if (C2->getAPIntValue() == 2)
2414 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2415 N->getOperand(0), N->getOperand(0));
2420 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2421 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2422 if (Res.getNode()) return Res;
2427 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2428 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2429 if (Res.getNode()) return Res;
2434 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2435 /// two operands of the same opcode, try to simplify it.
2436 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2437 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2438 EVT VT = N0.getValueType();
2439 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2441 // Bail early if none of these transforms apply.
2442 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2444 // For each of OP in AND/OR/XOR:
2445 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2446 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2447 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2448 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2450 // do not sink logical op inside of a vector extend, since it may combine
2452 EVT Op0VT = N0.getOperand(0).getValueType();
2453 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2454 N0.getOpcode() == ISD::SIGN_EXTEND ||
2455 // Avoid infinite looping with PromoteIntBinOp.
2456 (N0.getOpcode() == ISD::ANY_EXTEND &&
2457 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2458 (N0.getOpcode() == ISD::TRUNCATE &&
2459 (!TLI.isZExtFree(VT, Op0VT) ||
2460 !TLI.isTruncateFree(Op0VT, VT)) &&
2461 TLI.isTypeLegal(Op0VT))) &&
2463 Op0VT == N1.getOperand(0).getValueType() &&
2464 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2465 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2466 N0.getOperand(0).getValueType(),
2467 N0.getOperand(0), N1.getOperand(0));
2468 AddToWorkList(ORNode.getNode());
2469 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2472 // For each of OP in SHL/SRL/SRA/AND...
2473 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2474 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2475 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2476 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2477 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2478 N0.getOperand(1) == N1.getOperand(1)) {
2479 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2480 N0.getOperand(0).getValueType(),
2481 N0.getOperand(0), N1.getOperand(0));
2482 AddToWorkList(ORNode.getNode());
2483 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2484 ORNode, N0.getOperand(1));
2487 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2488 // Only perform this optimization after type legalization and before
2489 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2490 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2491 // we don't want to undo this promotion.
2492 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2494 if ((N0.getOpcode() == ISD::BITCAST ||
2495 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2496 Level == AfterLegalizeTypes) {
2497 SDValue In0 = N0.getOperand(0);
2498 SDValue In1 = N1.getOperand(0);
2499 EVT In0Ty = In0.getValueType();
2500 EVT In1Ty = In1.getValueType();
2502 // If both incoming values are integers, and the original types are the
2504 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2505 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2506 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2507 AddToWorkList(Op.getNode());
2512 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2513 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2514 // If both shuffles use the same mask, and both shuffle within a single
2515 // vector, then it is worthwhile to move the swizzle after the operation.
2516 // The type-legalizer generates this pattern when loading illegal
2517 // vector types from memory. In many cases this allows additional shuffle
2519 // There are other cases where moving the shuffle after the xor/and/or
2520 // is profitable even if shuffles don't perform a swizzle.
2521 // If both shuffles use the same mask, and both shuffles have the same first
2522 // or second operand, then it might still be profitable to move the shuffle
2523 // after the xor/and/or operation.
2524 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2525 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2526 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2528 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2529 "Inputs to shuffles are not the same type");
2531 // Check that both shuffles use the same mask. The masks are known to be of
2532 // the same length because the result vector type is the same.
2533 // Check also that shuffles have only one use to avoid introducing extra
2535 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2536 SVN0->getMask().equals(SVN1->getMask())) {
2537 SDValue ShOp = N0->getOperand(1);
2539 // Don't try to fold this node if it requires introducing a
2540 // build vector of all zeros that might be illegal at this stage.
2541 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2543 ShOp = DAG.getConstant(0, VT);
2548 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2549 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2550 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2551 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2552 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2553 N0->getOperand(0), N1->getOperand(0));
2554 AddToWorkList(NewNode.getNode());
2555 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2556 &SVN0->getMask()[0]);
2559 // Don't try to fold this node if it requires introducing a
2560 // build vector of all zeros that might be illegal at this stage.
2561 ShOp = N0->getOperand(0);
2562 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2564 ShOp = DAG.getConstant(0, VT);
2569 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2570 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2571 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2572 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2573 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2574 N0->getOperand(1), N1->getOperand(1));
2575 AddToWorkList(NewNode.getNode());
2576 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2577 &SVN0->getMask()[0]);
2585 SDValue DAGCombiner::visitAND(SDNode *N) {
2586 SDValue N0 = N->getOperand(0);
2587 SDValue N1 = N->getOperand(1);
2588 SDValue LL, LR, RL, RR, CC0, CC1;
2589 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2590 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2591 EVT VT = N1.getValueType();
2592 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2595 if (VT.isVector()) {
2596 SDValue FoldedVOp = SimplifyVBinOp(N);
2597 if (FoldedVOp.getNode()) return FoldedVOp;
2599 // fold (and x, 0) -> 0, vector edition
2600 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2602 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2605 // fold (and x, -1) -> x, vector edition
2606 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2608 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2612 // fold (and x, undef) -> 0
2613 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2614 return DAG.getConstant(0, VT);
2615 // fold (and c1, c2) -> c1&c2
2617 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2618 // canonicalize constant to RHS
2620 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2621 // fold (and x, -1) -> x
2622 if (N1C && N1C->isAllOnesValue())
2624 // if (and x, c) is known to be zero, return 0
2625 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2626 APInt::getAllOnesValue(BitWidth)))
2627 return DAG.getConstant(0, VT);
2629 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2632 // fold (and (or x, C), D) -> D if (C & D) == D
2633 if (N1C && N0.getOpcode() == ISD::OR)
2634 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2635 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2637 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2638 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2639 SDValue N0Op0 = N0.getOperand(0);
2640 APInt Mask = ~N1C->getAPIntValue();
2641 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2642 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2643 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2644 N0.getValueType(), N0Op0);
2646 // Replace uses of the AND with uses of the Zero extend node.
2649 // We actually want to replace all uses of the any_extend with the
2650 // zero_extend, to avoid duplicating things. This will later cause this
2651 // AND to be folded.
2652 CombineTo(N0.getNode(), Zext);
2653 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2656 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2657 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2658 // already be zero by virtue of the width of the base type of the load.
2660 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2662 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2663 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2664 N0.getOpcode() == ISD::LOAD) {
2665 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2666 N0 : N0.getOperand(0) );
2668 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2669 // This can be a pure constant or a vector splat, in which case we treat the
2670 // vector as a scalar and use the splat value.
2671 APInt Constant = APInt::getNullValue(1);
2672 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2673 Constant = C->getAPIntValue();
2674 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2675 APInt SplatValue, SplatUndef;
2676 unsigned SplatBitSize;
2678 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2679 SplatBitSize, HasAnyUndefs);
2681 // Undef bits can contribute to a possible optimisation if set, so
2683 SplatValue |= SplatUndef;
2685 // The splat value may be something like "0x00FFFFFF", which means 0 for
2686 // the first vector value and FF for the rest, repeating. We need a mask
2687 // that will apply equally to all members of the vector, so AND all the
2688 // lanes of the constant together.
2689 EVT VT = Vector->getValueType(0);
2690 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2692 // If the splat value has been compressed to a bitlength lower
2693 // than the size of the vector lane, we need to re-expand it to
2695 if (BitWidth > SplatBitSize)
2696 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2697 SplatBitSize < BitWidth;
2698 SplatBitSize = SplatBitSize * 2)
2699 SplatValue |= SplatValue.shl(SplatBitSize);
2701 Constant = APInt::getAllOnesValue(BitWidth);
2702 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2703 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2707 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2708 // actually legal and isn't going to get expanded, else this is a false
2710 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2711 Load->getMemoryVT());
2713 // Resize the constant to the same size as the original memory access before
2714 // extension. If it is still the AllOnesValue then this AND is completely
2717 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2720 switch (Load->getExtensionType()) {
2721 default: B = false; break;
2722 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2724 case ISD::NON_EXTLOAD: B = true; break;
2727 if (B && Constant.isAllOnesValue()) {
2728 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2729 // preserve semantics once we get rid of the AND.
2730 SDValue NewLoad(Load, 0);
2731 if (Load->getExtensionType() == ISD::EXTLOAD) {
2732 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2733 Load->getValueType(0), SDLoc(Load),
2734 Load->getChain(), Load->getBasePtr(),
2735 Load->getOffset(), Load->getMemoryVT(),
2736 Load->getMemOperand());
2737 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2738 if (Load->getNumValues() == 3) {
2739 // PRE/POST_INC loads have 3 values.
2740 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2741 NewLoad.getValue(2) };
2742 CombineTo(Load, To, 3, true);
2744 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2748 // Fold the AND away, taking care not to fold to the old load node if we
2750 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2752 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2755 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2756 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2757 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2758 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2760 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2761 LL.getValueType().isInteger()) {
2762 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2763 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2764 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2765 LR.getValueType(), LL, RL);
2766 AddToWorkList(ORNode.getNode());
2767 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2769 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2770 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2771 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2772 LR.getValueType(), LL, RL);
2773 AddToWorkList(ANDNode.getNode());
2774 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2776 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2777 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2778 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2779 LR.getValueType(), LL, RL);
2780 AddToWorkList(ORNode.getNode());
2781 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2784 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2785 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2786 Op0 == Op1 && LL.getValueType().isInteger() &&
2787 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2788 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2789 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2790 cast<ConstantSDNode>(RR)->isNullValue()))) {
2791 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2792 LL, DAG.getConstant(1, LL.getValueType()));
2793 AddToWorkList(ADDNode.getNode());
2794 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2795 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2797 // canonicalize equivalent to ll == rl
2798 if (LL == RR && LR == RL) {
2799 Op1 = ISD::getSetCCSwappedOperands(Op1);
2802 if (LL == RL && LR == RR) {
2803 bool isInteger = LL.getValueType().isInteger();
2804 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2805 if (Result != ISD::SETCC_INVALID &&
2806 (!LegalOperations ||
2807 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2808 TLI.isOperationLegal(ISD::SETCC,
2809 getSetCCResultType(N0.getSimpleValueType())))))
2810 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2815 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2816 if (N0.getOpcode() == N1.getOpcode()) {
2817 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2818 if (Tmp.getNode()) return Tmp;
2821 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2822 // fold (and (sra)) -> (and (srl)) when possible.
2823 if (!VT.isVector() &&
2824 SimplifyDemandedBits(SDValue(N, 0)))
2825 return SDValue(N, 0);
2827 // fold (zext_inreg (extload x)) -> (zextload x)
2828 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2829 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2830 EVT MemVT = LN0->getMemoryVT();
2831 // If we zero all the possible extended bits, then we can turn this into
2832 // a zextload if we are running before legalize or the operation is legal.
2833 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2834 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2835 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2836 ((!LegalOperations && !LN0->isVolatile()) ||
2837 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2838 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2839 LN0->getChain(), LN0->getBasePtr(),
2840 MemVT, LN0->getMemOperand());
2842 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2843 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2846 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2847 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2849 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2850 EVT MemVT = LN0->getMemoryVT();
2851 // If we zero all the possible extended bits, then we can turn this into
2852 // a zextload if we are running before legalize or the operation is legal.
2853 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2854 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2855 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2856 ((!LegalOperations && !LN0->isVolatile()) ||
2857 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2858 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2859 LN0->getChain(), LN0->getBasePtr(),
2860 MemVT, LN0->getMemOperand());
2862 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2863 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2867 // fold (and (load x), 255) -> (zextload x, i8)
2868 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2869 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2870 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2871 (N0.getOpcode() == ISD::ANY_EXTEND &&
2872 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2873 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2874 LoadSDNode *LN0 = HasAnyExt
2875 ? cast<LoadSDNode>(N0.getOperand(0))
2876 : cast<LoadSDNode>(N0);
2877 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2878 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2879 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2880 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2881 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2882 EVT LoadedVT = LN0->getMemoryVT();
2884 if (ExtVT == LoadedVT &&
2885 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2886 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2889 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2890 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2891 LN0->getMemOperand());
2893 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2894 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2897 // Do not change the width of a volatile load.
2898 // Do not generate loads of non-round integer types since these can
2899 // be expensive (and would be wrong if the type is not byte sized).
2900 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2901 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2902 EVT PtrType = LN0->getOperand(1).getValueType();
2904 unsigned Alignment = LN0->getAlignment();
2905 SDValue NewPtr = LN0->getBasePtr();
2907 // For big endian targets, we need to add an offset to the pointer
2908 // to load the correct bytes. For little endian systems, we merely
2909 // need to read fewer bytes from the same pointer.
2910 if (TLI.isBigEndian()) {
2911 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2912 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2913 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2914 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2915 NewPtr, DAG.getConstant(PtrOff, PtrType));
2916 Alignment = MinAlign(Alignment, PtrOff);
2919 AddToWorkList(NewPtr.getNode());
2921 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2923 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2924 LN0->getChain(), NewPtr,
2925 LN0->getPointerInfo(),
2926 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2927 Alignment, LN0->getTBAAInfo());
2929 CombineTo(LN0, Load, Load.getValue(1));
2930 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2936 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2937 VT.getSizeInBits() <= 64) {
2938 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2939 APInt ADDC = ADDI->getAPIntValue();
2940 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2941 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2942 // immediate for an add, but it is legal if its top c2 bits are set,
2943 // transform the ADD so the immediate doesn't need to be materialized
2945 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2946 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2947 SRLI->getZExtValue());
2948 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2950 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2952 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2953 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2954 CombineTo(N0.getNode(), NewAdd);
2955 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2963 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2964 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2965 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2966 N0.getOperand(1), false);
2967 if (BSwap.getNode())
2974 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2976 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2977 bool DemandHighBits) {
2978 if (!LegalOperations)
2981 EVT VT = N->getValueType(0);
2982 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2984 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2987 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2988 bool LookPassAnd0 = false;
2989 bool LookPassAnd1 = false;
2990 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2992 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2994 if (N0.getOpcode() == ISD::AND) {
2995 if (!N0.getNode()->hasOneUse())
2997 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2998 if (!N01C || N01C->getZExtValue() != 0xFF00)
3000 N0 = N0.getOperand(0);
3001 LookPassAnd0 = true;
3004 if (N1.getOpcode() == ISD::AND) {
3005 if (!N1.getNode()->hasOneUse())
3007 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3008 if (!N11C || N11C->getZExtValue() != 0xFF)
3010 N1 = N1.getOperand(0);
3011 LookPassAnd1 = true;
3014 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3016 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3018 if (!N0.getNode()->hasOneUse() ||
3019 !N1.getNode()->hasOneUse())
3022 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3023 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3026 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3029 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3030 SDValue N00 = N0->getOperand(0);
3031 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3032 if (!N00.getNode()->hasOneUse())
3034 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3035 if (!N001C || N001C->getZExtValue() != 0xFF)
3037 N00 = N00.getOperand(0);
3038 LookPassAnd0 = true;
3041 SDValue N10 = N1->getOperand(0);
3042 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3043 if (!N10.getNode()->hasOneUse())
3045 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3046 if (!N101C || N101C->getZExtValue() != 0xFF00)
3048 N10 = N10.getOperand(0);
3049 LookPassAnd1 = true;
3055 // Make sure everything beyond the low halfword gets set to zero since the SRL
3056 // 16 will clear the top bits.
3057 unsigned OpSizeInBits = VT.getSizeInBits();
3058 if (DemandHighBits && OpSizeInBits > 16) {
3059 // If the left-shift isn't masked out then the only way this is a bswap is
3060 // if all bits beyond the low 8 are 0. In that case the entire pattern
3061 // reduces to a left shift anyway: leave it for other parts of the combiner.
3065 // However, if the right shift isn't masked out then it might be because
3066 // it's not needed. See if we can spot that too.
3067 if (!LookPassAnd1 &&
3068 !DAG.MaskedValueIsZero(
3069 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3073 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3074 if (OpSizeInBits > 16)
3075 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3076 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3080 /// isBSwapHWordElement - Return true if the specified node is an element
3081 /// that makes up a 32-bit packed halfword byteswap. i.e.
3082 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3083 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3084 if (!N.getNode()->hasOneUse())
3087 unsigned Opc = N.getOpcode();
3088 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3091 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3096 switch (N1C->getZExtValue()) {
3099 case 0xFF: Num = 0; break;
3100 case 0xFF00: Num = 1; break;
3101 case 0xFF0000: Num = 2; break;
3102 case 0xFF000000: Num = 3; break;
3105 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3106 SDValue N0 = N.getOperand(0);
3107 if (Opc == ISD::AND) {
3108 if (Num == 0 || Num == 2) {
3110 // (x >> 8) & 0xff0000
3111 if (N0.getOpcode() != ISD::SRL)
3113 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3114 if (!C || C->getZExtValue() != 8)
3117 // (x << 8) & 0xff00
3118 // (x << 8) & 0xff000000
3119 if (N0.getOpcode() != ISD::SHL)
3121 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3122 if (!C || C->getZExtValue() != 8)
3125 } else if (Opc == ISD::SHL) {
3127 // (x & 0xff0000) << 8
3128 if (Num != 0 && Num != 2)
3130 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3131 if (!C || C->getZExtValue() != 8)
3133 } else { // Opc == ISD::SRL
3134 // (x & 0xff00) >> 8
3135 // (x & 0xff000000) >> 8
3136 if (Num != 1 && Num != 3)
3138 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3139 if (!C || C->getZExtValue() != 8)
3146 Parts[Num] = N0.getOperand(0).getNode();
3150 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3151 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3152 /// => (rotl (bswap x), 16)
3153 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3154 if (!LegalOperations)
3157 EVT VT = N->getValueType(0);
3160 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3163 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3165 // (or (or (and), (and)), (or (and), (and)))
3166 // (or (or (or (and), (and)), (and)), (and))
3167 if (N0.getOpcode() != ISD::OR)
3169 SDValue N00 = N0.getOperand(0);
3170 SDValue N01 = N0.getOperand(1);
3172 if (N1.getOpcode() == ISD::OR &&
3173 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3174 // (or (or (and), (and)), (or (and), (and)))
3175 SDValue N000 = N00.getOperand(0);
3176 if (!isBSwapHWordElement(N000, Parts))
3179 SDValue N001 = N00.getOperand(1);
3180 if (!isBSwapHWordElement(N001, Parts))
3182 SDValue N010 = N01.getOperand(0);
3183 if (!isBSwapHWordElement(N010, Parts))
3185 SDValue N011 = N01.getOperand(1);
3186 if (!isBSwapHWordElement(N011, Parts))
3189 // (or (or (or (and), (and)), (and)), (and))
3190 if (!isBSwapHWordElement(N1, Parts))
3192 if (!isBSwapHWordElement(N01, Parts))
3194 if (N00.getOpcode() != ISD::OR)
3196 SDValue N000 = N00.getOperand(0);
3197 if (!isBSwapHWordElement(N000, Parts))
3199 SDValue N001 = N00.getOperand(1);
3200 if (!isBSwapHWordElement(N001, Parts))
3204 // Make sure the parts are all coming from the same node.
3205 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3208 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3209 SDValue(Parts[0],0));
3211 // Result of the bswap should be rotated by 16. If it's not legal, then
3212 // do (x << 16) | (x >> 16).
3213 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3214 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3215 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3216 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3217 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3218 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3219 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3220 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3223 SDValue DAGCombiner::visitOR(SDNode *N) {
3224 SDValue N0 = N->getOperand(0);
3225 SDValue N1 = N->getOperand(1);
3226 SDValue LL, LR, RL, RR, CC0, CC1;
3227 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3228 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3229 EVT VT = N1.getValueType();
3232 if (VT.isVector()) {
3233 SDValue FoldedVOp = SimplifyVBinOp(N);
3234 if (FoldedVOp.getNode()) return FoldedVOp;
3236 // fold (or x, 0) -> x, vector edition
3237 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3239 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3242 // fold (or x, -1) -> -1, vector edition
3243 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3245 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3248 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3249 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3250 // Do this only if the resulting shuffle is legal.
3251 if (isa<ShuffleVectorSDNode>(N0) &&
3252 isa<ShuffleVectorSDNode>(N1) &&
3253 // Avoid folding a node with illegal type.
3254 TLI.isTypeLegal(VT) &&
3255 N0->getOperand(1) == N1->getOperand(1) &&
3256 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3257 bool CanFold = true;
3258 unsigned NumElts = VT.getVectorNumElements();
3259 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3260 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3261 // We construct two shuffle masks:
3262 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3263 // and N1 as the second operand.
3264 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3265 // and N0 as the second operand.
3266 // We do this because OR is commutable and therefore there might be
3267 // two ways to fold this node into a shuffle.
3268 SmallVector<int,4> Mask1;
3269 SmallVector<int,4> Mask2;
3271 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3272 int M0 = SV0->getMaskElt(i);
3273 int M1 = SV1->getMaskElt(i);
3275 // Both shuffle indexes are undef. Propagate Undef.
3276 if (M0 < 0 && M1 < 0) {
3277 Mask1.push_back(M0);
3278 Mask2.push_back(M0);
3282 if (M0 < 0 || M1 < 0 ||
3283 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3284 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3289 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3290 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3294 // Fold this sequence only if the resulting shuffle is 'legal'.
3295 if (TLI.isShuffleMaskLegal(Mask1, VT))
3296 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3297 N1->getOperand(0), &Mask1[0]);
3298 if (TLI.isShuffleMaskLegal(Mask2, VT))
3299 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3300 N0->getOperand(0), &Mask2[0]);
3305 // fold (or x, undef) -> -1
3306 if (!LegalOperations &&
3307 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3308 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3309 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3311 // fold (or c1, c2) -> c1|c2
3313 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3314 // canonicalize constant to RHS
3316 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3317 // fold (or x, 0) -> x
3318 if (N1C && N1C->isNullValue())
3320 // fold (or x, -1) -> -1
3321 if (N1C && N1C->isAllOnesValue())
3323 // fold (or x, c) -> c iff (x & ~c) == 0
3324 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3327 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3328 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3329 if (BSwap.getNode())
3331 BSwap = MatchBSwapHWordLow(N, N0, N1);
3332 if (BSwap.getNode())
3336 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3339 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3340 // iff (c1 & c2) == 0.
3341 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3342 isa<ConstantSDNode>(N0.getOperand(1))) {
3343 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3344 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3345 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3348 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3349 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3350 N0.getOperand(0), N1), COR);
3353 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3354 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3355 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3356 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3358 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3359 LL.getValueType().isInteger()) {
3360 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3361 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3362 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3363 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3364 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3365 LR.getValueType(), LL, RL);
3366 AddToWorkList(ORNode.getNode());
3367 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3369 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3370 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3371 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3372 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3373 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3374 LR.getValueType(), LL, RL);
3375 AddToWorkList(ANDNode.getNode());
3376 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3379 // canonicalize equivalent to ll == rl
3380 if (LL == RR && LR == RL) {
3381 Op1 = ISD::getSetCCSwappedOperands(Op1);
3384 if (LL == RL && LR == RR) {
3385 bool isInteger = LL.getValueType().isInteger();
3386 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3387 if (Result != ISD::SETCC_INVALID &&
3388 (!LegalOperations ||
3389 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3390 TLI.isOperationLegal(ISD::SETCC,
3391 getSetCCResultType(N0.getValueType())))))
3392 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3397 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3398 if (N0.getOpcode() == N1.getOpcode()) {
3399 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3400 if (Tmp.getNode()) return Tmp;
3403 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3404 if (N0.getOpcode() == ISD::AND &&
3405 N1.getOpcode() == ISD::AND &&
3406 N0.getOperand(1).getOpcode() == ISD::Constant &&
3407 N1.getOperand(1).getOpcode() == ISD::Constant &&
3408 // Don't increase # computations.
3409 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3410 // We can only do this xform if we know that bits from X that are set in C2
3411 // but not in C1 are already zero. Likewise for Y.
3412 const APInt &LHSMask =
3413 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3414 const APInt &RHSMask =
3415 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3417 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3418 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3419 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3420 N0.getOperand(0), N1.getOperand(0));
3421 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3422 DAG.getConstant(LHSMask | RHSMask, VT));
3426 // See if this is some rotate idiom.
3427 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3428 return SDValue(Rot, 0);
3430 // Simplify the operands using demanded-bits information.
3431 if (!VT.isVector() &&
3432 SimplifyDemandedBits(SDValue(N, 0)))
3433 return SDValue(N, 0);
3438 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3439 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3440 if (Op.getOpcode() == ISD::AND) {
3441 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3442 Mask = Op.getOperand(1);
3443 Op = Op.getOperand(0);
3449 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3457 // Return true if we can prove that, whenever Neg and Pos are both in the
3458 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3459 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3461 // (or (shift1 X, Neg), (shift2 X, Pos))
3463 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3464 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3465 // to consider shift amounts with defined behavior.
3466 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3467 // If OpSize is a power of 2 then:
3469 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3470 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3472 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3473 // for the stronger condition:
3475 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3477 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3478 // we can just replace Neg with Neg' for the rest of the function.
3480 // In other cases we check for the even stronger condition:
3482 // Neg == OpSize - Pos [B]
3484 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3485 // behavior if Pos == 0 (and consequently Neg == OpSize).
3487 // We could actually use [A] whenever OpSize is a power of 2, but the
3488 // only extra cases that it would match are those uninteresting ones
3489 // where Neg and Pos are never in range at the same time. E.g. for
3490 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3491 // as well as (sub 32, Pos), but:
3493 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3495 // always invokes undefined behavior for 32-bit X.
3497 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3498 unsigned MaskLoBits = 0;
3499 if (Neg.getOpcode() == ISD::AND &&
3500 isPowerOf2_64(OpSize) &&
3501 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3502 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3503 Neg = Neg.getOperand(0);
3504 MaskLoBits = Log2_64(OpSize);
3507 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3508 if (Neg.getOpcode() != ISD::SUB)
3510 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3513 SDValue NegOp1 = Neg.getOperand(1);
3515 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3516 // Pos'. The truncation is redundant for the purpose of the equality.
3518 Pos.getOpcode() == ISD::AND &&
3519 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3520 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3521 Pos = Pos.getOperand(0);
3523 // The condition we need is now:
3525 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3527 // If NegOp1 == Pos then we need:
3529 // OpSize & Mask == NegC & Mask
3531 // (because "x & Mask" is a truncation and distributes through subtraction).
3534 Width = NegC->getAPIntValue();
3535 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3536 // Then the condition we want to prove becomes:
3538 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3540 // which, again because "x & Mask" is a truncation, becomes:
3542 // NegC & Mask == (OpSize - PosC) & Mask
3543 // OpSize & Mask == (NegC + PosC) & Mask
3544 else if (Pos.getOpcode() == ISD::ADD &&
3545 Pos.getOperand(0) == NegOp1 &&
3546 Pos.getOperand(1).getOpcode() == ISD::Constant)
3547 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3548 NegC->getAPIntValue());
3552 // Now we just need to check that OpSize & Mask == Width & Mask.
3554 // Opsize & Mask is 0 since Mask is Opsize - 1.
3555 return Width.getLoBits(MaskLoBits) == 0;
3556 return Width == OpSize;
3559 // A subroutine of MatchRotate used once we have found an OR of two opposite
3560 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3561 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3562 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3563 // Neg with outer conversions stripped away.
3564 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3565 SDValue Neg, SDValue InnerPos,
3566 SDValue InnerNeg, unsigned PosOpcode,
3567 unsigned NegOpcode, SDLoc DL) {
3568 // fold (or (shl x, (*ext y)),
3569 // (srl x, (*ext (sub 32, y)))) ->
3570 // (rotl x, y) or (rotr x, (sub 32, y))
3572 // fold (or (shl x, (*ext (sub 32, y))),
3573 // (srl x, (*ext y))) ->
3574 // (rotr x, y) or (rotl x, (sub 32, y))
3575 EVT VT = Shifted.getValueType();
3576 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3577 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3578 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3579 HasPos ? Pos : Neg).getNode();
3585 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3586 // idioms for rotate, and if the target supports rotation instructions, generate
3588 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3589 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3590 EVT VT = LHS.getValueType();
3591 if (!TLI.isTypeLegal(VT)) return nullptr;
3593 // The target must have at least one rotate flavor.
3594 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3595 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3596 if (!HasROTL && !HasROTR) return nullptr;
3598 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3599 SDValue LHSShift; // The shift.
3600 SDValue LHSMask; // AND value if any.
3601 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3602 return nullptr; // Not part of a rotate.
3604 SDValue RHSShift; // The shift.
3605 SDValue RHSMask; // AND value if any.
3606 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3607 return nullptr; // Not part of a rotate.
3609 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3610 return nullptr; // Not shifting the same value.
3612 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3613 return nullptr; // Shifts must disagree.
3615 // Canonicalize shl to left side in a shl/srl pair.
3616 if (RHSShift.getOpcode() == ISD::SHL) {
3617 std::swap(LHS, RHS);
3618 std::swap(LHSShift, RHSShift);
3619 std::swap(LHSMask , RHSMask );
3622 unsigned OpSizeInBits = VT.getSizeInBits();
3623 SDValue LHSShiftArg = LHSShift.getOperand(0);
3624 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3625 SDValue RHSShiftArg = RHSShift.getOperand(0);
3626 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3628 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3629 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3630 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3631 RHSShiftAmt.getOpcode() == ISD::Constant) {
3632 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3633 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3634 if ((LShVal + RShVal) != OpSizeInBits)
3637 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3638 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3640 // If there is an AND of either shifted operand, apply it to the result.
3641 if (LHSMask.getNode() || RHSMask.getNode()) {
3642 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3644 if (LHSMask.getNode()) {
3645 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3646 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3648 if (RHSMask.getNode()) {
3649 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3650 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3653 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3656 return Rot.getNode();
3659 // If there is a mask here, and we have a variable shift, we can't be sure
3660 // that we're masking out the right stuff.
3661 if (LHSMask.getNode() || RHSMask.getNode())
3664 // If the shift amount is sign/zext/any-extended just peel it off.
3665 SDValue LExtOp0 = LHSShiftAmt;
3666 SDValue RExtOp0 = RHSShiftAmt;
3667 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3668 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3669 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3670 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3671 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3672 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3673 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3674 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3675 LExtOp0 = LHSShiftAmt.getOperand(0);
3676 RExtOp0 = RHSShiftAmt.getOperand(0);
3679 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3680 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3684 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3685 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3692 SDValue DAGCombiner::visitXOR(SDNode *N) {
3693 SDValue N0 = N->getOperand(0);
3694 SDValue N1 = N->getOperand(1);
3695 SDValue LHS, RHS, CC;
3696 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3697 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3698 EVT VT = N0.getValueType();
3701 if (VT.isVector()) {
3702 SDValue FoldedVOp = SimplifyVBinOp(N);
3703 if (FoldedVOp.getNode()) return FoldedVOp;
3705 // fold (xor x, 0) -> x, vector edition
3706 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3708 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3712 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3713 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3714 return DAG.getConstant(0, VT);
3715 // fold (xor x, undef) -> undef
3716 if (N0.getOpcode() == ISD::UNDEF)
3718 if (N1.getOpcode() == ISD::UNDEF)
3720 // fold (xor c1, c2) -> c1^c2
3722 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3723 // canonicalize constant to RHS
3725 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3726 // fold (xor x, 0) -> x
3727 if (N1C && N1C->isNullValue())
3730 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3734 // fold !(x cc y) -> (x !cc y)
3735 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3736 bool isInt = LHS.getValueType().isInteger();
3737 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3740 if (!LegalOperations ||
3741 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3742 switch (N0.getOpcode()) {
3744 llvm_unreachable("Unhandled SetCC Equivalent!");
3746 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3747 case ISD::SELECT_CC:
3748 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3749 N0.getOperand(3), NotCC);
3754 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3755 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3756 N0.getNode()->hasOneUse() &&
3757 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3758 SDValue V = N0.getOperand(0);
3759 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3760 DAG.getConstant(1, V.getValueType()));
3761 AddToWorkList(V.getNode());
3762 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3765 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3766 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3767 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3768 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3769 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3770 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3771 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3772 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3773 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3774 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3777 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3778 if (N1C && N1C->isAllOnesValue() &&
3779 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3780 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3781 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3782 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3783 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3784 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3785 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3786 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3789 // fold (xor (and x, y), y) -> (and (not x), y)
3790 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3791 N0->getOperand(1) == N1) {
3792 SDValue X = N0->getOperand(0);
3793 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3794 AddToWorkList(NotX.getNode());
3795 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3797 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3798 if (N1C && N0.getOpcode() == ISD::XOR) {
3799 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3800 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3802 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3803 DAG.getConstant(N1C->getAPIntValue() ^
3804 N00C->getAPIntValue(), VT));
3806 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3807 DAG.getConstant(N1C->getAPIntValue() ^
3808 N01C->getAPIntValue(), VT));
3810 // fold (xor x, x) -> 0
3812 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3814 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3815 if (N0.getOpcode() == N1.getOpcode()) {
3816 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3817 if (Tmp.getNode()) return Tmp;
3820 // Simplify the expression using non-local knowledge.
3821 if (!VT.isVector() &&
3822 SimplifyDemandedBits(SDValue(N, 0)))
3823 return SDValue(N, 0);
3828 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3829 /// the shift amount is a constant.
3830 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3831 // We can't and shouldn't fold opaque constants.
3832 if (Amt->isOpaque())
3835 SDNode *LHS = N->getOperand(0).getNode();
3836 if (!LHS->hasOneUse()) return SDValue();
3838 // We want to pull some binops through shifts, so that we have (and (shift))
3839 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3840 // thing happens with address calculations, so it's important to canonicalize
3842 bool HighBitSet = false; // Can we transform this if the high bit is set?
3844 switch (LHS->getOpcode()) {
3845 default: return SDValue();
3848 HighBitSet = false; // We can only transform sra if the high bit is clear.
3851 HighBitSet = true; // We can only transform sra if the high bit is set.
3854 if (N->getOpcode() != ISD::SHL)
3855 return SDValue(); // only shl(add) not sr[al](add).
3856 HighBitSet = false; // We can only transform sra if the high bit is clear.
3860 // We require the RHS of the binop to be a constant and not opaque as well.
3861 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3862 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3864 // FIXME: disable this unless the input to the binop is a shift by a constant.
3865 // If it is not a shift, it pessimizes some common cases like:
3867 // void foo(int *X, int i) { X[i & 1235] = 1; }
3868 // int bar(int *X, int i) { return X[i & 255]; }
3869 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3870 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3871 BinOpLHSVal->getOpcode() != ISD::SRA &&
3872 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3873 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3876 EVT VT = N->getValueType(0);
3878 // If this is a signed shift right, and the high bit is modified by the
3879 // logical operation, do not perform the transformation. The highBitSet
3880 // boolean indicates the value of the high bit of the constant which would
3881 // cause it to be modified for this operation.
3882 if (N->getOpcode() == ISD::SRA) {
3883 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3884 if (BinOpRHSSignSet != HighBitSet)
3888 if (!TLI.isDesirableToCommuteWithShift(LHS))
3891 // Fold the constants, shifting the binop RHS by the shift amount.
3892 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3894 LHS->getOperand(1), N->getOperand(1));
3895 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3897 // Create the new shift.
3898 SDValue NewShift = DAG.getNode(N->getOpcode(),
3899 SDLoc(LHS->getOperand(0)),
3900 VT, LHS->getOperand(0), N->getOperand(1));
3902 // Create the new binop.
3903 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3906 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3907 assert(N->getOpcode() == ISD::TRUNCATE);
3908 assert(N->getOperand(0).getOpcode() == ISD::AND);
3910 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3911 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3912 SDValue N01 = N->getOperand(0).getOperand(1);
3914 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3915 EVT TruncVT = N->getValueType(0);
3916 SDValue N00 = N->getOperand(0).getOperand(0);
3917 APInt TruncC = N01C->getAPIntValue();
3918 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3920 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3921 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3922 DAG.getConstant(TruncC, TruncVT));
3929 SDValue DAGCombiner::visitRotate(SDNode *N) {
3930 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3931 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3932 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3933 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3934 if (NewOp1.getNode())
3935 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3936 N->getOperand(0), NewOp1);
3941 SDValue DAGCombiner::visitSHL(SDNode *N) {
3942 SDValue N0 = N->getOperand(0);
3943 SDValue N1 = N->getOperand(1);
3944 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3945 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3946 EVT VT = N0.getValueType();
3947 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3950 if (VT.isVector()) {
3951 SDValue FoldedVOp = SimplifyVBinOp(N);
3952 if (FoldedVOp.getNode()) return FoldedVOp;
3954 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3955 // If setcc produces all-one true value then:
3956 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3957 if (N1CV && N1CV->isConstant()) {
3958 if (N0.getOpcode() == ISD::AND) {
3959 SDValue N00 = N0->getOperand(0);
3960 SDValue N01 = N0->getOperand(1);
3961 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3963 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
3964 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
3965 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3966 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3968 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3971 N1C = isConstOrConstSplat(N1);
3976 // fold (shl c1, c2) -> c1<<c2
3978 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3979 // fold (shl 0, x) -> 0
3980 if (N0C && N0C->isNullValue())
3982 // fold (shl x, c >= size(x)) -> undef
3983 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3984 return DAG.getUNDEF(VT);
3985 // fold (shl x, 0) -> x
3986 if (N1C && N1C->isNullValue())
3988 // fold (shl undef, x) -> 0
3989 if (N0.getOpcode() == ISD::UNDEF)
3990 return DAG.getConstant(0, VT);
3991 // if (shl x, c) is known to be zero, return 0
3992 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3993 APInt::getAllOnesValue(OpSizeInBits)))
3994 return DAG.getConstant(0, VT);
3995 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3996 if (N1.getOpcode() == ISD::TRUNCATE &&
3997 N1.getOperand(0).getOpcode() == ISD::AND) {
3998 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3999 if (NewOp1.getNode())
4000 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4003 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4004 return SDValue(N, 0);
4006 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4007 if (N1C && N0.getOpcode() == ISD::SHL) {
4008 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4009 uint64_t c1 = N0C1->getZExtValue();
4010 uint64_t c2 = N1C->getZExtValue();
4011 if (c1 + c2 >= OpSizeInBits)
4012 return DAG.getConstant(0, VT);
4013 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4014 DAG.getConstant(c1 + c2, N1.getValueType()));
4018 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4019 // For this to be valid, the second form must not preserve any of the bits
4020 // that are shifted out by the inner shift in the first form. This means
4021 // the outer shift size must be >= the number of bits added by the ext.
4022 // As a corollary, we don't care what kind of ext it is.
4023 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4024 N0.getOpcode() == ISD::ANY_EXTEND ||
4025 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4026 N0.getOperand(0).getOpcode() == ISD::SHL) {
4027 SDValue N0Op0 = N0.getOperand(0);
4028 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4029 uint64_t c1 = N0Op0C1->getZExtValue();
4030 uint64_t c2 = N1C->getZExtValue();
4031 EVT InnerShiftVT = N0Op0.getValueType();
4032 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4033 if (c2 >= OpSizeInBits - InnerShiftSize) {
4034 if (c1 + c2 >= OpSizeInBits)
4035 return DAG.getConstant(0, VT);
4036 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4037 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4038 N0Op0->getOperand(0)),
4039 DAG.getConstant(c1 + c2, N1.getValueType()));
4044 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4045 // Only fold this if the inner zext has no other uses to avoid increasing
4046 // the total number of instructions.
4047 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4048 N0.getOperand(0).getOpcode() == ISD::SRL) {
4049 SDValue N0Op0 = N0.getOperand(0);
4050 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4051 uint64_t c1 = N0Op0C1->getZExtValue();
4052 if (c1 < VT.getScalarSizeInBits()) {
4053 uint64_t c2 = N1C->getZExtValue();
4055 SDValue NewOp0 = N0.getOperand(0);
4056 EVT CountVT = NewOp0.getOperand(1).getValueType();
4057 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4058 NewOp0, DAG.getConstant(c2, CountVT));
4059 AddToWorkList(NewSHL.getNode());
4060 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4066 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4067 // (and (srl x, (sub c1, c2), MASK)
4068 // Only fold this if the inner shift has no other uses -- if it does, folding
4069 // this will increase the total number of instructions.
4070 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4071 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4072 uint64_t c1 = N0C1->getZExtValue();
4073 if (c1 < OpSizeInBits) {
4074 uint64_t c2 = N1C->getZExtValue();
4075 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4078 Mask = Mask.shl(c2 - c1);
4079 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4080 DAG.getConstant(c2 - c1, N1.getValueType()));
4082 Mask = Mask.lshr(c1 - c2);
4083 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4084 DAG.getConstant(c1 - c2, N1.getValueType()));
4086 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4087 DAG.getConstant(Mask, VT));
4091 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4092 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4093 unsigned BitSize = VT.getScalarSizeInBits();
4094 SDValue HiBitsMask =
4095 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4096 BitSize - N1C->getZExtValue()), VT);
4097 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4102 SDValue NewSHL = visitShiftByConstant(N, N1C);
4103 if (NewSHL.getNode())
4110 SDValue DAGCombiner::visitSRA(SDNode *N) {
4111 SDValue N0 = N->getOperand(0);
4112 SDValue N1 = N->getOperand(1);
4113 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4114 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4115 EVT VT = N0.getValueType();
4116 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4119 if (VT.isVector()) {
4120 SDValue FoldedVOp = SimplifyVBinOp(N);
4121 if (FoldedVOp.getNode()) return FoldedVOp;
4123 N1C = isConstOrConstSplat(N1);
4126 // fold (sra c1, c2) -> (sra c1, c2)
4128 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4129 // fold (sra 0, x) -> 0
4130 if (N0C && N0C->isNullValue())
4132 // fold (sra -1, x) -> -1
4133 if (N0C && N0C->isAllOnesValue())
4135 // fold (sra x, (setge c, size(x))) -> undef
4136 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4137 return DAG.getUNDEF(VT);
4138 // fold (sra x, 0) -> x
4139 if (N1C && N1C->isNullValue())
4141 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4143 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4144 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4145 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4147 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4148 ExtVT, VT.getVectorNumElements());
4149 if ((!LegalOperations ||
4150 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4151 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4152 N0.getOperand(0), DAG.getValueType(ExtVT));
4155 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4156 if (N1C && N0.getOpcode() == ISD::SRA) {
4157 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4158 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4159 if (Sum >= OpSizeInBits)
4160 Sum = OpSizeInBits - 1;
4161 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4162 DAG.getConstant(Sum, N1.getValueType()));
4166 // fold (sra (shl X, m), (sub result_size, n))
4167 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4168 // result_size - n != m.
4169 // If truncate is free for the target sext(shl) is likely to result in better
4171 if (N0.getOpcode() == ISD::SHL && N1C) {
4172 // Get the two constanst of the shifts, CN0 = m, CN = n.
4173 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4175 LLVMContext &Ctx = *DAG.getContext();
4176 // Determine what the truncate's result bitsize and type would be.
4177 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4180 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4182 // Determine the residual right-shift amount.
4183 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4185 // If the shift is not a no-op (in which case this should be just a sign
4186 // extend already), the truncated to type is legal, sign_extend is legal
4187 // on that type, and the truncate to that type is both legal and free,
4188 // perform the transform.
4189 if ((ShiftAmt > 0) &&
4190 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4191 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4192 TLI.isTruncateFree(VT, TruncVT)) {
4194 SDValue Amt = DAG.getConstant(ShiftAmt,
4195 getShiftAmountTy(N0.getOperand(0).getValueType()));
4196 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4197 N0.getOperand(0), Amt);
4198 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4200 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4201 N->getValueType(0), Trunc);
4206 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4207 if (N1.getOpcode() == ISD::TRUNCATE &&
4208 N1.getOperand(0).getOpcode() == ISD::AND) {
4209 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4210 if (NewOp1.getNode())
4211 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4214 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4215 // if c1 is equal to the number of bits the trunc removes
4216 if (N0.getOpcode() == ISD::TRUNCATE &&
4217 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4218 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4219 N0.getOperand(0).hasOneUse() &&
4220 N0.getOperand(0).getOperand(1).hasOneUse() &&
4222 SDValue N0Op0 = N0.getOperand(0);
4223 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4224 unsigned LargeShiftVal = LargeShift->getZExtValue();
4225 EVT LargeVT = N0Op0.getValueType();
4227 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4229 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4230 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4231 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4232 N0Op0.getOperand(0), Amt);
4233 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4238 // Simplify, based on bits shifted out of the LHS.
4239 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4240 return SDValue(N, 0);
4243 // If the sign bit is known to be zero, switch this to a SRL.
4244 if (DAG.SignBitIsZero(N0))
4245 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4248 SDValue NewSRA = visitShiftByConstant(N, N1C);
4249 if (NewSRA.getNode())
4256 SDValue DAGCombiner::visitSRL(SDNode *N) {
4257 SDValue N0 = N->getOperand(0);
4258 SDValue N1 = N->getOperand(1);
4259 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4260 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4261 EVT VT = N0.getValueType();
4262 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4265 if (VT.isVector()) {
4266 SDValue FoldedVOp = SimplifyVBinOp(N);
4267 if (FoldedVOp.getNode()) return FoldedVOp;
4269 N1C = isConstOrConstSplat(N1);
4272 // fold (srl c1, c2) -> c1 >>u c2
4274 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4275 // fold (srl 0, x) -> 0
4276 if (N0C && N0C->isNullValue())
4278 // fold (srl x, c >= size(x)) -> undef
4279 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4280 return DAG.getUNDEF(VT);
4281 // fold (srl x, 0) -> x
4282 if (N1C && N1C->isNullValue())
4284 // if (srl x, c) is known to be zero, return 0
4285 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4286 APInt::getAllOnesValue(OpSizeInBits)))
4287 return DAG.getConstant(0, VT);
4289 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4290 if (N1C && N0.getOpcode() == ISD::SRL) {
4291 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4292 uint64_t c1 = N01C->getZExtValue();
4293 uint64_t c2 = N1C->getZExtValue();
4294 if (c1 + c2 >= OpSizeInBits)
4295 return DAG.getConstant(0, VT);
4296 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4297 DAG.getConstant(c1 + c2, N1.getValueType()));
4301 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4302 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4303 N0.getOperand(0).getOpcode() == ISD::SRL &&
4304 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4306 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4307 uint64_t c2 = N1C->getZExtValue();
4308 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4309 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4310 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4311 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4312 if (c1 + OpSizeInBits == InnerShiftSize) {
4313 if (c1 + c2 >= InnerShiftSize)
4314 return DAG.getConstant(0, VT);
4315 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4316 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4317 N0.getOperand(0)->getOperand(0),
4318 DAG.getConstant(c1 + c2, ShiftCountVT)));
4322 // fold (srl (shl x, c), c) -> (and x, cst2)
4323 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4324 unsigned BitSize = N0.getScalarValueSizeInBits();
4325 if (BitSize <= 64) {
4326 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4327 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4328 DAG.getConstant(~0ULL >> ShAmt, VT));
4332 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4333 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4334 // Shifting in all undef bits?
4335 EVT SmallVT = N0.getOperand(0).getValueType();
4336 unsigned BitSize = SmallVT.getScalarSizeInBits();
4337 if (N1C->getZExtValue() >= BitSize)
4338 return DAG.getUNDEF(VT);
4340 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4341 uint64_t ShiftAmt = N1C->getZExtValue();
4342 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4344 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4345 AddToWorkList(SmallShift.getNode());
4346 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4347 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4348 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4349 DAG.getConstant(Mask, VT));
4353 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4354 // bit, which is unmodified by sra.
4355 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4356 if (N0.getOpcode() == ISD::SRA)
4357 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4360 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4361 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4362 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4363 APInt KnownZero, KnownOne;
4364 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4366 // If any of the input bits are KnownOne, then the input couldn't be all
4367 // zeros, thus the result of the srl will always be zero.
4368 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4370 // If all of the bits input the to ctlz node are known to be zero, then
4371 // the result of the ctlz is "32" and the result of the shift is one.
4372 APInt UnknownBits = ~KnownZero;
4373 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4375 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4376 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4377 // Okay, we know that only that the single bit specified by UnknownBits
4378 // could be set on input to the CTLZ node. If this bit is set, the SRL
4379 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4380 // to an SRL/XOR pair, which is likely to simplify more.
4381 unsigned ShAmt = UnknownBits.countTrailingZeros();
4382 SDValue Op = N0.getOperand(0);
4385 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4386 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4387 AddToWorkList(Op.getNode());
4390 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4391 Op, DAG.getConstant(1, VT));
4395 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4396 if (N1.getOpcode() == ISD::TRUNCATE &&
4397 N1.getOperand(0).getOpcode() == ISD::AND) {
4398 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4399 if (NewOp1.getNode())
4400 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4403 // fold operands of srl based on knowledge that the low bits are not
4405 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4406 return SDValue(N, 0);
4409 SDValue NewSRL = visitShiftByConstant(N, N1C);
4410 if (NewSRL.getNode())
4414 // Attempt to convert a srl of a load into a narrower zero-extending load.
4415 SDValue NarrowLoad = ReduceLoadWidth(N);
4416 if (NarrowLoad.getNode())
4419 // Here is a common situation. We want to optimize:
4422 // %b = and i32 %a, 2
4423 // %c = srl i32 %b, 1
4424 // brcond i32 %c ...
4430 // %c = setcc eq %b, 0
4433 // However when after the source operand of SRL is optimized into AND, the SRL
4434 // itself may not be optimized further. Look for it and add the BRCOND into
4436 if (N->hasOneUse()) {
4437 SDNode *Use = *N->use_begin();
4438 if (Use->getOpcode() == ISD::BRCOND)
4440 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4441 // Also look pass the truncate.
4442 Use = *Use->use_begin();
4443 if (Use->getOpcode() == ISD::BRCOND)
4451 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4452 SDValue N0 = N->getOperand(0);
4453 EVT VT = N->getValueType(0);
4455 // fold (ctlz c1) -> c2
4456 if (isa<ConstantSDNode>(N0))
4457 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4461 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4462 SDValue N0 = N->getOperand(0);
4463 EVT VT = N->getValueType(0);
4465 // fold (ctlz_zero_undef c1) -> c2
4466 if (isa<ConstantSDNode>(N0))
4467 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4471 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4472 SDValue N0 = N->getOperand(0);
4473 EVT VT = N->getValueType(0);
4475 // fold (cttz c1) -> c2
4476 if (isa<ConstantSDNode>(N0))
4477 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4481 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4482 SDValue N0 = N->getOperand(0);
4483 EVT VT = N->getValueType(0);
4485 // fold (cttz_zero_undef c1) -> c2
4486 if (isa<ConstantSDNode>(N0))
4487 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4491 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4492 SDValue N0 = N->getOperand(0);
4493 EVT VT = N->getValueType(0);
4495 // fold (ctpop c1) -> c2
4496 if (isa<ConstantSDNode>(N0))
4497 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4501 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4502 SDValue N0 = N->getOperand(0);
4503 SDValue N1 = N->getOperand(1);
4504 SDValue N2 = N->getOperand(2);
4505 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4506 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4507 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4508 EVT VT = N->getValueType(0);
4509 EVT VT0 = N0.getValueType();
4511 // fold (select C, X, X) -> X
4514 // fold (select true, X, Y) -> X
4515 if (N0C && !N0C->isNullValue())
4517 // fold (select false, X, Y) -> Y
4518 if (N0C && N0C->isNullValue())
4520 // fold (select C, 1, X) -> (or C, X)
4521 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4522 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4523 // fold (select C, 0, 1) -> (xor C, 1)
4524 // We can't do this reliably if integer based booleans have different contents
4525 // to floating point based booleans. This is because we can't tell whether we
4526 // have an integer-based boolean or a floating-point-based boolean unless we
4527 // can find the SETCC that produced it and inspect its operands. This is
4528 // fairly easy if C is the SETCC node, but it can potentially be
4529 // undiscoverable (or not reasonably discoverable). For example, it could be
4530 // in another basic block or it could require searching a complicated
4532 if (VT.isInteger() &&
4533 (VT0 == MVT::i1 || (VT0.isInteger() &&
4534 TLI.getBooleanContents(false, false) ==
4535 TLI.getBooleanContents(false, true) &&
4536 TLI.getBooleanContents(false, false) ==
4537 TargetLowering::ZeroOrOneBooleanContent)) &&
4538 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4541 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4542 N0, DAG.getConstant(1, VT0));
4543 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4544 N0, DAG.getConstant(1, VT0));
4545 AddToWorkList(XORNode.getNode());
4547 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4548 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4550 // fold (select C, 0, X) -> (and (not C), X)
4551 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4552 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4553 AddToWorkList(NOTNode.getNode());
4554 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4556 // fold (select C, X, 1) -> (or (not C), X)
4557 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4558 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4559 AddToWorkList(NOTNode.getNode());
4560 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4562 // fold (select C, X, 0) -> (and C, X)
4563 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4564 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4565 // fold (select X, X, Y) -> (or X, Y)
4566 // fold (select X, 1, Y) -> (or X, Y)
4567 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4568 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4569 // fold (select X, Y, X) -> (and X, Y)
4570 // fold (select X, Y, 0) -> (and X, Y)
4571 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4572 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4574 // If we can fold this based on the true/false value, do so.
4575 if (SimplifySelectOps(N, N1, N2))
4576 return SDValue(N, 0); // Don't revisit N.
4578 // fold selects based on a setcc into other things, such as min/max/abs
4579 if (N0.getOpcode() == ISD::SETCC) {
4580 if ((!LegalOperations &&
4581 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4582 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4583 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4584 N0.getOperand(0), N0.getOperand(1),
4585 N1, N2, N0.getOperand(2));
4586 return SimplifySelect(SDLoc(N), N0, N1, N2);
4593 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4596 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4598 // Split the inputs.
4599 SDValue Lo, Hi, LL, LH, RL, RH;
4600 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4601 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4603 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4604 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4606 return std::make_pair(Lo, Hi);
4609 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4610 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4611 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4613 SDValue Cond = N->getOperand(0);
4614 SDValue LHS = N->getOperand(1);
4615 SDValue RHS = N->getOperand(2);
4616 MVT VT = N->getSimpleValueType(0);
4617 int NumElems = VT.getVectorNumElements();
4618 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4619 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4620 Cond.getOpcode() == ISD::BUILD_VECTOR);
4622 // We're sure we have an even number of elements due to the
4623 // concat_vectors we have as arguments to vselect.
4624 // Skip BV elements until we find one that's not an UNDEF
4625 // After we find an UNDEF element, keep looping until we get to half the
4626 // length of the BV and see if all the non-undef nodes are the same.
4627 ConstantSDNode *BottomHalf = nullptr;
4628 for (int i = 0; i < NumElems / 2; ++i) {
4629 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4632 if (BottomHalf == nullptr)
4633 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4634 else if (Cond->getOperand(i).getNode() != BottomHalf)
4638 // Do the same for the second half of the BuildVector
4639 ConstantSDNode *TopHalf = nullptr;
4640 for (int i = NumElems / 2; i < NumElems; ++i) {
4641 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4644 if (TopHalf == nullptr)
4645 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4646 else if (Cond->getOperand(i).getNode() != TopHalf)
4650 assert(TopHalf && BottomHalf &&
4651 "One half of the selector was all UNDEFs and the other was all the "
4652 "same value. This should have been addressed before this function.");
4654 ISD::CONCAT_VECTORS, dl, VT,
4655 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4656 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4659 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4660 SDValue N0 = N->getOperand(0);
4661 SDValue N1 = N->getOperand(1);
4662 SDValue N2 = N->getOperand(2);
4665 // Canonicalize integer abs.
4666 // vselect (setg[te] X, 0), X, -X ->
4667 // vselect (setgt X, -1), X, -X ->
4668 // vselect (setl[te] X, 0), -X, X ->
4669 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4670 if (N0.getOpcode() == ISD::SETCC) {
4671 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4672 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4674 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4676 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4677 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4678 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4679 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4680 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4681 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4682 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4685 EVT VT = LHS.getValueType();
4686 SDValue Shift = DAG.getNode(
4687 ISD::SRA, DL, VT, LHS,
4688 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4689 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4690 AddToWorkList(Shift.getNode());
4691 AddToWorkList(Add.getNode());
4692 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4696 // If the VSELECT result requires splitting and the mask is provided by a
4697 // SETCC, then split both nodes and its operands before legalization. This
4698 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4699 // and enables future optimizations (e.g. min/max pattern matching on X86).
4700 if (N0.getOpcode() == ISD::SETCC) {
4701 EVT VT = N->getValueType(0);
4703 // Check if any splitting is required.
4704 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4705 TargetLowering::TypeSplitVector)
4708 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4709 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4710 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4711 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4713 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4714 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4716 // Add the new VSELECT nodes to the work list in case they need to be split
4718 AddToWorkList(Lo.getNode());
4719 AddToWorkList(Hi.getNode());
4721 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4724 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4725 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4727 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4728 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4731 // The ConvertSelectToConcatVector function is assuming both the above
4732 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4734 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4735 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4736 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4737 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4745 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4746 SDValue N0 = N->getOperand(0);
4747 SDValue N1 = N->getOperand(1);
4748 SDValue N2 = N->getOperand(2);
4749 SDValue N3 = N->getOperand(3);
4750 SDValue N4 = N->getOperand(4);
4751 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4753 // fold select_cc lhs, rhs, x, x, cc -> x
4757 // Determine if the condition we're dealing with is constant
4758 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4759 N0, N1, CC, SDLoc(N), false);
4760 if (SCC.getNode()) {
4761 AddToWorkList(SCC.getNode());
4763 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4764 if (!SCCC->isNullValue())
4765 return N2; // cond always true -> true val
4767 return N3; // cond always false -> false val
4770 // Fold to a simpler select_cc
4771 if (SCC.getOpcode() == ISD::SETCC)
4772 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4773 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4777 // If we can fold this based on the true/false value, do so.
4778 if (SimplifySelectOps(N, N2, N3))
4779 return SDValue(N, 0); // Don't revisit N.
4781 // fold select_cc into other things, such as min/max/abs
4782 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4785 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4786 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4787 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4791 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4792 // dag node into a ConstantSDNode or a build_vector of constants.
4793 // This function is called by the DAGCombiner when visiting sext/zext/aext
4794 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4795 // Vector extends are not folded if operations are legal; this is to
4796 // avoid introducing illegal build_vector dag nodes.
4797 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4798 SelectionDAG &DAG, bool LegalTypes,
4799 bool LegalOperations) {
4800 unsigned Opcode = N->getOpcode();
4801 SDValue N0 = N->getOperand(0);
4802 EVT VT = N->getValueType(0);
4804 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4805 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4807 // fold (sext c1) -> c1
4808 // fold (zext c1) -> c1
4809 // fold (aext c1) -> c1
4810 if (isa<ConstantSDNode>(N0))
4811 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4813 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4814 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4815 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4816 EVT SVT = VT.getScalarType();
4817 if (!(VT.isVector() &&
4818 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4819 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4822 // We can fold this node into a build_vector.
4823 unsigned VTBits = SVT.getSizeInBits();
4824 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4825 unsigned ShAmt = VTBits - EVTBits;
4826 SmallVector<SDValue, 8> Elts;
4827 unsigned NumElts = N0->getNumOperands();
4830 for (unsigned i=0; i != NumElts; ++i) {
4831 SDValue Op = N0->getOperand(i);
4832 if (Op->getOpcode() == ISD::UNDEF) {
4833 Elts.push_back(DAG.getUNDEF(SVT));
4837 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4838 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4839 if (Opcode == ISD::SIGN_EXTEND)
4840 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4843 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4847 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4850 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4851 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4852 // transformation. Returns true if extension are possible and the above
4853 // mentioned transformation is profitable.
4854 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4856 SmallVectorImpl<SDNode *> &ExtendNodes,
4857 const TargetLowering &TLI) {
4858 bool HasCopyToRegUses = false;
4859 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4860 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4861 UE = N0.getNode()->use_end();
4866 if (UI.getUse().getResNo() != N0.getResNo())
4868 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4869 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4870 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4871 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4872 // Sign bits will be lost after a zext.
4875 for (unsigned i = 0; i != 2; ++i) {
4876 SDValue UseOp = User->getOperand(i);
4879 if (!isa<ConstantSDNode>(UseOp))
4884 ExtendNodes.push_back(User);
4887 // If truncates aren't free and there are users we can't
4888 // extend, it isn't worthwhile.
4891 // Remember if this value is live-out.
4892 if (User->getOpcode() == ISD::CopyToReg)
4893 HasCopyToRegUses = true;
4896 if (HasCopyToRegUses) {
4897 bool BothLiveOut = false;
4898 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4900 SDUse &Use = UI.getUse();
4901 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4907 // Both unextended and extended values are live out. There had better be
4908 // a good reason for the transformation.
4909 return ExtendNodes.size();
4914 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4915 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4916 ISD::NodeType ExtType) {
4917 // Extend SetCC uses if necessary.
4918 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4919 SDNode *SetCC = SetCCs[i];
4920 SmallVector<SDValue, 4> Ops;
4922 for (unsigned j = 0; j != 2; ++j) {
4923 SDValue SOp = SetCC->getOperand(j);
4925 Ops.push_back(ExtLoad);
4927 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4930 Ops.push_back(SetCC->getOperand(2));
4931 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4935 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4936 SDValue N0 = N->getOperand(0);
4937 EVT VT = N->getValueType(0);
4939 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4941 return SDValue(Res, 0);
4943 // fold (sext (sext x)) -> (sext x)
4944 // fold (sext (aext x)) -> (sext x)
4945 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4946 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4949 if (N0.getOpcode() == ISD::TRUNCATE) {
4950 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4951 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4952 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4953 if (NarrowLoad.getNode()) {
4954 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4955 if (NarrowLoad.getNode() != N0.getNode()) {
4956 CombineTo(N0.getNode(), NarrowLoad);
4957 // CombineTo deleted the truncate, if needed, but not what's under it.
4960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4963 // See if the value being truncated is already sign extended. If so, just
4964 // eliminate the trunc/sext pair.
4965 SDValue Op = N0.getOperand(0);
4966 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4967 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4968 unsigned DestBits = VT.getScalarType().getSizeInBits();
4969 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4971 if (OpBits == DestBits) {
4972 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4973 // bits, it is already ready.
4974 if (NumSignBits > DestBits-MidBits)
4976 } else if (OpBits < DestBits) {
4977 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4978 // bits, just sext from i32.
4979 if (NumSignBits > OpBits-MidBits)
4980 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4982 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4983 // bits, just truncate to i32.
4984 if (NumSignBits > OpBits-MidBits)
4985 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4988 // fold (sext (truncate x)) -> (sextinreg x).
4989 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4990 N0.getValueType())) {
4991 if (OpBits < DestBits)
4992 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4993 else if (OpBits > DestBits)
4994 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4995 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4996 DAG.getValueType(N0.getValueType()));
5000 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5001 // None of the supported targets knows how to perform load and sign extend
5002 // on vectors in one instruction. We only perform this transformation on
5004 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5005 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5006 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5007 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5008 bool DoXform = true;
5009 SmallVector<SDNode*, 4> SetCCs;
5010 if (!N0.hasOneUse())
5011 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5013 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5014 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5016 LN0->getBasePtr(), N0.getValueType(),
5017 LN0->getMemOperand());
5018 CombineTo(N, ExtLoad);
5019 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5020 N0.getValueType(), ExtLoad);
5021 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5022 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5024 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5028 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5029 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5030 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5031 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5032 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5033 EVT MemVT = LN0->getMemoryVT();
5034 if ((!LegalOperations && !LN0->isVolatile()) ||
5035 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5036 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5038 LN0->getBasePtr(), MemVT,
5039 LN0->getMemOperand());
5040 CombineTo(N, ExtLoad);
5041 CombineTo(N0.getNode(),
5042 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5043 N0.getValueType(), ExtLoad),
5044 ExtLoad.getValue(1));
5045 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5049 // fold (sext (and/or/xor (load x), cst)) ->
5050 // (and/or/xor (sextload x), (sext cst))
5051 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5052 N0.getOpcode() == ISD::XOR) &&
5053 isa<LoadSDNode>(N0.getOperand(0)) &&
5054 N0.getOperand(1).getOpcode() == ISD::Constant &&
5055 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5056 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5057 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5058 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5059 bool DoXform = true;
5060 SmallVector<SDNode*, 4> SetCCs;
5061 if (!N0.hasOneUse())
5062 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5065 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5066 LN0->getChain(), LN0->getBasePtr(),
5068 LN0->getMemOperand());
5069 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5070 Mask = Mask.sext(VT.getSizeInBits());
5071 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5072 ExtLoad, DAG.getConstant(Mask, VT));
5073 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5074 SDLoc(N0.getOperand(0)),
5075 N0.getOperand(0).getValueType(), ExtLoad);
5077 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5078 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5080 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5085 if (N0.getOpcode() == ISD::SETCC) {
5086 EVT N0VT = N0.getOperand(0).getValueType();
5087 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5088 // Only do this before legalize for now.
5089 if (VT.isVector() && !LegalOperations &&
5090 TLI.getBooleanContents(N0VT) ==
5091 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5092 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5093 // of the same size as the compared operands. Only optimize sext(setcc())
5094 // if this is the case.
5095 EVT SVT = getSetCCResultType(N0VT);
5097 // We know that the # elements of the results is the same as the
5098 // # elements of the compare (and the # elements of the compare result
5099 // for that matter). Check to see that they are the same size. If so,
5100 // we know that the element size of the sext'd result matches the
5101 // element size of the compare operands.
5102 if (VT.getSizeInBits() == SVT.getSizeInBits())
5103 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5105 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5107 // If the desired elements are smaller or larger than the source
5108 // elements we can use a matching integer vector type and then
5109 // truncate/sign extend
5110 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5111 if (SVT == MatchingVectorType) {
5112 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5113 N0.getOperand(0), N0.getOperand(1),
5114 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5115 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5119 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5120 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5122 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5124 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5125 NegOne, DAG.getConstant(0, VT),
5126 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5127 if (SCC.getNode()) return SCC;
5129 if (!VT.isVector()) {
5130 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5131 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5133 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5134 SDValue SetCC = DAG.getSetCC(DL,
5136 N0.getOperand(0), N0.getOperand(1), CC);
5137 EVT SelectVT = getSetCCResultType(VT);
5138 return DAG.getSelect(DL, VT,
5139 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5140 NegOne, DAG.getConstant(0, VT));
5146 // fold (sext x) -> (zext x) if the sign bit is known zero.
5147 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5148 DAG.SignBitIsZero(N0))
5149 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5154 // isTruncateOf - If N is a truncate of some other value, return true, record
5155 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5156 // This function computes KnownZero to avoid a duplicated call to
5157 // computeKnownBits in the caller.
5158 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5161 if (N->getOpcode() == ISD::TRUNCATE) {
5162 Op = N->getOperand(0);
5163 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5167 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5168 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5171 SDValue Op0 = N->getOperand(0);
5172 SDValue Op1 = N->getOperand(1);
5173 assert(Op0.getValueType() == Op1.getValueType());
5175 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5176 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5177 if (COp0 && COp0->isNullValue())
5179 else if (COp1 && COp1->isNullValue())
5184 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5186 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5192 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5193 SDValue N0 = N->getOperand(0);
5194 EVT VT = N->getValueType(0);
5196 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5198 return SDValue(Res, 0);
5200 // fold (zext (zext x)) -> (zext x)
5201 // fold (zext (aext x)) -> (zext x)
5202 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5203 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5206 // fold (zext (truncate x)) -> (zext x) or
5207 // (zext (truncate x)) -> (truncate x)
5208 // This is valid when the truncated bits of x are already zero.
5209 // FIXME: We should extend this to work for vectors too.
5212 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5213 APInt TruncatedBits =
5214 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5215 APInt(Op.getValueSizeInBits(), 0) :
5216 APInt::getBitsSet(Op.getValueSizeInBits(),
5217 N0.getValueSizeInBits(),
5218 std::min(Op.getValueSizeInBits(),
5219 VT.getSizeInBits()));
5220 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5221 if (VT.bitsGT(Op.getValueType()))
5222 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5223 if (VT.bitsLT(Op.getValueType()))
5224 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5230 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5231 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5232 if (N0.getOpcode() == ISD::TRUNCATE) {
5233 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5234 if (NarrowLoad.getNode()) {
5235 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5236 if (NarrowLoad.getNode() != N0.getNode()) {
5237 CombineTo(N0.getNode(), NarrowLoad);
5238 // CombineTo deleted the truncate, if needed, but not what's under it.
5241 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5245 // fold (zext (truncate x)) -> (and x, mask)
5246 if (N0.getOpcode() == ISD::TRUNCATE &&
5247 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5249 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5250 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5251 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5252 if (NarrowLoad.getNode()) {
5253 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5254 if (NarrowLoad.getNode() != N0.getNode()) {
5255 CombineTo(N0.getNode(), NarrowLoad);
5256 // CombineTo deleted the truncate, if needed, but not what's under it.
5259 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5262 SDValue Op = N0.getOperand(0);
5263 if (Op.getValueType().bitsLT(VT)) {
5264 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5265 AddToWorkList(Op.getNode());
5266 } else if (Op.getValueType().bitsGT(VT)) {
5267 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5268 AddToWorkList(Op.getNode());
5270 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5271 N0.getValueType().getScalarType());
5274 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5275 // if either of the casts is not free.
5276 if (N0.getOpcode() == ISD::AND &&
5277 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5278 N0.getOperand(1).getOpcode() == ISD::Constant &&
5279 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5280 N0.getValueType()) ||
5281 !TLI.isZExtFree(N0.getValueType(), VT))) {
5282 SDValue X = N0.getOperand(0).getOperand(0);
5283 if (X.getValueType().bitsLT(VT)) {
5284 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5285 } else if (X.getValueType().bitsGT(VT)) {
5286 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5288 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5289 Mask = Mask.zext(VT.getSizeInBits());
5290 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5291 X, DAG.getConstant(Mask, VT));
5294 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5295 // None of the supported targets knows how to perform load and vector_zext
5296 // on vectors in one instruction. We only perform this transformation on
5298 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5299 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5300 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5301 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5302 bool DoXform = true;
5303 SmallVector<SDNode*, 4> SetCCs;
5304 if (!N0.hasOneUse())
5305 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5307 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5308 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5310 LN0->getBasePtr(), N0.getValueType(),
5311 LN0->getMemOperand());
5312 CombineTo(N, ExtLoad);
5313 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5314 N0.getValueType(), ExtLoad);
5315 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5317 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5319 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5323 // fold (zext (and/or/xor (load x), cst)) ->
5324 // (and/or/xor (zextload x), (zext cst))
5325 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5326 N0.getOpcode() == ISD::XOR) &&
5327 isa<LoadSDNode>(N0.getOperand(0)) &&
5328 N0.getOperand(1).getOpcode() == ISD::Constant &&
5329 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5330 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5331 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5332 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5333 bool DoXform = true;
5334 SmallVector<SDNode*, 4> SetCCs;
5335 if (!N0.hasOneUse())
5336 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5339 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5340 LN0->getChain(), LN0->getBasePtr(),
5342 LN0->getMemOperand());
5343 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5344 Mask = Mask.zext(VT.getSizeInBits());
5345 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5346 ExtLoad, DAG.getConstant(Mask, VT));
5347 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5348 SDLoc(N0.getOperand(0)),
5349 N0.getOperand(0).getValueType(), ExtLoad);
5351 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5352 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5354 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5359 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5360 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5361 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5362 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5363 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5364 EVT MemVT = LN0->getMemoryVT();
5365 if ((!LegalOperations && !LN0->isVolatile()) ||
5366 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5367 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5369 LN0->getBasePtr(), MemVT,
5370 LN0->getMemOperand());
5371 CombineTo(N, ExtLoad);
5372 CombineTo(N0.getNode(),
5373 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5375 ExtLoad.getValue(1));
5376 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5380 if (N0.getOpcode() == ISD::SETCC) {
5381 if (!LegalOperations && VT.isVector() &&
5382 N0.getValueType().getVectorElementType() == MVT::i1) {
5383 EVT N0VT = N0.getOperand(0).getValueType();
5384 if (getSetCCResultType(N0VT) == N0.getValueType())
5387 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5388 // Only do this before legalize for now.
5389 EVT EltVT = VT.getVectorElementType();
5390 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5391 DAG.getConstant(1, EltVT));
5392 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5393 // We know that the # elements of the results is the same as the
5394 // # elements of the compare (and the # elements of the compare result
5395 // for that matter). Check to see that they are the same size. If so,
5396 // we know that the element size of the sext'd result matches the
5397 // element size of the compare operands.
5398 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5399 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5401 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5402 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5405 // If the desired elements are smaller or larger than the source
5406 // elements we can use a matching integer vector type and then
5407 // truncate/sign extend
5408 EVT MatchingElementType =
5409 EVT::getIntegerVT(*DAG.getContext(),
5410 N0VT.getScalarType().getSizeInBits());
5411 EVT MatchingVectorType =
5412 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5413 N0VT.getVectorNumElements());
5415 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5417 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5418 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5419 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5420 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5423 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5425 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5426 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5427 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5428 if (SCC.getNode()) return SCC;
5431 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5432 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5433 isa<ConstantSDNode>(N0.getOperand(1)) &&
5434 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5436 SDValue ShAmt = N0.getOperand(1);
5437 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5438 if (N0.getOpcode() == ISD::SHL) {
5439 SDValue InnerZExt = N0.getOperand(0);
5440 // If the original shl may be shifting out bits, do not perform this
5442 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5443 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5444 if (ShAmtVal > KnownZeroBits)
5450 // Ensure that the shift amount is wide enough for the shifted value.
5451 if (VT.getSizeInBits() >= 256)
5452 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5454 return DAG.getNode(N0.getOpcode(), DL, VT,
5455 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5462 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5463 SDValue N0 = N->getOperand(0);
5464 EVT VT = N->getValueType(0);
5466 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5468 return SDValue(Res, 0);
5470 // fold (aext (aext x)) -> (aext x)
5471 // fold (aext (zext x)) -> (zext x)
5472 // fold (aext (sext x)) -> (sext x)
5473 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5474 N0.getOpcode() == ISD::ZERO_EXTEND ||
5475 N0.getOpcode() == ISD::SIGN_EXTEND)
5476 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5478 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5479 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5480 if (N0.getOpcode() == ISD::TRUNCATE) {
5481 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5482 if (NarrowLoad.getNode()) {
5483 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5484 if (NarrowLoad.getNode() != N0.getNode()) {
5485 CombineTo(N0.getNode(), NarrowLoad);
5486 // CombineTo deleted the truncate, if needed, but not what's under it.
5489 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5493 // fold (aext (truncate x))
5494 if (N0.getOpcode() == ISD::TRUNCATE) {
5495 SDValue TruncOp = N0.getOperand(0);
5496 if (TruncOp.getValueType() == VT)
5497 return TruncOp; // x iff x size == zext size.
5498 if (TruncOp.getValueType().bitsGT(VT))
5499 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5500 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5503 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5504 // if the trunc is not free.
5505 if (N0.getOpcode() == ISD::AND &&
5506 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5507 N0.getOperand(1).getOpcode() == ISD::Constant &&
5508 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5509 N0.getValueType())) {
5510 SDValue X = N0.getOperand(0).getOperand(0);
5511 if (X.getValueType().bitsLT(VT)) {
5512 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5513 } else if (X.getValueType().bitsGT(VT)) {
5514 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5516 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5517 Mask = Mask.zext(VT.getSizeInBits());
5518 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5519 X, DAG.getConstant(Mask, VT));
5522 // fold (aext (load x)) -> (aext (truncate (extload x)))
5523 // None of the supported targets knows how to perform load and any_ext
5524 // on vectors in one instruction. We only perform this transformation on
5526 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5527 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5528 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5529 bool DoXform = true;
5530 SmallVector<SDNode*, 4> SetCCs;
5531 if (!N0.hasOneUse())
5532 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5534 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5535 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5537 LN0->getBasePtr(), N0.getValueType(),
5538 LN0->getMemOperand());
5539 CombineTo(N, ExtLoad);
5540 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5541 N0.getValueType(), ExtLoad);
5542 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5543 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5545 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5549 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5550 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5551 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5552 if (N0.getOpcode() == ISD::LOAD &&
5553 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5555 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5556 ISD::LoadExtType ExtType = LN0->getExtensionType();
5557 EVT MemVT = LN0->getMemoryVT();
5558 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5559 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5560 VT, LN0->getChain(), LN0->getBasePtr(),
5561 MemVT, LN0->getMemOperand());
5562 CombineTo(N, ExtLoad);
5563 CombineTo(N0.getNode(),
5564 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5565 N0.getValueType(), ExtLoad),
5566 ExtLoad.getValue(1));
5567 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5571 if (N0.getOpcode() == ISD::SETCC) {
5573 // aext(setcc) -> vsetcc
5574 // aext(setcc) -> truncate(vsetcc)
5575 // aext(setcc) -> aext(vsetcc)
5576 // Only do this before legalize for now.
5577 if (VT.isVector() && !LegalOperations) {
5578 EVT N0VT = N0.getOperand(0).getValueType();
5579 // We know that the # elements of the results is the same as the
5580 // # elements of the compare (and the # elements of the compare result
5581 // for that matter). Check to see that they are the same size. If so,
5582 // we know that the element size of the sext'd result matches the
5583 // element size of the compare operands.
5584 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5585 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5587 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5588 // If the desired elements are smaller or larger than the source
5589 // elements we can use a matching integer vector type and then
5590 // truncate/any extend
5592 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5594 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5596 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5597 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5601 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5603 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5604 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5605 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5613 /// GetDemandedBits - See if the specified operand can be simplified with the
5614 /// knowledge that only the bits specified by Mask are used. If so, return the
5615 /// simpler operand, otherwise return a null SDValue.
5616 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5617 switch (V.getOpcode()) {
5619 case ISD::Constant: {
5620 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5621 assert(CV && "Const value should be ConstSDNode.");
5622 const APInt &CVal = CV->getAPIntValue();
5623 APInt NewVal = CVal & Mask;
5625 return DAG.getConstant(NewVal, V.getValueType());
5630 // If the LHS or RHS don't contribute bits to the or, drop them.
5631 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5632 return V.getOperand(1);
5633 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5634 return V.getOperand(0);
5637 // Only look at single-use SRLs.
5638 if (!V.getNode()->hasOneUse())
5640 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5641 // See if we can recursively simplify the LHS.
5642 unsigned Amt = RHSC->getZExtValue();
5644 // Watch out for shift count overflow though.
5645 if (Amt >= Mask.getBitWidth()) break;
5646 APInt NewMask = Mask << Amt;
5647 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5648 if (SimplifyLHS.getNode())
5649 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5650 SimplifyLHS, V.getOperand(1));
5656 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5657 /// bits and then truncated to a narrower type and where N is a multiple
5658 /// of number of bits of the narrower type, transform it to a narrower load
5659 /// from address + N / num of bits of new type. If the result is to be
5660 /// extended, also fold the extension to form a extending load.
5661 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5662 unsigned Opc = N->getOpcode();
5664 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5665 SDValue N0 = N->getOperand(0);
5666 EVT VT = N->getValueType(0);
5669 // This transformation isn't valid for vector loads.
5673 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5675 if (Opc == ISD::SIGN_EXTEND_INREG) {
5676 ExtType = ISD::SEXTLOAD;
5677 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5678 } else if (Opc == ISD::SRL) {
5679 // Another special-case: SRL is basically zero-extending a narrower value.
5680 ExtType = ISD::ZEXTLOAD;
5682 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5683 if (!N01) return SDValue();
5684 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5685 VT.getSizeInBits() - N01->getZExtValue());
5687 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5690 unsigned EVTBits = ExtVT.getSizeInBits();
5692 // Do not generate loads of non-round integer types since these can
5693 // be expensive (and would be wrong if the type is not byte sized).
5694 if (!ExtVT.isRound())
5698 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5699 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5700 ShAmt = N01->getZExtValue();
5701 // Is the shift amount a multiple of size of VT?
5702 if ((ShAmt & (EVTBits-1)) == 0) {
5703 N0 = N0.getOperand(0);
5704 // Is the load width a multiple of size of VT?
5705 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5709 // At this point, we must have a load or else we can't do the transform.
5710 if (!isa<LoadSDNode>(N0)) return SDValue();
5712 // Because a SRL must be assumed to *need* to zero-extend the high bits
5713 // (as opposed to anyext the high bits), we can't combine the zextload
5714 // lowering of SRL and an sextload.
5715 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5718 // If the shift amount is larger than the input type then we're not
5719 // accessing any of the loaded bytes. If the load was a zextload/extload
5720 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5721 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5726 // If the load is shifted left (and the result isn't shifted back right),
5727 // we can fold the truncate through the shift.
5728 unsigned ShLeftAmt = 0;
5729 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5730 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5731 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5732 ShLeftAmt = N01->getZExtValue();
5733 N0 = N0.getOperand(0);
5737 // If we haven't found a load, we can't narrow it. Don't transform one with
5738 // multiple uses, this would require adding a new load.
5739 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5742 // Don't change the width of a volatile load.
5743 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5744 if (LN0->isVolatile())
5747 // Verify that we are actually reducing a load width here.
5748 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5751 // For the transform to be legal, the load must produce only two values
5752 // (the value loaded and the chain). Don't transform a pre-increment
5753 // load, for example, which produces an extra value. Otherwise the
5754 // transformation is not equivalent, and the downstream logic to replace
5755 // uses gets things wrong.
5756 if (LN0->getNumValues() > 2)
5759 // If the load that we're shrinking is an extload and we're not just
5760 // discarding the extension we can't simply shrink the load. Bail.
5761 // TODO: It would be possible to merge the extensions in some cases.
5762 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5763 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5766 EVT PtrType = N0.getOperand(1).getValueType();
5768 if (PtrType == MVT::Untyped || PtrType.isExtended())
5769 // It's not possible to generate a constant of extended or untyped type.
5772 // For big endian targets, we need to adjust the offset to the pointer to
5773 // load the correct bytes.
5774 if (TLI.isBigEndian()) {
5775 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5776 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5777 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5780 uint64_t PtrOff = ShAmt / 8;
5781 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5782 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5783 PtrType, LN0->getBasePtr(),
5784 DAG.getConstant(PtrOff, PtrType));
5785 AddToWorkList(NewPtr.getNode());
5788 if (ExtType == ISD::NON_EXTLOAD)
5789 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5790 LN0->getPointerInfo().getWithOffset(PtrOff),
5791 LN0->isVolatile(), LN0->isNonTemporal(),
5792 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5794 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5795 LN0->getPointerInfo().getWithOffset(PtrOff),
5796 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5797 NewAlign, LN0->getTBAAInfo());
5799 // Replace the old load's chain with the new load's chain.
5800 WorkListRemover DeadNodes(*this);
5801 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5803 // Shift the result left, if we've swallowed a left shift.
5804 SDValue Result = Load;
5805 if (ShLeftAmt != 0) {
5806 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5807 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5809 // If the shift amount is as large as the result size (but, presumably,
5810 // no larger than the source) then the useful bits of the result are
5811 // zero; we can't simply return the shortened shift, because the result
5812 // of that operation is undefined.
5813 if (ShLeftAmt >= VT.getSizeInBits())
5814 Result = DAG.getConstant(0, VT);
5816 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5817 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5820 // Return the new loaded value.
5824 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5825 SDValue N0 = N->getOperand(0);
5826 SDValue N1 = N->getOperand(1);
5827 EVT VT = N->getValueType(0);
5828 EVT EVT = cast<VTSDNode>(N1)->getVT();
5829 unsigned VTBits = VT.getScalarType().getSizeInBits();
5830 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5832 // fold (sext_in_reg c1) -> c1
5833 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5834 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5836 // If the input is already sign extended, just drop the extension.
5837 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5840 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5841 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5842 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5843 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5844 N0.getOperand(0), N1);
5846 // fold (sext_in_reg (sext x)) -> (sext x)
5847 // fold (sext_in_reg (aext x)) -> (sext x)
5848 // if x is small enough.
5849 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5850 SDValue N00 = N0.getOperand(0);
5851 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5852 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5853 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5856 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5857 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5858 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5860 // fold operands of sext_in_reg based on knowledge that the top bits are not
5862 if (SimplifyDemandedBits(SDValue(N, 0)))
5863 return SDValue(N, 0);
5865 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5866 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5867 SDValue NarrowLoad = ReduceLoadWidth(N);
5868 if (NarrowLoad.getNode())
5871 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5872 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5873 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5874 if (N0.getOpcode() == ISD::SRL) {
5875 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5876 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5877 // We can turn this into an SRA iff the input to the SRL is already sign
5879 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5880 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5881 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5882 N0.getOperand(0), N0.getOperand(1));
5886 // fold (sext_inreg (extload x)) -> (sextload x)
5887 if (ISD::isEXTLoad(N0.getNode()) &&
5888 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5889 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5890 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5891 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5892 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5893 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5895 LN0->getBasePtr(), EVT,
5896 LN0->getMemOperand());
5897 CombineTo(N, ExtLoad);
5898 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5899 AddToWorkList(ExtLoad.getNode());
5900 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5902 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5903 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5905 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5906 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5907 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5908 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5909 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5911 LN0->getBasePtr(), EVT,
5912 LN0->getMemOperand());
5913 CombineTo(N, ExtLoad);
5914 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5915 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5918 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5919 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5920 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5921 N0.getOperand(1), false);
5922 if (BSwap.getNode())
5923 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5927 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5928 // into a build_vector.
5929 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5930 SmallVector<SDValue, 8> Elts;
5931 unsigned NumElts = N0->getNumOperands();
5932 unsigned ShAmt = VTBits - EVTBits;
5934 for (unsigned i = 0; i != NumElts; ++i) {
5935 SDValue Op = N0->getOperand(i);
5936 if (Op->getOpcode() == ISD::UNDEF) {
5941 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5942 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5943 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5944 Op.getValueType()));
5947 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5953 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5954 SDValue N0 = N->getOperand(0);
5955 EVT VT = N->getValueType(0);
5956 bool isLE = TLI.isLittleEndian();
5959 if (N0.getValueType() == N->getValueType(0))
5961 // fold (truncate c1) -> c1
5962 if (isa<ConstantSDNode>(N0))
5963 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5964 // fold (truncate (truncate x)) -> (truncate x)
5965 if (N0.getOpcode() == ISD::TRUNCATE)
5966 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5967 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5968 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5969 N0.getOpcode() == ISD::SIGN_EXTEND ||
5970 N0.getOpcode() == ISD::ANY_EXTEND) {
5971 if (N0.getOperand(0).getValueType().bitsLT(VT))
5972 // if the source is smaller than the dest, we still need an extend
5973 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5975 if (N0.getOperand(0).getValueType().bitsGT(VT))
5976 // if the source is larger than the dest, than we just need the truncate
5977 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5978 // if the source and dest are the same type, we can drop both the extend
5979 // and the truncate.
5980 return N0.getOperand(0);
5983 // Fold extract-and-trunc into a narrow extract. For example:
5984 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5985 // i32 y = TRUNCATE(i64 x)
5987 // v16i8 b = BITCAST (v2i64 val)
5988 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5990 // Note: We only run this optimization after type legalization (which often
5991 // creates this pattern) and before operation legalization after which
5992 // we need to be more careful about the vector instructions that we generate.
5993 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5994 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5996 EVT VecTy = N0.getOperand(0).getValueType();
5997 EVT ExTy = N0.getValueType();
5998 EVT TrTy = N->getValueType(0);
6000 unsigned NumElem = VecTy.getVectorNumElements();
6001 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6003 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6004 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6006 SDValue EltNo = N0->getOperand(1);
6007 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6008 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6009 EVT IndexTy = TLI.getVectorIdxTy();
6010 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6012 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6013 NVT, N0.getOperand(0));
6015 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6017 DAG.getConstant(Index, IndexTy));
6021 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6022 if (N0.getOpcode() == ISD::SELECT) {
6023 EVT SrcVT = N0.getValueType();
6024 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6025 TLI.isTruncateFree(SrcVT, VT)) {
6027 SDValue Cond = N0.getOperand(0);
6028 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6029 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6030 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6034 // Fold a series of buildvector, bitcast, and truncate if possible.
6036 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6037 // (2xi32 (buildvector x, y)).
6038 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6039 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6040 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6041 N0.getOperand(0).hasOneUse()) {
6043 SDValue BuildVect = N0.getOperand(0);
6044 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6045 EVT TruncVecEltTy = VT.getVectorElementType();
6047 // Check that the element types match.
6048 if (BuildVectEltTy == TruncVecEltTy) {
6049 // Now we only need to compute the offset of the truncated elements.
6050 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6051 unsigned TruncVecNumElts = VT.getVectorNumElements();
6052 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6054 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6055 "Invalid number of elements");
6057 SmallVector<SDValue, 8> Opnds;
6058 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6059 Opnds.push_back(BuildVect.getOperand(i));
6061 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6065 // See if we can simplify the input to this truncate through knowledge that
6066 // only the low bits are being used.
6067 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6068 // Currently we only perform this optimization on scalars because vectors
6069 // may have different active low bits.
6070 if (!VT.isVector()) {
6072 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6073 VT.getSizeInBits()));
6074 if (Shorter.getNode())
6075 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6077 // fold (truncate (load x)) -> (smaller load x)
6078 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6079 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6080 SDValue Reduced = ReduceLoadWidth(N);
6081 if (Reduced.getNode())
6083 // Handle the case where the load remains an extending load even
6084 // after truncation.
6085 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6086 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6087 if (!LN0->isVolatile() &&
6088 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6089 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6090 VT, LN0->getChain(), LN0->getBasePtr(),
6092 LN0->getMemOperand());
6093 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6098 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6099 // where ... are all 'undef'.
6100 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6101 SmallVector<EVT, 8> VTs;
6104 unsigned NumDefs = 0;
6106 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6107 SDValue X = N0.getOperand(i);
6108 if (X.getOpcode() != ISD::UNDEF) {
6113 // Stop if more than one members are non-undef.
6116 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6117 VT.getVectorElementType(),
6118 X.getValueType().getVectorNumElements()));
6122 return DAG.getUNDEF(VT);
6125 assert(V.getNode() && "The single defined operand is empty!");
6126 SmallVector<SDValue, 8> Opnds;
6127 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6129 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6132 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6133 AddToWorkList(NV.getNode());
6134 Opnds.push_back(NV);
6136 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6140 // Simplify the operands using demanded-bits information.
6141 if (!VT.isVector() &&
6142 SimplifyDemandedBits(SDValue(N, 0)))
6143 return SDValue(N, 0);
6148 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6149 SDValue Elt = N->getOperand(i);
6150 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6151 return Elt.getNode();
6152 return Elt.getOperand(Elt.getResNo()).getNode();
6155 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6156 /// if load locations are consecutive.
6157 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6158 assert(N->getOpcode() == ISD::BUILD_PAIR);
6160 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6161 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6162 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6163 LD1->getAddressSpace() != LD2->getAddressSpace())
6165 EVT LD1VT = LD1->getValueType(0);
6167 if (ISD::isNON_EXTLoad(LD2) &&
6169 // If both are volatile this would reduce the number of volatile loads.
6170 // If one is volatile it might be ok, but play conservative and bail out.
6171 !LD1->isVolatile() &&
6172 !LD2->isVolatile() &&
6173 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6174 unsigned Align = LD1->getAlignment();
6175 unsigned NewAlign = TLI.getDataLayout()->
6176 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6178 if (NewAlign <= Align &&
6179 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6180 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6181 LD1->getBasePtr(), LD1->getPointerInfo(),
6182 false, false, false, Align);
6188 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6189 SDValue N0 = N->getOperand(0);
6190 EVT VT = N->getValueType(0);
6192 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6193 // Only do this before legalize, since afterward the target may be depending
6194 // on the bitconvert.
6195 // First check to see if this is all constant.
6197 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6199 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6201 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6202 assert(!DestEltVT.isVector() &&
6203 "Element type of vector ValueType must not be vector!");
6205 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6208 // If the input is a constant, let getNode fold it.
6209 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6210 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6211 if (Res.getNode() != N) {
6212 if (!LegalOperations ||
6213 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6216 // Folding it resulted in an illegal node, and it's too late to
6217 // do that. Clean up the old node and forego the transformation.
6218 // Ideally this won't happen very often, because instcombine
6219 // and the earlier dagcombine runs (where illegal nodes are
6220 // permitted) should have folded most of them already.
6221 DAG.DeleteNode(Res.getNode());
6225 // (conv (conv x, t1), t2) -> (conv x, t2)
6226 if (N0.getOpcode() == ISD::BITCAST)
6227 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6230 // fold (conv (load x)) -> (load (conv*)x)
6231 // If the resultant load doesn't need a higher alignment than the original!
6232 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6233 // Do not change the width of a volatile load.
6234 !cast<LoadSDNode>(N0)->isVolatile() &&
6235 // Do not remove the cast if the types differ in endian layout.
6236 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6237 TLI.hasBigEndianPartOrdering(VT) &&
6238 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6239 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6240 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6241 unsigned Align = TLI.getDataLayout()->
6242 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6243 unsigned OrigAlign = LN0->getAlignment();
6245 if (Align <= OrigAlign) {
6246 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6247 LN0->getBasePtr(), LN0->getPointerInfo(),
6248 LN0->isVolatile(), LN0->isNonTemporal(),
6249 LN0->isInvariant(), OrigAlign,
6250 LN0->getTBAAInfo());
6252 CombineTo(N0.getNode(),
6253 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6254 N0.getValueType(), Load),
6260 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6261 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6262 // This often reduces constant pool loads.
6263 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6264 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6265 N0.getNode()->hasOneUse() && VT.isInteger() &&
6266 !VT.isVector() && !N0.getValueType().isVector()) {
6267 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6269 AddToWorkList(NewConv.getNode());
6271 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6272 if (N0.getOpcode() == ISD::FNEG)
6273 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6274 NewConv, DAG.getConstant(SignBit, VT));
6275 assert(N0.getOpcode() == ISD::FABS);
6276 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6277 NewConv, DAG.getConstant(~SignBit, VT));
6280 // fold (bitconvert (fcopysign cst, x)) ->
6281 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6282 // Note that we don't handle (copysign x, cst) because this can always be
6283 // folded to an fneg or fabs.
6284 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6285 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6286 VT.isInteger() && !VT.isVector()) {
6287 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6288 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6289 if (isTypeLegal(IntXVT)) {
6290 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6291 IntXVT, N0.getOperand(1));
6292 AddToWorkList(X.getNode());
6294 // If X has a different width than the result/lhs, sext it or truncate it.
6295 unsigned VTWidth = VT.getSizeInBits();
6296 if (OrigXWidth < VTWidth) {
6297 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6298 AddToWorkList(X.getNode());
6299 } else if (OrigXWidth > VTWidth) {
6300 // To get the sign bit in the right place, we have to shift it right
6301 // before truncating.
6302 X = DAG.getNode(ISD::SRL, SDLoc(X),
6303 X.getValueType(), X,
6304 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6305 AddToWorkList(X.getNode());
6306 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6307 AddToWorkList(X.getNode());
6310 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6311 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6312 X, DAG.getConstant(SignBit, VT));
6313 AddToWorkList(X.getNode());
6315 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6316 VT, N0.getOperand(0));
6317 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6318 Cst, DAG.getConstant(~SignBit, VT));
6319 AddToWorkList(Cst.getNode());
6321 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6325 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6326 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6327 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6328 if (CombineLD.getNode())
6335 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6336 EVT VT = N->getValueType(0);
6337 return CombineConsecutiveLoads(N, VT);
6340 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6341 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6342 /// destination element value type.
6343 SDValue DAGCombiner::
6344 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6345 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6347 // If this is already the right type, we're done.
6348 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6350 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6351 unsigned DstBitSize = DstEltVT.getSizeInBits();
6353 // If this is a conversion of N elements of one type to N elements of another
6354 // type, convert each element. This handles FP<->INT cases.
6355 if (SrcBitSize == DstBitSize) {
6356 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6357 BV->getValueType(0).getVectorNumElements());
6359 // Due to the FP element handling below calling this routine recursively,
6360 // we can end up with a scalar-to-vector node here.
6361 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6362 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6363 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6364 DstEltVT, BV->getOperand(0)));
6366 SmallVector<SDValue, 8> Ops;
6367 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6368 SDValue Op = BV->getOperand(i);
6369 // If the vector element type is not legal, the BUILD_VECTOR operands
6370 // are promoted and implicitly truncated. Make that explicit here.
6371 if (Op.getValueType() != SrcEltVT)
6372 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6373 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6375 AddToWorkList(Ops.back().getNode());
6377 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6380 // Otherwise, we're growing or shrinking the elements. To avoid having to
6381 // handle annoying details of growing/shrinking FP values, we convert them to
6383 if (SrcEltVT.isFloatingPoint()) {
6384 // Convert the input float vector to a int vector where the elements are the
6386 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6387 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6388 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6392 // Now we know the input is an integer vector. If the output is a FP type,
6393 // convert to integer first, then to FP of the right size.
6394 if (DstEltVT.isFloatingPoint()) {
6395 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6396 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6397 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6399 // Next, convert to FP elements of the same size.
6400 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6403 // Okay, we know the src/dst types are both integers of differing types.
6404 // Handling growing first.
6405 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6406 if (SrcBitSize < DstBitSize) {
6407 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6409 SmallVector<SDValue, 8> Ops;
6410 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6411 i += NumInputsPerOutput) {
6412 bool isLE = TLI.isLittleEndian();
6413 APInt NewBits = APInt(DstBitSize, 0);
6414 bool EltIsUndef = true;
6415 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6416 // Shift the previously computed bits over.
6417 NewBits <<= SrcBitSize;
6418 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6419 if (Op.getOpcode() == ISD::UNDEF) continue;
6422 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6423 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6427 Ops.push_back(DAG.getUNDEF(DstEltVT));
6429 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6432 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6433 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6436 // Finally, this must be the case where we are shrinking elements: each input
6437 // turns into multiple outputs.
6438 bool isS2V = ISD::isScalarToVector(BV);
6439 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6440 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6441 NumOutputsPerInput*BV->getNumOperands());
6442 SmallVector<SDValue, 8> Ops;
6444 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6445 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6446 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6447 Ops.push_back(DAG.getUNDEF(DstEltVT));
6451 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6452 getAPIntValue().zextOrTrunc(SrcBitSize);
6454 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6455 APInt ThisVal = OpVal.trunc(DstBitSize);
6456 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6457 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6458 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6459 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6461 OpVal = OpVal.lshr(DstBitSize);
6464 // For big endian targets, swap the order of the pieces of each element.
6465 if (TLI.isBigEndian())
6466 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6469 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6472 SDValue DAGCombiner::visitFADD(SDNode *N) {
6473 SDValue N0 = N->getOperand(0);
6474 SDValue N1 = N->getOperand(1);
6475 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6476 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6477 EVT VT = N->getValueType(0);
6480 if (VT.isVector()) {
6481 SDValue FoldedVOp = SimplifyVBinOp(N);
6482 if (FoldedVOp.getNode()) return FoldedVOp;
6485 // fold (fadd c1, c2) -> c1 + c2
6487 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6488 // canonicalize constant to RHS
6489 if (N0CFP && !N1CFP)
6490 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6491 // fold (fadd A, 0) -> A
6492 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6493 N1CFP->getValueAPF().isZero())
6495 // fold (fadd A, (fneg B)) -> (fsub A, B)
6496 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6497 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6498 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6499 GetNegatedExpression(N1, DAG, LegalOperations));
6500 // fold (fadd (fneg A), B) -> (fsub B, A)
6501 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6502 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6503 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6504 GetNegatedExpression(N0, DAG, LegalOperations));
6506 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6507 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6508 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6509 isa<ConstantFPSDNode>(N0.getOperand(1)))
6510 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6511 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6512 N0.getOperand(1), N1));
6514 // No FP constant should be created after legalization as Instruction
6515 // Selection pass has hard time in dealing with FP constant.
6517 // We don't need test this condition for transformation like following, as
6518 // the DAG being transformed implies it is legal to take FP constant as
6521 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6523 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6525 // If allow, fold (fadd (fneg x), x) -> 0.0
6526 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6527 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6528 return DAG.getConstantFP(0.0, VT);
6530 // If allow, fold (fadd x, (fneg x)) -> 0.0
6531 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6532 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6533 return DAG.getConstantFP(0.0, VT);
6535 // In unsafe math mode, we can fold chains of FADD's of the same value
6536 // into multiplications. This transform is not safe in general because
6537 // we are reducing the number of rounding steps.
6538 if (DAG.getTarget().Options.UnsafeFPMath &&
6539 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6541 if (N0.getOpcode() == ISD::FMUL) {
6542 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6543 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6545 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6546 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6547 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6549 DAG.getConstantFP(1.0, VT));
6550 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6554 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6555 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6556 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6558 DAG.getConstantFP(1.0, VT));
6559 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6563 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6564 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6565 N1.getOperand(0) == N1.getOperand(1) &&
6566 N0.getOperand(1) == N1.getOperand(0)) {
6567 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6569 DAG.getConstantFP(2.0, VT));
6570 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6571 N0.getOperand(1), NewCFP);
6574 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6575 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6576 N1.getOperand(0) == N1.getOperand(1) &&
6577 N0.getOperand(0) == N1.getOperand(0)) {
6578 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6580 DAG.getConstantFP(2.0, VT));
6581 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6582 N0.getOperand(0), NewCFP);
6586 if (N1.getOpcode() == ISD::FMUL) {
6587 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6588 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6590 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6591 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6592 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6594 DAG.getConstantFP(1.0, VT));
6595 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6599 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6600 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6601 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6603 DAG.getConstantFP(1.0, VT));
6604 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6609 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6610 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6611 N0.getOperand(0) == N0.getOperand(1) &&
6612 N1.getOperand(1) == N0.getOperand(0)) {
6613 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6615 DAG.getConstantFP(2.0, VT));
6616 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6617 N1.getOperand(1), NewCFP);
6620 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6621 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6622 N0.getOperand(0) == N0.getOperand(1) &&
6623 N1.getOperand(0) == N0.getOperand(0)) {
6624 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6626 DAG.getConstantFP(2.0, VT));
6627 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6628 N1.getOperand(0), NewCFP);
6632 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6633 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6634 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6635 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6636 (N0.getOperand(0) == N1))
6637 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6638 N1, DAG.getConstantFP(3.0, VT));
6641 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6642 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6643 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6644 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6645 N1.getOperand(0) == N0)
6646 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6647 N0, DAG.getConstantFP(3.0, VT));
6650 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6651 if (AllowNewFpConst &&
6652 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6653 N0.getOperand(0) == N0.getOperand(1) &&
6654 N1.getOperand(0) == N1.getOperand(1) &&
6655 N0.getOperand(0) == N1.getOperand(0))
6656 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6658 DAG.getConstantFP(4.0, VT));
6661 // FADD -> FMA combines:
6662 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6663 DAG.getTarget().Options.UnsafeFPMath) &&
6664 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6665 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6667 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6668 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6669 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6670 N0.getOperand(0), N0.getOperand(1), N1);
6672 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6673 // Note: Commutes FADD operands.
6674 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6675 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6676 N1.getOperand(0), N1.getOperand(1), N0);
6682 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6683 SDValue N0 = N->getOperand(0);
6684 SDValue N1 = N->getOperand(1);
6685 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6686 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6687 EVT VT = N->getValueType(0);
6691 if (VT.isVector()) {
6692 SDValue FoldedVOp = SimplifyVBinOp(N);
6693 if (FoldedVOp.getNode()) return FoldedVOp;
6696 // fold (fsub c1, c2) -> c1-c2
6698 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6699 // fold (fsub A, 0) -> A
6700 if (DAG.getTarget().Options.UnsafeFPMath &&
6701 N1CFP && N1CFP->getValueAPF().isZero())
6703 // fold (fsub 0, B) -> -B
6704 if (DAG.getTarget().Options.UnsafeFPMath &&
6705 N0CFP && N0CFP->getValueAPF().isZero()) {
6706 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6707 return GetNegatedExpression(N1, DAG, LegalOperations);
6708 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6709 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6711 // fold (fsub A, (fneg B)) -> (fadd A, B)
6712 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6713 return DAG.getNode(ISD::FADD, dl, VT, N0,
6714 GetNegatedExpression(N1, DAG, LegalOperations));
6716 // If 'unsafe math' is enabled, fold
6717 // (fsub x, x) -> 0.0 &
6718 // (fsub x, (fadd x, y)) -> (fneg y) &
6719 // (fsub x, (fadd y, x)) -> (fneg y)
6720 if (DAG.getTarget().Options.UnsafeFPMath) {
6722 return DAG.getConstantFP(0.0f, VT);
6724 if (N1.getOpcode() == ISD::FADD) {
6725 SDValue N10 = N1->getOperand(0);
6726 SDValue N11 = N1->getOperand(1);
6728 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6729 &DAG.getTarget().Options))
6730 return GetNegatedExpression(N11, DAG, LegalOperations);
6732 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6733 &DAG.getTarget().Options))
6734 return GetNegatedExpression(N10, DAG, LegalOperations);
6738 // FSUB -> FMA combines:
6739 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6740 DAG.getTarget().Options.UnsafeFPMath) &&
6741 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6742 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6744 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6745 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6746 return DAG.getNode(ISD::FMA, dl, VT,
6747 N0.getOperand(0), N0.getOperand(1),
6748 DAG.getNode(ISD::FNEG, dl, VT, N1));
6750 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6751 // Note: Commutes FSUB operands.
6752 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6753 return DAG.getNode(ISD::FMA, dl, VT,
6754 DAG.getNode(ISD::FNEG, dl, VT,
6756 N1.getOperand(1), N0);
6758 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6759 if (N0.getOpcode() == ISD::FNEG &&
6760 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6761 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6762 SDValue N00 = N0.getOperand(0).getOperand(0);
6763 SDValue N01 = N0.getOperand(0).getOperand(1);
6764 return DAG.getNode(ISD::FMA, dl, VT,
6765 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6766 DAG.getNode(ISD::FNEG, dl, VT, N1));
6773 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6774 SDValue N0 = N->getOperand(0);
6775 SDValue N1 = N->getOperand(1);
6776 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6777 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6778 EVT VT = N->getValueType(0);
6779 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6782 if (VT.isVector()) {
6783 SDValue FoldedVOp = SimplifyVBinOp(N);
6784 if (FoldedVOp.getNode()) return FoldedVOp;
6787 // fold (fmul c1, c2) -> c1*c2
6789 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6790 // canonicalize constant to RHS
6791 if (N0CFP && !N1CFP)
6792 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6793 // fold (fmul A, 0) -> 0
6794 if (DAG.getTarget().Options.UnsafeFPMath &&
6795 N1CFP && N1CFP->getValueAPF().isZero())
6797 // fold (fmul A, 0) -> 0, vector edition.
6798 if (DAG.getTarget().Options.UnsafeFPMath &&
6799 ISD::isBuildVectorAllZeros(N1.getNode()))
6801 // fold (fmul A, 1.0) -> A
6802 if (N1CFP && N1CFP->isExactlyValue(1.0))
6804 // fold (fmul X, 2.0) -> (fadd X, X)
6805 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6806 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6807 // fold (fmul X, -1.0) -> (fneg X)
6808 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6809 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6810 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6812 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6813 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6814 &DAG.getTarget().Options)) {
6815 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6816 &DAG.getTarget().Options)) {
6817 // Both can be negated for free, check to see if at least one is cheaper
6819 if (LHSNeg == 2 || RHSNeg == 2)
6820 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6821 GetNegatedExpression(N0, DAG, LegalOperations),
6822 GetNegatedExpression(N1, DAG, LegalOperations));
6826 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6827 if (DAG.getTarget().Options.UnsafeFPMath &&
6828 N1CFP && N0.getOpcode() == ISD::FMUL &&
6829 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6830 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6831 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6832 N0.getOperand(1), N1));
6837 SDValue DAGCombiner::visitFMA(SDNode *N) {
6838 SDValue N0 = N->getOperand(0);
6839 SDValue N1 = N->getOperand(1);
6840 SDValue N2 = N->getOperand(2);
6841 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6842 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6843 EVT VT = N->getValueType(0);
6846 if (DAG.getTarget().Options.UnsafeFPMath) {
6847 if (N0CFP && N0CFP->isZero())
6849 if (N1CFP && N1CFP->isZero())
6852 if (N0CFP && N0CFP->isExactlyValue(1.0))
6853 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6854 if (N1CFP && N1CFP->isExactlyValue(1.0))
6855 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6857 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6858 if (N0CFP && !N1CFP)
6859 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6861 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6862 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6863 N2.getOpcode() == ISD::FMUL &&
6864 N0 == N2.getOperand(0) &&
6865 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6866 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6867 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6871 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6872 if (DAG.getTarget().Options.UnsafeFPMath &&
6873 N0.getOpcode() == ISD::FMUL && N1CFP &&
6874 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6875 return DAG.getNode(ISD::FMA, dl, VT,
6877 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6881 // (fma x, 1, y) -> (fadd x, y)
6882 // (fma x, -1, y) -> (fadd (fneg x), y)
6884 if (N1CFP->isExactlyValue(1.0))
6885 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6887 if (N1CFP->isExactlyValue(-1.0) &&
6888 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6889 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6890 AddToWorkList(RHSNeg.getNode());
6891 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6895 // (fma x, c, x) -> (fmul x, (c+1))
6896 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6897 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6898 DAG.getNode(ISD::FADD, dl, VT,
6899 N1, DAG.getConstantFP(1.0, VT)));
6901 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6902 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6903 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6904 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6905 DAG.getNode(ISD::FADD, dl, VT,
6906 N1, DAG.getConstantFP(-1.0, VT)));
6912 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6913 SDValue N0 = N->getOperand(0);
6914 SDValue N1 = N->getOperand(1);
6915 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6916 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6917 EVT VT = N->getValueType(0);
6918 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6921 if (VT.isVector()) {
6922 SDValue FoldedVOp = SimplifyVBinOp(N);
6923 if (FoldedVOp.getNode()) return FoldedVOp;
6926 // fold (fdiv c1, c2) -> c1/c2
6928 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6930 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6931 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6932 // Compute the reciprocal 1.0 / c2.
6933 APFloat N1APF = N1CFP->getValueAPF();
6934 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6935 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6936 // Only do the transform if the reciprocal is a legal fp immediate that
6937 // isn't too nasty (eg NaN, denormal, ...).
6938 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6939 (!LegalOperations ||
6940 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6941 // backend)... we should handle this gracefully after Legalize.
6942 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6943 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6944 TLI.isFPImmLegal(Recip, VT)))
6945 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6946 DAG.getConstantFP(Recip, VT));
6949 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6950 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6951 &DAG.getTarget().Options)) {
6952 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6953 &DAG.getTarget().Options)) {
6954 // Both can be negated for free, check to see if at least one is cheaper
6956 if (LHSNeg == 2 || RHSNeg == 2)
6957 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6958 GetNegatedExpression(N0, DAG, LegalOperations),
6959 GetNegatedExpression(N1, DAG, LegalOperations));
6966 SDValue DAGCombiner::visitFREM(SDNode *N) {
6967 SDValue N0 = N->getOperand(0);
6968 SDValue N1 = N->getOperand(1);
6969 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6970 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6971 EVT VT = N->getValueType(0);
6973 // fold (frem c1, c2) -> fmod(c1,c2)
6975 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6980 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6981 SDValue N0 = N->getOperand(0);
6982 SDValue N1 = N->getOperand(1);
6983 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6984 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6985 EVT VT = N->getValueType(0);
6987 if (N0CFP && N1CFP) // Constant fold
6988 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6991 const APFloat& V = N1CFP->getValueAPF();
6992 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6993 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6994 if (!V.isNegative()) {
6995 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6996 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6998 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6999 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7000 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7004 // copysign(fabs(x), y) -> copysign(x, y)
7005 // copysign(fneg(x), y) -> copysign(x, y)
7006 // copysign(copysign(x,z), y) -> copysign(x, y)
7007 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7008 N0.getOpcode() == ISD::FCOPYSIGN)
7009 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7010 N0.getOperand(0), N1);
7012 // copysign(x, abs(y)) -> abs(x)
7013 if (N1.getOpcode() == ISD::FABS)
7014 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7016 // copysign(x, copysign(y,z)) -> copysign(x, z)
7017 if (N1.getOpcode() == ISD::FCOPYSIGN)
7018 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7019 N0, N1.getOperand(1));
7021 // copysign(x, fp_extend(y)) -> copysign(x, y)
7022 // copysign(x, fp_round(y)) -> copysign(x, y)
7023 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7024 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7025 N0, N1.getOperand(0));
7030 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7031 SDValue N0 = N->getOperand(0);
7032 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7033 EVT VT = N->getValueType(0);
7034 EVT OpVT = N0.getValueType();
7036 // fold (sint_to_fp c1) -> c1fp
7038 // ...but only if the target supports immediate floating-point values
7039 (!LegalOperations ||
7040 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7041 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7043 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7044 // but UINT_TO_FP is legal on this target, try to convert.
7045 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7046 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7047 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7048 if (DAG.SignBitIsZero(N0))
7049 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7052 // The next optimizations are desirable only if SELECT_CC can be lowered.
7053 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7054 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7055 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7057 (!LegalOperations ||
7058 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7060 { N0.getOperand(0), N0.getOperand(1),
7061 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7063 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7066 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7067 // (select_cc x, y, 1.0, 0.0,, cc)
7068 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7069 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7070 (!LegalOperations ||
7071 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7073 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7074 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7075 N0.getOperand(0).getOperand(2) };
7076 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7083 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7084 SDValue N0 = N->getOperand(0);
7085 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7086 EVT VT = N->getValueType(0);
7087 EVT OpVT = N0.getValueType();
7089 // fold (uint_to_fp c1) -> c1fp
7091 // ...but only if the target supports immediate floating-point values
7092 (!LegalOperations ||
7093 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7094 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7096 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7097 // but SINT_TO_FP is legal on this target, try to convert.
7098 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7099 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7100 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7101 if (DAG.SignBitIsZero(N0))
7102 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7105 // The next optimizations are desirable only if SELECT_CC can be lowered.
7106 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7107 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7109 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7110 (!LegalOperations ||
7111 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7113 { N0.getOperand(0), N0.getOperand(1),
7114 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7116 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7123 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7124 SDValue N0 = N->getOperand(0);
7125 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7126 EVT VT = N->getValueType(0);
7128 // fold (fp_to_sint c1fp) -> c1
7130 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7135 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7136 SDValue N0 = N->getOperand(0);
7137 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7138 EVT VT = N->getValueType(0);
7140 // fold (fp_to_uint c1fp) -> c1
7142 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7147 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7148 SDValue N0 = N->getOperand(0);
7149 SDValue N1 = N->getOperand(1);
7150 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7151 EVT VT = N->getValueType(0);
7153 // fold (fp_round c1fp) -> c1fp
7155 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7157 // fold (fp_round (fp_extend x)) -> x
7158 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7159 return N0.getOperand(0);
7161 // fold (fp_round (fp_round x)) -> (fp_round x)
7162 if (N0.getOpcode() == ISD::FP_ROUND) {
7163 // This is a value preserving truncation if both round's are.
7164 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7165 N0.getNode()->getConstantOperandVal(1) == 1;
7166 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7167 DAG.getIntPtrConstant(IsTrunc));
7170 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7171 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7172 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7173 N0.getOperand(0), N1);
7174 AddToWorkList(Tmp.getNode());
7175 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7176 Tmp, N0.getOperand(1));
7182 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7183 SDValue N0 = N->getOperand(0);
7184 EVT VT = N->getValueType(0);
7185 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7186 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7188 // fold (fp_round_inreg c1fp) -> c1fp
7189 if (N0CFP && isTypeLegal(EVT)) {
7190 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7191 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7197 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7198 SDValue N0 = N->getOperand(0);
7199 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7200 EVT VT = N->getValueType(0);
7202 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7203 if (N->hasOneUse() &&
7204 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7207 // fold (fp_extend c1fp) -> c1fp
7209 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7211 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7213 if (N0.getOpcode() == ISD::FP_ROUND
7214 && N0.getNode()->getConstantOperandVal(1) == 1) {
7215 SDValue In = N0.getOperand(0);
7216 if (In.getValueType() == VT) return In;
7217 if (VT.bitsLT(In.getValueType()))
7218 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7219 In, N0.getOperand(1));
7220 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7223 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7224 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7225 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7226 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7227 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7229 LN0->getBasePtr(), N0.getValueType(),
7230 LN0->getMemOperand());
7231 CombineTo(N, ExtLoad);
7232 CombineTo(N0.getNode(),
7233 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7234 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7235 ExtLoad.getValue(1));
7236 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7242 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7243 SDValue N0 = N->getOperand(0);
7244 EVT VT = N->getValueType(0);
7246 if (VT.isVector()) {
7247 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7248 if (FoldedVOp.getNode()) return FoldedVOp;
7251 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7252 &DAG.getTarget().Options))
7253 return GetNegatedExpression(N0, DAG, LegalOperations);
7255 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7256 // constant pool values.
7257 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7259 N0.getNode()->hasOneUse() &&
7260 N0.getOperand(0).getValueType().isInteger()) {
7261 SDValue Int = N0.getOperand(0);
7262 EVT IntVT = Int.getValueType();
7263 if (IntVT.isInteger() && !IntVT.isVector()) {
7264 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7265 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7266 AddToWorkList(Int.getNode());
7267 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7272 // (fneg (fmul c, x)) -> (fmul -c, x)
7273 if (N0.getOpcode() == ISD::FMUL) {
7274 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7276 APFloat CVal = CFP1->getValueAPF();
7278 if (Level >= AfterLegalizeDAG &&
7279 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7280 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7282 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7283 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7290 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7291 SDValue N0 = N->getOperand(0);
7292 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7293 EVT VT = N->getValueType(0);
7295 // fold (fceil c1) -> fceil(c1)
7297 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7302 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7303 SDValue N0 = N->getOperand(0);
7304 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7305 EVT VT = N->getValueType(0);
7307 // fold (ftrunc c1) -> ftrunc(c1)
7309 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7314 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7315 SDValue N0 = N->getOperand(0);
7316 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7317 EVT VT = N->getValueType(0);
7319 // fold (ffloor c1) -> ffloor(c1)
7321 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7326 SDValue DAGCombiner::visitFABS(SDNode *N) {
7327 SDValue N0 = N->getOperand(0);
7328 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7329 EVT VT = N->getValueType(0);
7331 if (VT.isVector()) {
7332 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7333 if (FoldedVOp.getNode()) return FoldedVOp;
7336 // fold (fabs c1) -> fabs(c1)
7338 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7339 // fold (fabs (fabs x)) -> (fabs x)
7340 if (N0.getOpcode() == ISD::FABS)
7341 return N->getOperand(0);
7342 // fold (fabs (fneg x)) -> (fabs x)
7343 // fold (fabs (fcopysign x, y)) -> (fabs x)
7344 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7345 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7347 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7348 // constant pool values.
7349 if (!TLI.isFAbsFree(VT) &&
7350 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7351 N0.getOperand(0).getValueType().isInteger() &&
7352 !N0.getOperand(0).getValueType().isVector()) {
7353 SDValue Int = N0.getOperand(0);
7354 EVT IntVT = Int.getValueType();
7355 if (IntVT.isInteger() && !IntVT.isVector()) {
7356 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7357 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7358 AddToWorkList(Int.getNode());
7359 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7360 N->getValueType(0), Int);
7367 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7368 SDValue Chain = N->getOperand(0);
7369 SDValue N1 = N->getOperand(1);
7370 SDValue N2 = N->getOperand(2);
7372 // If N is a constant we could fold this into a fallthrough or unconditional
7373 // branch. However that doesn't happen very often in normal code, because
7374 // Instcombine/SimplifyCFG should have handled the available opportunities.
7375 // If we did this folding here, it would be necessary to update the
7376 // MachineBasicBlock CFG, which is awkward.
7378 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7380 if (N1.getOpcode() == ISD::SETCC &&
7381 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7382 N1.getOperand(0).getValueType())) {
7383 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7384 Chain, N1.getOperand(2),
7385 N1.getOperand(0), N1.getOperand(1), N2);
7388 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7389 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7390 (N1.getOperand(0).hasOneUse() &&
7391 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7392 SDNode *Trunc = nullptr;
7393 if (N1.getOpcode() == ISD::TRUNCATE) {
7394 // Look pass the truncate.
7395 Trunc = N1.getNode();
7396 N1 = N1.getOperand(0);
7399 // Match this pattern so that we can generate simpler code:
7402 // %b = and i32 %a, 2
7403 // %c = srl i32 %b, 1
7404 // brcond i32 %c ...
7409 // %b = and i32 %a, 2
7410 // %c = setcc eq %b, 0
7413 // This applies only when the AND constant value has one bit set and the
7414 // SRL constant is equal to the log2 of the AND constant. The back-end is
7415 // smart enough to convert the result into a TEST/JMP sequence.
7416 SDValue Op0 = N1.getOperand(0);
7417 SDValue Op1 = N1.getOperand(1);
7419 if (Op0.getOpcode() == ISD::AND &&
7420 Op1.getOpcode() == ISD::Constant) {
7421 SDValue AndOp1 = Op0.getOperand(1);
7423 if (AndOp1.getOpcode() == ISD::Constant) {
7424 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7426 if (AndConst.isPowerOf2() &&
7427 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7429 DAG.getSetCC(SDLoc(N),
7430 getSetCCResultType(Op0.getValueType()),
7431 Op0, DAG.getConstant(0, Op0.getValueType()),
7434 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7435 MVT::Other, Chain, SetCC, N2);
7436 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7437 // will convert it back to (X & C1) >> C2.
7438 CombineTo(N, NewBRCond, false);
7439 // Truncate is dead.
7441 removeFromWorkList(Trunc);
7442 DAG.DeleteNode(Trunc);
7444 // Replace the uses of SRL with SETCC
7445 WorkListRemover DeadNodes(*this);
7446 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7447 removeFromWorkList(N1.getNode());
7448 DAG.DeleteNode(N1.getNode());
7449 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7455 // Restore N1 if the above transformation doesn't match.
7456 N1 = N->getOperand(1);
7459 // Transform br(xor(x, y)) -> br(x != y)
7460 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7461 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7462 SDNode *TheXor = N1.getNode();
7463 SDValue Op0 = TheXor->getOperand(0);
7464 SDValue Op1 = TheXor->getOperand(1);
7465 if (Op0.getOpcode() == Op1.getOpcode()) {
7466 // Avoid missing important xor optimizations.
7467 SDValue Tmp = visitXOR(TheXor);
7468 if (Tmp.getNode()) {
7469 if (Tmp.getNode() != TheXor) {
7470 DEBUG(dbgs() << "\nReplacing.8 ";
7472 dbgs() << "\nWith: ";
7473 Tmp.getNode()->dump(&DAG);
7475 WorkListRemover DeadNodes(*this);
7476 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7477 removeFromWorkList(TheXor);
7478 DAG.DeleteNode(TheXor);
7479 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7480 MVT::Other, Chain, Tmp, N2);
7483 // visitXOR has changed XOR's operands or replaced the XOR completely,
7485 return SDValue(N, 0);
7489 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7491 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7492 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7493 Op0.getOpcode() == ISD::XOR) {
7494 TheXor = Op0.getNode();
7498 EVT SetCCVT = N1.getValueType();
7500 SetCCVT = getSetCCResultType(SetCCVT);
7501 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7504 Equal ? ISD::SETEQ : ISD::SETNE);
7505 // Replace the uses of XOR with SETCC
7506 WorkListRemover DeadNodes(*this);
7507 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7508 removeFromWorkList(N1.getNode());
7509 DAG.DeleteNode(N1.getNode());
7510 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7511 MVT::Other, Chain, SetCC, N2);
7518 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7520 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7521 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7522 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7524 // If N is a constant we could fold this into a fallthrough or unconditional
7525 // branch. However that doesn't happen very often in normal code, because
7526 // Instcombine/SimplifyCFG should have handled the available opportunities.
7527 // If we did this folding here, it would be necessary to update the
7528 // MachineBasicBlock CFG, which is awkward.
7530 // Use SimplifySetCC to simplify SETCC's.
7531 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7532 CondLHS, CondRHS, CC->get(), SDLoc(N),
7534 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7536 // fold to a simpler setcc
7537 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7538 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7539 N->getOperand(0), Simp.getOperand(2),
7540 Simp.getOperand(0), Simp.getOperand(1),
7546 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7547 /// uses N as its base pointer and that N may be folded in the load / store
7548 /// addressing mode.
7549 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7551 const TargetLowering &TLI) {
7553 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7554 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7556 VT = Use->getValueType(0);
7557 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7558 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7560 VT = ST->getValue().getValueType();
7564 TargetLowering::AddrMode AM;
7565 if (N->getOpcode() == ISD::ADD) {
7566 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7569 AM.BaseOffs = Offset->getSExtValue();
7573 } else if (N->getOpcode() == ISD::SUB) {
7574 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7577 AM.BaseOffs = -Offset->getSExtValue();
7584 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7587 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7588 /// pre-indexed load / store when the base pointer is an add or subtract
7589 /// and it has other uses besides the load / store. After the
7590 /// transformation, the new indexed load / store has effectively folded
7591 /// the add / subtract in and all of its other uses are redirected to the
7592 /// new load / store.
7593 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7594 if (Level < AfterLegalizeDAG)
7600 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7601 if (LD->isIndexed())
7603 VT = LD->getMemoryVT();
7604 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7605 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7607 Ptr = LD->getBasePtr();
7608 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7609 if (ST->isIndexed())
7611 VT = ST->getMemoryVT();
7612 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7613 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7615 Ptr = ST->getBasePtr();
7621 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7622 // out. There is no reason to make this a preinc/predec.
7623 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7624 Ptr.getNode()->hasOneUse())
7627 // Ask the target to do addressing mode selection.
7630 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7631 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7634 // Backends without true r+i pre-indexed forms may need to pass a
7635 // constant base with a variable offset so that constant coercion
7636 // will work with the patterns in canonical form.
7637 bool Swapped = false;
7638 if (isa<ConstantSDNode>(BasePtr)) {
7639 std::swap(BasePtr, Offset);
7643 // Don't create a indexed load / store with zero offset.
7644 if (isa<ConstantSDNode>(Offset) &&
7645 cast<ConstantSDNode>(Offset)->isNullValue())
7648 // Try turning it into a pre-indexed load / store except when:
7649 // 1) The new base ptr is a frame index.
7650 // 2) If N is a store and the new base ptr is either the same as or is a
7651 // predecessor of the value being stored.
7652 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7653 // that would create a cycle.
7654 // 4) All uses are load / store ops that use it as old base ptr.
7656 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7657 // (plus the implicit offset) to a register to preinc anyway.
7658 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7663 SDValue Val = cast<StoreSDNode>(N)->getValue();
7664 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7668 // If the offset is a constant, there may be other adds of constants that
7669 // can be folded with this one. We should do this to avoid having to keep
7670 // a copy of the original base pointer.
7671 SmallVector<SDNode *, 16> OtherUses;
7672 if (isa<ConstantSDNode>(Offset))
7673 for (SDNode *Use : BasePtr.getNode()->uses()) {
7674 if (Use == Ptr.getNode())
7677 if (Use->isPredecessorOf(N))
7680 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7685 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7686 if (Op1.getNode() == BasePtr.getNode())
7687 std::swap(Op0, Op1);
7688 assert(Op0.getNode() == BasePtr.getNode() &&
7689 "Use of ADD/SUB but not an operand");
7691 if (!isa<ConstantSDNode>(Op1)) {
7696 // FIXME: In some cases, we can be smarter about this.
7697 if (Op1.getValueType() != Offset.getValueType()) {
7702 OtherUses.push_back(Use);
7706 std::swap(BasePtr, Offset);
7708 // Now check for #3 and #4.
7709 bool RealUse = false;
7711 // Caches for hasPredecessorHelper
7712 SmallPtrSet<const SDNode *, 32> Visited;
7713 SmallVector<const SDNode *, 16> Worklist;
7715 for (SDNode *Use : Ptr.getNode()->uses()) {
7718 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7721 // If Ptr may be folded in addressing mode of other use, then it's
7722 // not profitable to do this transformation.
7723 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7732 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7733 BasePtr, Offset, AM);
7735 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7736 BasePtr, Offset, AM);
7739 DEBUG(dbgs() << "\nReplacing.4 ";
7741 dbgs() << "\nWith: ";
7742 Result.getNode()->dump(&DAG);
7744 WorkListRemover DeadNodes(*this);
7746 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7747 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7749 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7752 // Finally, since the node is now dead, remove it from the graph.
7756 std::swap(BasePtr, Offset);
7758 // Replace other uses of BasePtr that can be updated to use Ptr
7759 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7760 unsigned OffsetIdx = 1;
7761 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7763 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7764 BasePtr.getNode() && "Expected BasePtr operand");
7766 // We need to replace ptr0 in the following expression:
7767 // x0 * offset0 + y0 * ptr0 = t0
7769 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7771 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7772 // indexed load/store and the expresion that needs to be re-written.
7774 // Therefore, we have:
7775 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7777 ConstantSDNode *CN =
7778 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7780 APInt Offset0 = CN->getAPIntValue();
7781 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7783 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7784 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7785 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7786 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7788 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7790 APInt CNV = Offset0;
7791 if (X0 < 0) CNV = -CNV;
7792 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7793 else CNV = CNV - Offset1;
7795 // We can now generate the new expression.
7796 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7797 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7799 SDValue NewUse = DAG.getNode(Opcode,
7800 SDLoc(OtherUses[i]),
7801 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7802 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7803 removeFromWorkList(OtherUses[i]);
7804 DAG.DeleteNode(OtherUses[i]);
7807 // Replace the uses of Ptr with uses of the updated base value.
7808 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7809 removeFromWorkList(Ptr.getNode());
7810 DAG.DeleteNode(Ptr.getNode());
7815 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7816 /// add / sub of the base pointer node into a post-indexed load / store.
7817 /// The transformation folded the add / subtract into the new indexed
7818 /// load / store effectively and all of its uses are redirected to the
7819 /// new load / store.
7820 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7821 if (Level < AfterLegalizeDAG)
7827 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7828 if (LD->isIndexed())
7830 VT = LD->getMemoryVT();
7831 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7832 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7834 Ptr = LD->getBasePtr();
7835 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7836 if (ST->isIndexed())
7838 VT = ST->getMemoryVT();
7839 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7840 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7842 Ptr = ST->getBasePtr();
7848 if (Ptr.getNode()->hasOneUse())
7851 for (SDNode *Op : Ptr.getNode()->uses()) {
7853 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7858 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7859 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7860 // Don't create a indexed load / store with zero offset.
7861 if (isa<ConstantSDNode>(Offset) &&
7862 cast<ConstantSDNode>(Offset)->isNullValue())
7865 // Try turning it into a post-indexed load / store except when
7866 // 1) All uses are load / store ops that use it as base ptr (and
7867 // it may be folded as addressing mmode).
7868 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7869 // nor a successor of N. Otherwise, if Op is folded that would
7872 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7876 bool TryNext = false;
7877 for (SDNode *Use : BasePtr.getNode()->uses()) {
7878 if (Use == Ptr.getNode())
7881 // If all the uses are load / store addresses, then don't do the
7883 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7884 bool RealUse = false;
7885 for (SDNode *UseUse : Use->uses()) {
7886 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7901 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7902 SDValue Result = isLoad
7903 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7904 BasePtr, Offset, AM)
7905 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7906 BasePtr, Offset, AM);
7909 DEBUG(dbgs() << "\nReplacing.5 ";
7911 dbgs() << "\nWith: ";
7912 Result.getNode()->dump(&DAG);
7914 WorkListRemover DeadNodes(*this);
7916 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7917 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7919 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7922 // Finally, since the node is now dead, remove it from the graph.
7925 // Replace the uses of Use with uses of the updated base value.
7926 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7927 Result.getValue(isLoad ? 1 : 0));
7928 removeFromWorkList(Op);
7938 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7939 LoadSDNode *LD = cast<LoadSDNode>(N);
7940 SDValue Chain = LD->getChain();
7941 SDValue Ptr = LD->getBasePtr();
7943 // If load is not volatile and there are no uses of the loaded value (and
7944 // the updated indexed value in case of indexed loads), change uses of the
7945 // chain value into uses of the chain input (i.e. delete the dead load).
7946 if (!LD->isVolatile()) {
7947 if (N->getValueType(1) == MVT::Other) {
7949 if (!N->hasAnyUseOfValue(0)) {
7950 // It's not safe to use the two value CombineTo variant here. e.g.
7951 // v1, chain2 = load chain1, loc
7952 // v2, chain3 = load chain2, loc
7954 // Now we replace use of chain2 with chain1. This makes the second load
7955 // isomorphic to the one we are deleting, and thus makes this load live.
7956 DEBUG(dbgs() << "\nReplacing.6 ";
7958 dbgs() << "\nWith chain: ";
7959 Chain.getNode()->dump(&DAG);
7961 WorkListRemover DeadNodes(*this);
7962 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7964 if (N->use_empty()) {
7965 removeFromWorkList(N);
7969 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7973 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7974 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7975 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7976 DEBUG(dbgs() << "\nReplacing.7 ";
7978 dbgs() << "\nWith: ";
7979 Undef.getNode()->dump(&DAG);
7980 dbgs() << " and 2 other values\n");
7981 WorkListRemover DeadNodes(*this);
7982 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7983 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7984 DAG.getUNDEF(N->getValueType(1)));
7985 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7986 removeFromWorkList(N);
7988 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7993 // If this load is directly stored, replace the load value with the stored
7995 // TODO: Handle store large -> read small portion.
7996 // TODO: Handle TRUNCSTORE/LOADEXT
7997 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7998 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7999 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8000 if (PrevST->getBasePtr() == Ptr &&
8001 PrevST->getValue().getValueType() == N->getValueType(0))
8002 return CombineTo(N, Chain.getOperand(1), Chain);
8006 // Try to infer better alignment information than the load already has.
8007 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8008 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8009 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8011 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8012 LD->getValueType(0),
8013 Chain, Ptr, LD->getPointerInfo(),
8015 LD->isVolatile(), LD->isNonTemporal(), Align,
8017 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8022 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8023 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8025 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8026 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8029 if (UseAA && LD->isUnindexed()) {
8030 // Walk up chain skipping non-aliasing memory nodes.
8031 SDValue BetterChain = FindBetterChain(N, Chain);
8033 // If there is a better chain.
8034 if (Chain != BetterChain) {
8037 // Replace the chain to void dependency.
8038 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8039 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8040 BetterChain, Ptr, LD->getMemOperand());
8042 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8043 LD->getValueType(0),
8044 BetterChain, Ptr, LD->getMemoryVT(),
8045 LD->getMemOperand());
8048 // Create token factor to keep old chain connected.
8049 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8050 MVT::Other, Chain, ReplLoad.getValue(1));
8052 // Make sure the new and old chains are cleaned up.
8053 AddToWorkList(Token.getNode());
8055 // Replace uses with load result and token factor. Don't add users
8057 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8061 // Try transforming N to an indexed load.
8062 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8063 return SDValue(N, 0);
8065 // Try to slice up N to more direct loads if the slices are mapped to
8066 // different register banks or pairing can take place.
8068 return SDValue(N, 0);
8074 /// \brief Helper structure used to slice a load in smaller loads.
8075 /// Basically a slice is obtained from the following sequence:
8076 /// Origin = load Ty1, Base
8077 /// Shift = srl Ty1 Origin, CstTy Amount
8078 /// Inst = trunc Shift to Ty2
8080 /// Then, it will be rewriten into:
8081 /// Slice = load SliceTy, Base + SliceOffset
8082 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8084 /// SliceTy is deduced from the number of bits that are actually used to
8086 struct LoadedSlice {
8087 /// \brief Helper structure used to compute the cost of a slice.
8089 /// Are we optimizing for code size.
8094 unsigned CrossRegisterBanksCopies;
8098 Cost(bool ForCodeSize = false)
8099 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8100 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8102 /// \brief Get the cost of one isolated slice.
8103 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8104 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8105 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8106 EVT TruncType = LS.Inst->getValueType(0);
8107 EVT LoadedType = LS.getLoadedType();
8108 if (TruncType != LoadedType &&
8109 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8113 /// \brief Account for slicing gain in the current cost.
8114 /// Slicing provide a few gains like removing a shift or a
8115 /// truncate. This method allows to grow the cost of the original
8116 /// load with the gain from this slice.
8117 void addSliceGain(const LoadedSlice &LS) {
8118 // Each slice saves a truncate.
8119 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8120 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8121 LS.Inst->getOperand(0).getValueType()))
8123 // If there is a shift amount, this slice gets rid of it.
8126 // If this slice can merge a cross register bank copy, account for it.
8127 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8128 ++CrossRegisterBanksCopies;
8131 Cost &operator+=(const Cost &RHS) {
8133 Truncates += RHS.Truncates;
8134 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8140 bool operator==(const Cost &RHS) const {
8141 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8142 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8143 ZExts == RHS.ZExts && Shift == RHS.Shift;
8146 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8148 bool operator<(const Cost &RHS) const {
8149 // Assume cross register banks copies are as expensive as loads.
8150 // FIXME: Do we want some more target hooks?
8151 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8152 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8153 // Unless we are optimizing for code size, consider the
8154 // expensive operation first.
8155 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8156 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8157 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8158 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8161 bool operator>(const Cost &RHS) const { return RHS < *this; }
8163 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8165 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8167 // The last instruction that represent the slice. This should be a
8168 // truncate instruction.
8170 // The original load instruction.
8172 // The right shift amount in bits from the original load.
8174 // The DAG from which Origin came from.
8175 // This is used to get some contextual information about legal types, etc.
8178 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8179 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8180 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8182 LoadedSlice(const LoadedSlice &LS)
8183 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8185 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8186 /// \return Result is \p BitWidth and has used bits set to 1 and
8187 /// not used bits set to 0.
8188 APInt getUsedBits() const {
8189 // Reproduce the trunc(lshr) sequence:
8190 // - Start from the truncated value.
8191 // - Zero extend to the desired bit width.
8193 assert(Origin && "No original load to compare against.");
8194 unsigned BitWidth = Origin->getValueSizeInBits(0);
8195 assert(Inst && "This slice is not bound to an instruction");
8196 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8197 "Extracted slice is bigger than the whole type!");
8198 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8199 UsedBits.setAllBits();
8200 UsedBits = UsedBits.zext(BitWidth);
8205 /// \brief Get the size of the slice to be loaded in bytes.
8206 unsigned getLoadedSize() const {
8207 unsigned SliceSize = getUsedBits().countPopulation();
8208 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8209 return SliceSize / 8;
8212 /// \brief Get the type that will be loaded for this slice.
8213 /// Note: This may not be the final type for the slice.
8214 EVT getLoadedType() const {
8215 assert(DAG && "Missing context");
8216 LLVMContext &Ctxt = *DAG->getContext();
8217 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8220 /// \brief Get the alignment of the load used for this slice.
8221 unsigned getAlignment() const {
8222 unsigned Alignment = Origin->getAlignment();
8223 unsigned Offset = getOffsetFromBase();
8225 Alignment = MinAlign(Alignment, Alignment + Offset);
8229 /// \brief Check if this slice can be rewritten with legal operations.
8230 bool isLegal() const {
8231 // An invalid slice is not legal.
8232 if (!Origin || !Inst || !DAG)
8235 // Offsets are for indexed load only, we do not handle that.
8236 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8239 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8241 // Check that the type is legal.
8242 EVT SliceType = getLoadedType();
8243 if (!TLI.isTypeLegal(SliceType))
8246 // Check that the load is legal for this type.
8247 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8250 // Check that the offset can be computed.
8251 // 1. Check its type.
8252 EVT PtrType = Origin->getBasePtr().getValueType();
8253 if (PtrType == MVT::Untyped || PtrType.isExtended())
8256 // 2. Check that it fits in the immediate.
8257 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8260 // 3. Check that the computation is legal.
8261 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8264 // Check that the zext is legal if it needs one.
8265 EVT TruncateType = Inst->getValueType(0);
8266 if (TruncateType != SliceType &&
8267 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8273 /// \brief Get the offset in bytes of this slice in the original chunk of
8275 /// \pre DAG != nullptr.
8276 uint64_t getOffsetFromBase() const {
8277 assert(DAG && "Missing context.");
8279 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8280 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8281 uint64_t Offset = Shift / 8;
8282 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8283 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8284 "The size of the original loaded type is not a multiple of a"
8286 // If Offset is bigger than TySizeInBytes, it means we are loading all
8287 // zeros. This should have been optimized before in the process.
8288 assert(TySizeInBytes > Offset &&
8289 "Invalid shift amount for given loaded size");
8291 Offset = TySizeInBytes - Offset - getLoadedSize();
8295 /// \brief Generate the sequence of instructions to load the slice
8296 /// represented by this object and redirect the uses of this slice to
8297 /// this new sequence of instructions.
8298 /// \pre this->Inst && this->Origin are valid Instructions and this
8299 /// object passed the legal check: LoadedSlice::isLegal returned true.
8300 /// \return The last instruction of the sequence used to load the slice.
8301 SDValue loadSlice() const {
8302 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8303 const SDValue &OldBaseAddr = Origin->getBasePtr();
8304 SDValue BaseAddr = OldBaseAddr;
8305 // Get the offset in that chunk of bytes w.r.t. the endianess.
8306 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8307 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8309 // BaseAddr = BaseAddr + Offset.
8310 EVT ArithType = BaseAddr.getValueType();
8311 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8312 DAG->getConstant(Offset, ArithType));
8315 // Create the type of the loaded slice according to its size.
8316 EVT SliceType = getLoadedType();
8318 // Create the load for the slice.
8319 SDValue LastInst = DAG->getLoad(
8320 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8321 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8322 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8323 // If the final type is not the same as the loaded type, this means that
8324 // we have to pad with zero. Create a zero extend for that.
8325 EVT FinalType = Inst->getValueType(0);
8326 if (SliceType != FinalType)
8328 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8332 /// \brief Check if this slice can be merged with an expensive cross register
8333 /// bank copy. E.g.,
8335 /// f = bitcast i32 i to float
8336 bool canMergeExpensiveCrossRegisterBankCopy() const {
8337 if (!Inst || !Inst->hasOneUse())
8339 SDNode *Use = *Inst->use_begin();
8340 if (Use->getOpcode() != ISD::BITCAST)
8342 assert(DAG && "Missing context");
8343 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8344 EVT ResVT = Use->getValueType(0);
8345 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8346 const TargetRegisterClass *ArgRC =
8347 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8348 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8351 // At this point, we know that we perform a cross-register-bank copy.
8352 // Check if it is expensive.
8353 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8354 // Assume bitcasts are cheap, unless both register classes do not
8355 // explicitly share a common sub class.
8356 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8359 // Check if it will be merged with the load.
8360 // 1. Check the alignment constraint.
8361 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8362 ResVT.getTypeForEVT(*DAG->getContext()));
8364 if (RequiredAlignment > getAlignment())
8367 // 2. Check that the load is a legal operation for that type.
8368 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8371 // 3. Check that we do not have a zext in the way.
8372 if (Inst->getValueType(0) != getLoadedType())
8380 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8381 /// \p UsedBits looks like 0..0 1..1 0..0.
8382 static bool areUsedBitsDense(const APInt &UsedBits) {
8383 // If all the bits are one, this is dense!
8384 if (UsedBits.isAllOnesValue())
8387 // Get rid of the unused bits on the right.
8388 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8389 // Get rid of the unused bits on the left.
8390 if (NarrowedUsedBits.countLeadingZeros())
8391 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8392 // Check that the chunk of bits is completely used.
8393 return NarrowedUsedBits.isAllOnesValue();
8396 /// \brief Check whether or not \p First and \p Second are next to each other
8397 /// in memory. This means that there is no hole between the bits loaded
8398 /// by \p First and the bits loaded by \p Second.
8399 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8400 const LoadedSlice &Second) {
8401 assert(First.Origin == Second.Origin && First.Origin &&
8402 "Unable to match different memory origins.");
8403 APInt UsedBits = First.getUsedBits();
8404 assert((UsedBits & Second.getUsedBits()) == 0 &&
8405 "Slices are not supposed to overlap.");
8406 UsedBits |= Second.getUsedBits();
8407 return areUsedBitsDense(UsedBits);
8410 /// \brief Adjust the \p GlobalLSCost according to the target
8411 /// paring capabilities and the layout of the slices.
8412 /// \pre \p GlobalLSCost should account for at least as many loads as
8413 /// there is in the slices in \p LoadedSlices.
8414 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8415 LoadedSlice::Cost &GlobalLSCost) {
8416 unsigned NumberOfSlices = LoadedSlices.size();
8417 // If there is less than 2 elements, no pairing is possible.
8418 if (NumberOfSlices < 2)
8421 // Sort the slices so that elements that are likely to be next to each
8422 // other in memory are next to each other in the list.
8423 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8424 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8425 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8426 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8428 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8429 // First (resp. Second) is the first (resp. Second) potentially candidate
8430 // to be placed in a paired load.
8431 const LoadedSlice *First = nullptr;
8432 const LoadedSlice *Second = nullptr;
8433 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8434 // Set the beginning of the pair.
8437 Second = &LoadedSlices[CurrSlice];
8439 // If First is NULL, it means we start a new pair.
8440 // Get to the next slice.
8444 EVT LoadedType = First->getLoadedType();
8446 // If the types of the slices are different, we cannot pair them.
8447 if (LoadedType != Second->getLoadedType())
8450 // Check if the target supplies paired loads for this type.
8451 unsigned RequiredAlignment = 0;
8452 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8453 // move to the next pair, this type is hopeless.
8457 // Check if we meet the alignment requirement.
8458 if (RequiredAlignment > First->getAlignment())
8461 // Check that both loads are next to each other in memory.
8462 if (!areSlicesNextToEachOther(*First, *Second))
8465 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8466 --GlobalLSCost.Loads;
8467 // Move to the next pair.
8472 /// \brief Check the profitability of all involved LoadedSlice.
8473 /// Currently, it is considered profitable if there is exactly two
8474 /// involved slices (1) which are (2) next to each other in memory, and
8475 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8477 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8478 /// the elements themselves.
8480 /// FIXME: When the cost model will be mature enough, we can relax
8481 /// constraints (1) and (2).
8482 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8483 const APInt &UsedBits, bool ForCodeSize) {
8484 unsigned NumberOfSlices = LoadedSlices.size();
8485 if (StressLoadSlicing)
8486 return NumberOfSlices > 1;
8489 if (NumberOfSlices != 2)
8493 if (!areUsedBitsDense(UsedBits))
8497 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8498 // The original code has one big load.
8500 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8501 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8502 // Accumulate the cost of all the slices.
8503 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8504 GlobalSlicingCost += SliceCost;
8506 // Account as cost in the original configuration the gain obtained
8507 // with the current slices.
8508 OrigCost.addSliceGain(LS);
8511 // If the target supports paired load, adjust the cost accordingly.
8512 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8513 return OrigCost > GlobalSlicingCost;
8516 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8517 /// operations, split it in the various pieces being extracted.
8519 /// This sort of thing is introduced by SROA.
8520 /// This slicing takes care not to insert overlapping loads.
8521 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8522 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8523 if (Level < AfterLegalizeDAG)
8526 LoadSDNode *LD = cast<LoadSDNode>(N);
8527 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8528 !LD->getValueType(0).isInteger())
8531 // Keep track of already used bits to detect overlapping values.
8532 // In that case, we will just abort the transformation.
8533 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8535 SmallVector<LoadedSlice, 4> LoadedSlices;
8537 // Check if this load is used as several smaller chunks of bits.
8538 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8539 // of computation for each trunc.
8540 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8541 UI != UIEnd; ++UI) {
8542 // Skip the uses of the chain.
8543 if (UI.getUse().getResNo() != 0)
8549 // Check if this is a trunc(lshr).
8550 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8551 isa<ConstantSDNode>(User->getOperand(1))) {
8552 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8553 User = *User->use_begin();
8556 // At this point, User is a Truncate, iff we encountered, trunc or
8558 if (User->getOpcode() != ISD::TRUNCATE)
8561 // The width of the type must be a power of 2 and greater than 8-bits.
8562 // Otherwise the load cannot be represented in LLVM IR.
8563 // Moreover, if we shifted with a non-8-bits multiple, the slice
8564 // will be across several bytes. We do not support that.
8565 unsigned Width = User->getValueSizeInBits(0);
8566 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8569 // Build the slice for this chain of computations.
8570 LoadedSlice LS(User, LD, Shift, &DAG);
8571 APInt CurrentUsedBits = LS.getUsedBits();
8573 // Check if this slice overlaps with another.
8574 if ((CurrentUsedBits & UsedBits) != 0)
8576 // Update the bits used globally.
8577 UsedBits |= CurrentUsedBits;
8579 // Check if the new slice would be legal.
8583 // Record the slice.
8584 LoadedSlices.push_back(LS);
8587 // Abort slicing if it does not seem to be profitable.
8588 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8593 // Rewrite each chain to use an independent load.
8594 // By construction, each chain can be represented by a unique load.
8596 // Prepare the argument for the new token factor for all the slices.
8597 SmallVector<SDValue, 8> ArgChains;
8598 for (SmallVectorImpl<LoadedSlice>::const_iterator
8599 LSIt = LoadedSlices.begin(),
8600 LSItEnd = LoadedSlices.end();
8601 LSIt != LSItEnd; ++LSIt) {
8602 SDValue SliceInst = LSIt->loadSlice();
8603 CombineTo(LSIt->Inst, SliceInst, true);
8604 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8605 SliceInst = SliceInst.getOperand(0);
8606 assert(SliceInst->getOpcode() == ISD::LOAD &&
8607 "It takes more than a zext to get to the loaded slice!!");
8608 ArgChains.push_back(SliceInst.getValue(1));
8611 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8613 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8617 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8618 /// load is having specific bytes cleared out. If so, return the byte size
8619 /// being masked out and the shift amount.
8620 static std::pair<unsigned, unsigned>
8621 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8622 std::pair<unsigned, unsigned> Result(0, 0);
8624 // Check for the structure we're looking for.
8625 if (V->getOpcode() != ISD::AND ||
8626 !isa<ConstantSDNode>(V->getOperand(1)) ||
8627 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8630 // Check the chain and pointer.
8631 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8632 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8634 // The store should be chained directly to the load or be an operand of a
8636 if (LD == Chain.getNode())
8638 else if (Chain->getOpcode() != ISD::TokenFactor)
8639 return Result; // Fail.
8642 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8643 if (Chain->getOperand(i).getNode() == LD) {
8647 if (!isOk) return Result;
8650 // This only handles simple types.
8651 if (V.getValueType() != MVT::i16 &&
8652 V.getValueType() != MVT::i32 &&
8653 V.getValueType() != MVT::i64)
8656 // Check the constant mask. Invert it so that the bits being masked out are
8657 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8658 // follow the sign bit for uniformity.
8659 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8660 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8661 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8662 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8663 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8664 if (NotMaskLZ == 64) return Result; // All zero mask.
8666 // See if we have a continuous run of bits. If so, we have 0*1+0*
8667 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8670 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8671 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8672 NotMaskLZ -= 64-V.getValueSizeInBits();
8674 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8675 switch (MaskedBytes) {
8679 default: return Result; // All one mask, or 5-byte mask.
8682 // Verify that the first bit starts at a multiple of mask so that the access
8683 // is aligned the same as the access width.
8684 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8686 Result.first = MaskedBytes;
8687 Result.second = NotMaskTZ/8;
8692 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8693 /// provides a value as specified by MaskInfo. If so, replace the specified
8694 /// store with a narrower store of truncated IVal.
8696 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8697 SDValue IVal, StoreSDNode *St,
8699 unsigned NumBytes = MaskInfo.first;
8700 unsigned ByteShift = MaskInfo.second;
8701 SelectionDAG &DAG = DC->getDAG();
8703 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8704 // that uses this. If not, this is not a replacement.
8705 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8706 ByteShift*8, (ByteShift+NumBytes)*8);
8707 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8709 // Check that it is legal on the target to do this. It is legal if the new
8710 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8712 MVT VT = MVT::getIntegerVT(NumBytes*8);
8713 if (!DC->isTypeLegal(VT))
8716 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8717 // shifted by ByteShift and truncated down to NumBytes.
8719 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8720 DAG.getConstant(ByteShift*8,
8721 DC->getShiftAmountTy(IVal.getValueType())));
8723 // Figure out the offset for the store and the alignment of the access.
8725 unsigned NewAlign = St->getAlignment();
8727 if (DAG.getTargetLoweringInfo().isLittleEndian())
8728 StOffset = ByteShift;
8730 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8732 SDValue Ptr = St->getBasePtr();
8734 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8735 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8736 NewAlign = MinAlign(NewAlign, StOffset);
8739 // Truncate down to the new size.
8740 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8743 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8744 St->getPointerInfo().getWithOffset(StOffset),
8745 false, false, NewAlign).getNode();
8749 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8750 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8751 /// of the loaded bits, try narrowing the load and store if it would end up
8752 /// being a win for performance or code size.
8753 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8754 StoreSDNode *ST = cast<StoreSDNode>(N);
8755 if (ST->isVolatile())
8758 SDValue Chain = ST->getChain();
8759 SDValue Value = ST->getValue();
8760 SDValue Ptr = ST->getBasePtr();
8761 EVT VT = Value.getValueType();
8763 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8766 unsigned Opc = Value.getOpcode();
8768 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8769 // is a byte mask indicating a consecutive number of bytes, check to see if
8770 // Y is known to provide just those bytes. If so, we try to replace the
8771 // load + replace + store sequence with a single (narrower) store, which makes
8773 if (Opc == ISD::OR) {
8774 std::pair<unsigned, unsigned> MaskedLoad;
8775 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8776 if (MaskedLoad.first)
8777 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8778 Value.getOperand(1), ST,this))
8779 return SDValue(NewST, 0);
8781 // Or is commutative, so try swapping X and Y.
8782 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8783 if (MaskedLoad.first)
8784 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8785 Value.getOperand(0), ST,this))
8786 return SDValue(NewST, 0);
8789 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8790 Value.getOperand(1).getOpcode() != ISD::Constant)
8793 SDValue N0 = Value.getOperand(0);
8794 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8795 Chain == SDValue(N0.getNode(), 1)) {
8796 LoadSDNode *LD = cast<LoadSDNode>(N0);
8797 if (LD->getBasePtr() != Ptr ||
8798 LD->getPointerInfo().getAddrSpace() !=
8799 ST->getPointerInfo().getAddrSpace())
8802 // Find the type to narrow it the load / op / store to.
8803 SDValue N1 = Value.getOperand(1);
8804 unsigned BitWidth = N1.getValueSizeInBits();
8805 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8806 if (Opc == ISD::AND)
8807 Imm ^= APInt::getAllOnesValue(BitWidth);
8808 if (Imm == 0 || Imm.isAllOnesValue())
8810 unsigned ShAmt = Imm.countTrailingZeros();
8811 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8812 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8813 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8814 while (NewBW < BitWidth &&
8815 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8816 TLI.isNarrowingProfitable(VT, NewVT))) {
8817 NewBW = NextPowerOf2(NewBW);
8818 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8820 if (NewBW >= BitWidth)
8823 // If the lsb changed does not start at the type bitwidth boundary,
8824 // start at the previous one.
8826 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8827 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8828 std::min(BitWidth, ShAmt + NewBW));
8829 if ((Imm & Mask) == Imm) {
8830 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8831 if (Opc == ISD::AND)
8832 NewImm ^= APInt::getAllOnesValue(NewBW);
8833 uint64_t PtrOff = ShAmt / 8;
8834 // For big endian targets, we need to adjust the offset to the pointer to
8835 // load the correct bytes.
8836 if (TLI.isBigEndian())
8837 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8839 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8840 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8841 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8844 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8845 Ptr.getValueType(), Ptr,
8846 DAG.getConstant(PtrOff, Ptr.getValueType()));
8847 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8848 LD->getChain(), NewPtr,
8849 LD->getPointerInfo().getWithOffset(PtrOff),
8850 LD->isVolatile(), LD->isNonTemporal(),
8851 LD->isInvariant(), NewAlign,
8853 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8854 DAG.getConstant(NewImm, NewVT));
8855 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8857 ST->getPointerInfo().getWithOffset(PtrOff),
8858 false, false, NewAlign);
8860 AddToWorkList(NewPtr.getNode());
8861 AddToWorkList(NewLD.getNode());
8862 AddToWorkList(NewVal.getNode());
8863 WorkListRemover DeadNodes(*this);
8864 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8873 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8874 /// if the load value isn't used by any other operations, then consider
8875 /// transforming the pair to integer load / store operations if the target
8876 /// deems the transformation profitable.
8877 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8878 StoreSDNode *ST = cast<StoreSDNode>(N);
8879 SDValue Chain = ST->getChain();
8880 SDValue Value = ST->getValue();
8881 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8882 Value.hasOneUse() &&
8883 Chain == SDValue(Value.getNode(), 1)) {
8884 LoadSDNode *LD = cast<LoadSDNode>(Value);
8885 EVT VT = LD->getMemoryVT();
8886 if (!VT.isFloatingPoint() ||
8887 VT != ST->getMemoryVT() ||
8888 LD->isNonTemporal() ||
8889 ST->isNonTemporal() ||
8890 LD->getPointerInfo().getAddrSpace() != 0 ||
8891 ST->getPointerInfo().getAddrSpace() != 0)
8894 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8895 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8896 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8897 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8898 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8901 unsigned LDAlign = LD->getAlignment();
8902 unsigned STAlign = ST->getAlignment();
8903 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8904 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8905 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8908 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8909 LD->getChain(), LD->getBasePtr(),
8910 LD->getPointerInfo(),
8911 false, false, false, LDAlign);
8913 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8914 NewLD, ST->getBasePtr(),
8915 ST->getPointerInfo(),
8916 false, false, STAlign);
8918 AddToWorkList(NewLD.getNode());
8919 AddToWorkList(NewST.getNode());
8920 WorkListRemover DeadNodes(*this);
8921 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8929 /// Helper struct to parse and store a memory address as base + index + offset.
8930 /// We ignore sign extensions when it is safe to do so.
8931 /// The following two expressions are not equivalent. To differentiate we need
8932 /// to store whether there was a sign extension involved in the index
8934 /// (load (i64 add (i64 copyfromreg %c)
8935 /// (i64 signextend (add (i8 load %index)
8939 /// (load (i64 add (i64 copyfromreg %c)
8940 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8942 struct BaseIndexOffset {
8946 bool IsIndexSignExt;
8948 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8950 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8951 bool IsIndexSignExt) :
8952 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8954 bool equalBaseIndex(const BaseIndexOffset &Other) {
8955 return Other.Base == Base && Other.Index == Index &&
8956 Other.IsIndexSignExt == IsIndexSignExt;
8959 /// Parses tree in Ptr for base, index, offset addresses.
8960 static BaseIndexOffset match(SDValue Ptr) {
8961 bool IsIndexSignExt = false;
8963 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8964 // instruction, then it could be just the BASE or everything else we don't
8965 // know how to handle. Just use Ptr as BASE and give up.
8966 if (Ptr->getOpcode() != ISD::ADD)
8967 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8969 // We know that we have at least an ADD instruction. Try to pattern match
8970 // the simple case of BASE + OFFSET.
8971 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8972 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8973 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8977 // Inside a loop the current BASE pointer is calculated using an ADD and a
8978 // MUL instruction. In this case Ptr is the actual BASE pointer.
8979 // (i64 add (i64 %array_ptr)
8980 // (i64 mul (i64 %induction_var)
8981 // (i64 %element_size)))
8982 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8983 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8985 // Look at Base + Index + Offset cases.
8986 SDValue Base = Ptr->getOperand(0);
8987 SDValue IndexOffset = Ptr->getOperand(1);
8989 // Skip signextends.
8990 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8991 IndexOffset = IndexOffset->getOperand(0);
8992 IsIndexSignExt = true;
8995 // Either the case of Base + Index (no offset) or something else.
8996 if (IndexOffset->getOpcode() != ISD::ADD)
8997 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8999 // Now we have the case of Base + Index + offset.
9000 SDValue Index = IndexOffset->getOperand(0);
9001 SDValue Offset = IndexOffset->getOperand(1);
9003 if (!isa<ConstantSDNode>(Offset))
9004 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9006 // Ignore signextends.
9007 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9008 Index = Index->getOperand(0);
9009 IsIndexSignExt = true;
9010 } else IsIndexSignExt = false;
9012 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9013 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9017 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9018 /// is located in a sequence of memory operations connected by a chain.
9020 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9021 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9022 // Ptr to the mem node.
9023 LSBaseSDNode *MemNode;
9024 // Offset from the base ptr.
9025 int64_t OffsetFromBase;
9026 // What is the sequence number of this mem node.
9027 // Lowest mem operand in the DAG starts at zero.
9028 unsigned SequenceNum;
9031 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9032 EVT MemVT = St->getMemoryVT();
9033 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9034 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9035 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9037 // Don't merge vectors into wider inputs.
9038 if (MemVT.isVector() || !MemVT.isSimple())
9041 // Perform an early exit check. Do not bother looking at stored values that
9042 // are not constants or loads.
9043 SDValue StoredVal = St->getValue();
9044 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9045 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9049 // Only look at ends of store sequences.
9050 SDValue Chain = SDValue(St, 1);
9051 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9054 // This holds the base pointer, index, and the offset in bytes from the base
9056 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9058 // We must have a base and an offset.
9059 if (!BasePtr.Base.getNode())
9062 // Do not handle stores to undef base pointers.
9063 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9066 // Save the LoadSDNodes that we find in the chain.
9067 // We need to make sure that these nodes do not interfere with
9068 // any of the store nodes.
9069 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9071 // Save the StoreSDNodes that we find in the chain.
9072 SmallVector<MemOpLink, 8> StoreNodes;
9074 // Walk up the chain and look for nodes with offsets from the same
9075 // base pointer. Stop when reaching an instruction with a different kind
9076 // or instruction which has a different base pointer.
9078 StoreSDNode *Index = St;
9080 // If the chain has more than one use, then we can't reorder the mem ops.
9081 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9084 // Find the base pointer and offset for this memory node.
9085 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9087 // Check that the base pointer is the same as the original one.
9088 if (!Ptr.equalBaseIndex(BasePtr))
9091 // Check that the alignment is the same.
9092 if (Index->getAlignment() != St->getAlignment())
9095 // The memory operands must not be volatile.
9096 if (Index->isVolatile() || Index->isIndexed())
9100 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9101 if (St->isTruncatingStore())
9104 // The stored memory type must be the same.
9105 if (Index->getMemoryVT() != MemVT)
9108 // We do not allow unaligned stores because we want to prevent overriding
9110 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9113 // We found a potential memory operand to merge.
9114 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9116 // Find the next memory operand in the chain. If the next operand in the
9117 // chain is a store then move up and continue the scan with the next
9118 // memory operand. If the next operand is a load save it and use alias
9119 // information to check if it interferes with anything.
9120 SDNode *NextInChain = Index->getChain().getNode();
9122 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9123 // We found a store node. Use it for the next iteration.
9126 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9127 if (Ldn->isVolatile()) {
9132 // Save the load node for later. Continue the scan.
9133 AliasLoadNodes.push_back(Ldn);
9134 NextInChain = Ldn->getChain().getNode();
9143 // Check if there is anything to merge.
9144 if (StoreNodes.size() < 2)
9147 // Sort the memory operands according to their distance from the base pointer.
9148 std::sort(StoreNodes.begin(), StoreNodes.end(),
9149 [](MemOpLink LHS, MemOpLink RHS) {
9150 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9151 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9152 LHS.SequenceNum > RHS.SequenceNum);
9155 // Scan the memory operations on the chain and find the first non-consecutive
9156 // store memory address.
9157 unsigned LastConsecutiveStore = 0;
9158 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9159 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9161 // Check that the addresses are consecutive starting from the second
9162 // element in the list of stores.
9164 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9165 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9170 // Check if this store interferes with any of the loads that we found.
9171 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9172 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9176 // We found a load that alias with this store. Stop the sequence.
9180 // Mark this node as useful.
9181 LastConsecutiveStore = i;
9184 // The node with the lowest store address.
9185 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9187 // Store the constants into memory as one consecutive store.
9189 unsigned LastLegalType = 0;
9190 unsigned LastLegalVectorType = 0;
9191 bool NonZero = false;
9192 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9193 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9194 SDValue StoredVal = St->getValue();
9196 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9197 NonZero |= !C->isNullValue();
9198 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9199 NonZero |= !C->getConstantFPValue()->isNullValue();
9205 // Find a legal type for the constant store.
9206 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9207 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9208 if (TLI.isTypeLegal(StoreTy))
9209 LastLegalType = i+1;
9210 // Or check whether a truncstore is legal.
9211 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9212 TargetLowering::TypePromoteInteger) {
9213 EVT LegalizedStoredValueTy =
9214 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9215 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9216 LastLegalType = i+1;
9219 // Find a legal type for the vector store.
9220 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9221 if (TLI.isTypeLegal(Ty))
9222 LastLegalVectorType = i + 1;
9225 // We only use vectors if the constant is known to be zero and the
9226 // function is not marked with the noimplicitfloat attribute.
9227 if (NonZero || NoVectors)
9228 LastLegalVectorType = 0;
9230 // Check if we found a legal integer type to store.
9231 if (LastLegalType == 0 && LastLegalVectorType == 0)
9234 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9235 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9237 // Make sure we have something to merge.
9241 unsigned EarliestNodeUsed = 0;
9242 for (unsigned i=0; i < NumElem; ++i) {
9243 // Find a chain for the new wide-store operand. Notice that some
9244 // of the store nodes that we found may not be selected for inclusion
9245 // in the wide store. The chain we use needs to be the chain of the
9246 // earliest store node which is *used* and replaced by the wide store.
9247 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9248 EarliestNodeUsed = i;
9251 // The earliest Node in the DAG.
9252 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9253 SDLoc DL(StoreNodes[0].MemNode);
9257 // Find a legal type for the vector store.
9258 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9259 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9260 StoredVal = DAG.getConstant(0, Ty);
9262 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9263 APInt StoreInt(StoreBW, 0);
9265 // Construct a single integer constant which is made of the smaller
9267 bool IsLE = TLI.isLittleEndian();
9268 for (unsigned i = 0; i < NumElem ; ++i) {
9269 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9270 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9271 SDValue Val = St->getValue();
9272 StoreInt<<=ElementSizeBytes*8;
9273 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9274 StoreInt|=C->getAPIntValue().zext(StoreBW);
9275 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9276 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9278 assert(false && "Invalid constant element type");
9282 // Create the new Load and Store operations.
9283 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9284 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9287 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9288 FirstInChain->getBasePtr(),
9289 FirstInChain->getPointerInfo(),
9291 FirstInChain->getAlignment());
9293 // Replace the first store with the new store
9294 CombineTo(EarliestOp, NewStore);
9295 // Erase all other stores.
9296 for (unsigned i = 0; i < NumElem ; ++i) {
9297 if (StoreNodes[i].MemNode == EarliestOp)
9299 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9300 // ReplaceAllUsesWith will replace all uses that existed when it was
9301 // called, but graph optimizations may cause new ones to appear. For
9302 // example, the case in pr14333 looks like
9304 // St's chain -> St -> another store -> X
9306 // And the only difference from St to the other store is the chain.
9307 // When we change it's chain to be St's chain they become identical,
9308 // get CSEed and the net result is that X is now a use of St.
9309 // Since we know that St is redundant, just iterate.
9310 while (!St->use_empty())
9311 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9312 removeFromWorkList(St);
9319 // Below we handle the case of multiple consecutive stores that
9320 // come from multiple consecutive loads. We merge them into a single
9321 // wide load and a single wide store.
9323 // Look for load nodes which are used by the stored values.
9324 SmallVector<MemOpLink, 8> LoadNodes;
9326 // Find acceptable loads. Loads need to have the same chain (token factor),
9327 // must not be zext, volatile, indexed, and they must be consecutive.
9328 BaseIndexOffset LdBasePtr;
9329 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9330 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9331 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9334 // Loads must only have one use.
9335 if (!Ld->hasNUsesOfValue(1, 0))
9338 // Check that the alignment is the same as the stores.
9339 if (Ld->getAlignment() != St->getAlignment())
9342 // The memory operands must not be volatile.
9343 if (Ld->isVolatile() || Ld->isIndexed())
9346 // We do not accept ext loads.
9347 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9350 // The stored memory type must be the same.
9351 if (Ld->getMemoryVT() != MemVT)
9354 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9355 // If this is not the first ptr that we check.
9356 if (LdBasePtr.Base.getNode()) {
9357 // The base ptr must be the same.
9358 if (!LdPtr.equalBaseIndex(LdBasePtr))
9361 // Check that all other base pointers are the same as this one.
9365 // We found a potential memory operand to merge.
9366 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9369 if (LoadNodes.size() < 2)
9372 // Scan the memory operations on the chain and find the first non-consecutive
9373 // load memory address. These variables hold the index in the store node
9375 unsigned LastConsecutiveLoad = 0;
9376 // This variable refers to the size and not index in the array.
9377 unsigned LastLegalVectorType = 0;
9378 unsigned LastLegalIntegerType = 0;
9379 StartAddress = LoadNodes[0].OffsetFromBase;
9380 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9381 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9382 // All loads much share the same chain.
9383 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9386 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9387 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9389 LastConsecutiveLoad = i;
9391 // Find a legal type for the vector store.
9392 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9393 if (TLI.isTypeLegal(StoreTy))
9394 LastLegalVectorType = i + 1;
9396 // Find a legal type for the integer store.
9397 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9398 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9399 if (TLI.isTypeLegal(StoreTy))
9400 LastLegalIntegerType = i + 1;
9401 // Or check whether a truncstore and extload is legal.
9402 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9403 TargetLowering::TypePromoteInteger) {
9404 EVT LegalizedStoredValueTy =
9405 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9406 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9407 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9408 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9409 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9410 LastLegalIntegerType = i+1;
9414 // Only use vector types if the vector type is larger than the integer type.
9415 // If they are the same, use integers.
9416 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9417 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9419 // We add +1 here because the LastXXX variables refer to location while
9420 // the NumElem refers to array/index size.
9421 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9422 NumElem = std::min(LastLegalType, NumElem);
9427 // The earliest Node in the DAG.
9428 unsigned EarliestNodeUsed = 0;
9429 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9430 for (unsigned i=1; i<NumElem; ++i) {
9431 // Find a chain for the new wide-store operand. Notice that some
9432 // of the store nodes that we found may not be selected for inclusion
9433 // in the wide store. The chain we use needs to be the chain of the
9434 // earliest store node which is *used* and replaced by the wide store.
9435 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9436 EarliestNodeUsed = i;
9439 // Find if it is better to use vectors or integers to load and store
9443 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9445 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9446 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9449 SDLoc LoadDL(LoadNodes[0].MemNode);
9450 SDLoc StoreDL(StoreNodes[0].MemNode);
9452 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9453 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9454 FirstLoad->getChain(),
9455 FirstLoad->getBasePtr(),
9456 FirstLoad->getPointerInfo(),
9457 false, false, false,
9458 FirstLoad->getAlignment());
9460 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9461 FirstInChain->getBasePtr(),
9462 FirstInChain->getPointerInfo(), false, false,
9463 FirstInChain->getAlignment());
9465 // Replace one of the loads with the new load.
9466 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9467 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9468 SDValue(NewLoad.getNode(), 1));
9470 // Remove the rest of the load chains.
9471 for (unsigned i = 1; i < NumElem ; ++i) {
9472 // Replace all chain users of the old load nodes with the chain of the new
9474 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9475 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9478 // Replace the first store with the new store.
9479 CombineTo(EarliestOp, NewStore);
9480 // Erase all other stores.
9481 for (unsigned i = 0; i < NumElem ; ++i) {
9482 // Remove all Store nodes.
9483 if (StoreNodes[i].MemNode == EarliestOp)
9485 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9486 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9487 removeFromWorkList(St);
9494 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9495 StoreSDNode *ST = cast<StoreSDNode>(N);
9496 SDValue Chain = ST->getChain();
9497 SDValue Value = ST->getValue();
9498 SDValue Ptr = ST->getBasePtr();
9500 // If this is a store of a bit convert, store the input value if the
9501 // resultant store does not need a higher alignment than the original.
9502 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9503 ST->isUnindexed()) {
9504 unsigned OrigAlign = ST->getAlignment();
9505 EVT SVT = Value.getOperand(0).getValueType();
9506 unsigned Align = TLI.getDataLayout()->
9507 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9508 if (Align <= OrigAlign &&
9509 ((!LegalOperations && !ST->isVolatile()) ||
9510 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9511 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9512 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9513 ST->isNonTemporal(), OrigAlign,
9517 // Turn 'store undef, Ptr' -> nothing.
9518 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9521 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9522 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9523 // NOTE: If the original store is volatile, this transform must not increase
9524 // the number of stores. For example, on x86-32 an f64 can be stored in one
9525 // processor operation but an i64 (which is not legal) requires two. So the
9526 // transform should not be done in this case.
9527 if (Value.getOpcode() != ISD::TargetConstantFP) {
9529 switch (CFP->getSimpleValueType(0).SimpleTy) {
9530 default: llvm_unreachable("Unknown FP type");
9531 case MVT::f16: // We don't do this for these yet.
9537 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9538 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9539 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9540 bitcastToAPInt().getZExtValue(), MVT::i32);
9541 return DAG.getStore(Chain, SDLoc(N), Tmp,
9542 Ptr, ST->getMemOperand());
9546 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9547 !ST->isVolatile()) ||
9548 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9549 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9550 getZExtValue(), MVT::i64);
9551 return DAG.getStore(Chain, SDLoc(N), Tmp,
9552 Ptr, ST->getMemOperand());
9555 if (!ST->isVolatile() &&
9556 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9557 // Many FP stores are not made apparent until after legalize, e.g. for
9558 // argument passing. Since this is so common, custom legalize the
9559 // 64-bit integer store into two 32-bit stores.
9560 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9561 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9562 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9563 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9565 unsigned Alignment = ST->getAlignment();
9566 bool isVolatile = ST->isVolatile();
9567 bool isNonTemporal = ST->isNonTemporal();
9568 const MDNode *TBAAInfo = ST->getTBAAInfo();
9570 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9571 Ptr, ST->getPointerInfo(),
9572 isVolatile, isNonTemporal,
9573 ST->getAlignment(), TBAAInfo);
9574 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9575 DAG.getConstant(4, Ptr.getValueType()));
9576 Alignment = MinAlign(Alignment, 4U);
9577 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9578 Ptr, ST->getPointerInfo().getWithOffset(4),
9579 isVolatile, isNonTemporal,
9580 Alignment, TBAAInfo);
9581 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9590 // Try to infer better alignment information than the store already has.
9591 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9592 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9593 if (Align > ST->getAlignment())
9594 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9595 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9596 ST->isVolatile(), ST->isNonTemporal(), Align,
9601 // Try transforming a pair floating point load / store ops to integer
9602 // load / store ops.
9603 SDValue NewST = TransformFPLoadStorePair(N);
9604 if (NewST.getNode())
9607 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9608 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9610 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9611 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9614 if (UseAA && ST->isUnindexed()) {
9615 // Walk up chain skipping non-aliasing memory nodes.
9616 SDValue BetterChain = FindBetterChain(N, Chain);
9618 // If there is a better chain.
9619 if (Chain != BetterChain) {
9622 // Replace the chain to avoid dependency.
9623 if (ST->isTruncatingStore()) {
9624 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9625 ST->getMemoryVT(), ST->getMemOperand());
9627 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9628 ST->getMemOperand());
9631 // Create token to keep both nodes around.
9632 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9633 MVT::Other, Chain, ReplStore);
9635 // Make sure the new and old chains are cleaned up.
9636 AddToWorkList(Token.getNode());
9638 // Don't add users to work list.
9639 return CombineTo(N, Token, false);
9643 // Try transforming N to an indexed store.
9644 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9645 return SDValue(N, 0);
9647 // FIXME: is there such a thing as a truncating indexed store?
9648 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9649 Value.getValueType().isInteger()) {
9650 // See if we can simplify the input to this truncstore with knowledge that
9651 // only the low bits are being used. For example:
9652 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9654 GetDemandedBits(Value,
9655 APInt::getLowBitsSet(
9656 Value.getValueType().getScalarType().getSizeInBits(),
9657 ST->getMemoryVT().getScalarType().getSizeInBits()));
9658 AddToWorkList(Value.getNode());
9659 if (Shorter.getNode())
9660 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9661 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9663 // Otherwise, see if we can simplify the operation with
9664 // SimplifyDemandedBits, which only works if the value has a single use.
9665 if (SimplifyDemandedBits(Value,
9666 APInt::getLowBitsSet(
9667 Value.getValueType().getScalarType().getSizeInBits(),
9668 ST->getMemoryVT().getScalarType().getSizeInBits())))
9669 return SDValue(N, 0);
9672 // If this is a load followed by a store to the same location, then the store
9674 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9675 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9676 ST->isUnindexed() && !ST->isVolatile() &&
9677 // There can't be any side effects between the load and store, such as
9679 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9680 // The store is dead, remove it.
9685 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9686 // truncating store. We can do this even if this is already a truncstore.
9687 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9688 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9689 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9690 ST->getMemoryVT())) {
9691 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9692 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9695 // Only perform this optimization before the types are legal, because we
9696 // don't want to perform this optimization on every DAGCombine invocation.
9698 bool EverChanged = false;
9701 // There can be multiple store sequences on the same chain.
9702 // Keep trying to merge store sequences until we are unable to do so
9703 // or until we merge the last store on the chain.
9704 bool Changed = MergeConsecutiveStores(ST);
9705 EverChanged |= Changed;
9706 if (!Changed) break;
9707 } while (ST->getOpcode() != ISD::DELETED_NODE);
9710 return SDValue(N, 0);
9713 return ReduceLoadOpStoreWidth(N);
9716 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9717 SDValue InVec = N->getOperand(0);
9718 SDValue InVal = N->getOperand(1);
9719 SDValue EltNo = N->getOperand(2);
9722 // If the inserted element is an UNDEF, just use the input vector.
9723 if (InVal.getOpcode() == ISD::UNDEF)
9726 EVT VT = InVec.getValueType();
9728 // If we can't generate a legal BUILD_VECTOR, exit
9729 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9732 // Check that we know which element is being inserted
9733 if (!isa<ConstantSDNode>(EltNo))
9735 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9737 // Canonicalize insert_vector_elt dag nodes.
9739 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9740 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9742 // Do this only if the child insert_vector node has one use; also
9743 // do this only if indices are both constants and Idx1 < Idx0.
9744 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9745 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9747 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9748 if (Elt < OtherElt) {
9750 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9751 InVec.getOperand(0), InVal, EltNo);
9752 AddToWorkList(NewOp.getNode());
9753 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9754 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9758 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9759 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9761 SmallVector<SDValue, 8> Ops;
9762 // Do not combine these two vectors if the output vector will not replace
9763 // the input vector.
9764 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9765 Ops.append(InVec.getNode()->op_begin(),
9766 InVec.getNode()->op_end());
9767 } else if (InVec.getOpcode() == ISD::UNDEF) {
9768 unsigned NElts = VT.getVectorNumElements();
9769 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9774 // Insert the element
9775 if (Elt < Ops.size()) {
9776 // All the operands of BUILD_VECTOR must have the same type;
9777 // we enforce that here.
9778 EVT OpVT = Ops[0].getValueType();
9779 if (InVal.getValueType() != OpVT)
9780 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9781 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9782 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9786 // Return the new vector
9787 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9790 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9791 // (vextract (scalar_to_vector val, 0) -> val
9792 SDValue InVec = N->getOperand(0);
9793 EVT VT = InVec.getValueType();
9794 EVT NVT = N->getValueType(0);
9796 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9797 // Check if the result type doesn't match the inserted element type. A
9798 // SCALAR_TO_VECTOR may truncate the inserted element and the
9799 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9800 SDValue InOp = InVec.getOperand(0);
9801 if (InOp.getValueType() != NVT) {
9802 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9803 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9808 SDValue EltNo = N->getOperand(1);
9809 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9811 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9812 // We only perform this optimization before the op legalization phase because
9813 // we may introduce new vector instructions which are not backed by TD
9814 // patterns. For example on AVX, extracting elements from a wide vector
9815 // without using extract_subvector. However, if we can find an underlying
9816 // scalar value, then we can always use that.
9817 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9819 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9820 int NumElem = VT.getVectorNumElements();
9821 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9822 // Find the new index to extract from.
9823 int OrigElt = SVOp->getMaskElt(Elt);
9825 // Extracting an undef index is undef.
9827 return DAG.getUNDEF(NVT);
9829 // Select the right vector half to extract from.
9831 if (OrigElt < NumElem) {
9832 SVInVec = InVec->getOperand(0);
9834 SVInVec = InVec->getOperand(1);
9838 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9839 SDValue InOp = SVInVec.getOperand(OrigElt);
9840 if (InOp.getValueType() != NVT) {
9841 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9842 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9848 // FIXME: We should handle recursing on other vector shuffles and
9849 // scalar_to_vector here as well.
9851 if (!LegalOperations) {
9852 EVT IndexTy = TLI.getVectorIdxTy();
9853 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9854 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9858 // Perform only after legalization to ensure build_vector / vector_shuffle
9859 // optimizations have already been done.
9860 if (!LegalOperations) return SDValue();
9862 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9863 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9864 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9867 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9868 bool NewLoad = false;
9869 bool BCNumEltsChanged = false;
9870 EVT ExtVT = VT.getVectorElementType();
9873 // If the result of load has to be truncated, then it's not necessarily
9875 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9878 if (InVec.getOpcode() == ISD::BITCAST) {
9879 // Don't duplicate a load with other uses.
9880 if (!InVec.hasOneUse())
9883 EVT BCVT = InVec.getOperand(0).getValueType();
9884 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9886 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9887 BCNumEltsChanged = true;
9888 InVec = InVec.getOperand(0);
9889 ExtVT = BCVT.getVectorElementType();
9893 LoadSDNode *LN0 = nullptr;
9894 const ShuffleVectorSDNode *SVN = nullptr;
9895 if (ISD::isNormalLoad(InVec.getNode())) {
9896 LN0 = cast<LoadSDNode>(InVec);
9897 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9898 InVec.getOperand(0).getValueType() == ExtVT &&
9899 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9900 // Don't duplicate a load with other uses.
9901 if (!InVec.hasOneUse())
9904 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9905 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9906 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9908 // (load $addr+1*size)
9910 // Don't duplicate a load with other uses.
9911 if (!InVec.hasOneUse())
9914 // If the bit convert changed the number of elements, it is unsafe
9915 // to examine the mask.
9916 if (BCNumEltsChanged)
9919 // Select the input vector, guarding against out of range extract vector.
9920 unsigned NumElems = VT.getVectorNumElements();
9921 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9922 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9924 if (InVec.getOpcode() == ISD::BITCAST) {
9925 // Don't duplicate a load with other uses.
9926 if (!InVec.hasOneUse())
9929 InVec = InVec.getOperand(0);
9931 if (ISD::isNormalLoad(InVec.getNode())) {
9932 LN0 = cast<LoadSDNode>(InVec);
9933 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9937 // Make sure we found a non-volatile load and the extractelement is
9939 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9942 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9944 return DAG.getUNDEF(LVT);
9946 unsigned Align = LN0->getAlignment();
9948 // Check the resultant load doesn't need a higher alignment than the
9952 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9954 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9960 SDValue NewPtr = LN0->getBasePtr();
9961 unsigned PtrOff = 0;
9964 PtrOff = LVT.getSizeInBits() * Elt / 8;
9965 EVT PtrType = NewPtr.getValueType();
9966 if (TLI.isBigEndian())
9967 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9968 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9969 DAG.getConstant(PtrOff, PtrType));
9972 // The replacement we need to do here is a little tricky: we need to
9973 // replace an extractelement of a load with a load.
9974 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9975 // Note that this replacement assumes that the extractvalue is the only
9976 // use of the load; that's okay because we don't want to perform this
9977 // transformation in other cases anyway.
9980 if (NVT.bitsGT(LVT)) {
9981 // If the result type of vextract is wider than the load, then issue an
9982 // extending load instead.
9983 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9984 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9985 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9986 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9987 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9988 Align, LN0->getTBAAInfo());
9989 Chain = Load.getValue(1);
9991 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9992 LN0->getPointerInfo().getWithOffset(PtrOff),
9993 LN0->isVolatile(), LN0->isNonTemporal(),
9994 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9995 Chain = Load.getValue(1);
9996 if (NVT.bitsLT(LVT))
9997 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9999 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10001 WorkListRemover DeadNodes(*this);
10002 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10003 SDValue To[] = { Load, Chain };
10004 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10005 // Since we're explcitly calling ReplaceAllUses, add the new node to the
10006 // worklist explicitly as well.
10007 AddToWorkList(Load.getNode());
10008 AddUsersToWorkList(Load.getNode()); // Add users too
10009 // Make sure to revisit this node to clean it up; it will usually be dead.
10011 return SDValue(N, 0);
10017 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10018 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10019 // We perform this optimization post type-legalization because
10020 // the type-legalizer often scalarizes integer-promoted vectors.
10021 // Performing this optimization before may create bit-casts which
10022 // will be type-legalized to complex code sequences.
10023 // We perform this optimization only before the operation legalizer because we
10024 // may introduce illegal operations.
10025 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10028 unsigned NumInScalars = N->getNumOperands();
10030 EVT VT = N->getValueType(0);
10032 // Check to see if this is a BUILD_VECTOR of a bunch of values
10033 // which come from any_extend or zero_extend nodes. If so, we can create
10034 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10035 // optimizations. We do not handle sign-extend because we can't fill the sign
10037 EVT SourceType = MVT::Other;
10038 bool AllAnyExt = true;
10040 for (unsigned i = 0; i != NumInScalars; ++i) {
10041 SDValue In = N->getOperand(i);
10042 // Ignore undef inputs.
10043 if (In.getOpcode() == ISD::UNDEF) continue;
10045 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10046 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10048 // Abort if the element is not an extension.
10049 if (!ZeroExt && !AnyExt) {
10050 SourceType = MVT::Other;
10054 // The input is a ZeroExt or AnyExt. Check the original type.
10055 EVT InTy = In.getOperand(0).getValueType();
10057 // Check that all of the widened source types are the same.
10058 if (SourceType == MVT::Other)
10061 else if (InTy != SourceType) {
10062 // Multiple income types. Abort.
10063 SourceType = MVT::Other;
10067 // Check if all of the extends are ANY_EXTENDs.
10068 AllAnyExt &= AnyExt;
10071 // In order to have valid types, all of the inputs must be extended from the
10072 // same source type and all of the inputs must be any or zero extend.
10073 // Scalar sizes must be a power of two.
10074 EVT OutScalarTy = VT.getScalarType();
10075 bool ValidTypes = SourceType != MVT::Other &&
10076 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10077 isPowerOf2_32(SourceType.getSizeInBits());
10079 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10080 // turn into a single shuffle instruction.
10084 bool isLE = TLI.isLittleEndian();
10085 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10086 assert(ElemRatio > 1 && "Invalid element size ratio");
10087 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10088 DAG.getConstant(0, SourceType);
10090 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10091 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10093 // Populate the new build_vector
10094 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10095 SDValue Cast = N->getOperand(i);
10096 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10097 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10098 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10100 if (Cast.getOpcode() == ISD::UNDEF)
10101 In = DAG.getUNDEF(SourceType);
10103 In = Cast->getOperand(0);
10104 unsigned Index = isLE ? (i * ElemRatio) :
10105 (i * ElemRatio + (ElemRatio - 1));
10107 assert(Index < Ops.size() && "Invalid index");
10111 // The type of the new BUILD_VECTOR node.
10112 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10113 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10114 "Invalid vector size");
10115 // Check if the new vector type is legal.
10116 if (!isTypeLegal(VecVT)) return SDValue();
10118 // Make the new BUILD_VECTOR.
10119 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10121 // The new BUILD_VECTOR node has the potential to be further optimized.
10122 AddToWorkList(BV.getNode());
10123 // Bitcast to the desired type.
10124 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10127 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10128 EVT VT = N->getValueType(0);
10130 unsigned NumInScalars = N->getNumOperands();
10133 EVT SrcVT = MVT::Other;
10134 unsigned Opcode = ISD::DELETED_NODE;
10135 unsigned NumDefs = 0;
10137 for (unsigned i = 0; i != NumInScalars; ++i) {
10138 SDValue In = N->getOperand(i);
10139 unsigned Opc = In.getOpcode();
10141 if (Opc == ISD::UNDEF)
10144 // If all scalar values are floats and converted from integers.
10145 if (Opcode == ISD::DELETED_NODE &&
10146 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10153 EVT InVT = In.getOperand(0).getValueType();
10155 // If all scalar values are typed differently, bail out. It's chosen to
10156 // simplify BUILD_VECTOR of integer types.
10157 if (SrcVT == MVT::Other)
10164 // If the vector has just one element defined, it's not worth to fold it into
10165 // a vectorized one.
10169 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10170 && "Should only handle conversion from integer to float.");
10171 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10173 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10175 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10178 SmallVector<SDValue, 8> Opnds;
10179 for (unsigned i = 0; i != NumInScalars; ++i) {
10180 SDValue In = N->getOperand(i);
10182 if (In.getOpcode() == ISD::UNDEF)
10183 Opnds.push_back(DAG.getUNDEF(SrcVT));
10185 Opnds.push_back(In.getOperand(0));
10187 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10188 AddToWorkList(BV.getNode());
10190 return DAG.getNode(Opcode, dl, VT, BV);
10193 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10194 unsigned NumInScalars = N->getNumOperands();
10196 EVT VT = N->getValueType(0);
10198 // A vector built entirely of undefs is undef.
10199 if (ISD::allOperandsUndef(N))
10200 return DAG.getUNDEF(VT);
10202 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10206 V = reduceBuildVecConvertToConvertBuildVec(N);
10210 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10211 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10212 // at most two distinct vectors, turn this into a shuffle node.
10214 // May only combine to shuffle after legalize if shuffle is legal.
10215 if (LegalOperations &&
10216 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10219 SDValue VecIn1, VecIn2;
10220 for (unsigned i = 0; i != NumInScalars; ++i) {
10221 // Ignore undef inputs.
10222 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10224 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10225 // constant index, bail out.
10226 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10227 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10228 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10232 // We allow up to two distinct input vectors.
10233 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10234 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10237 if (!VecIn1.getNode()) {
10238 VecIn1 = ExtractedFromVec;
10239 } else if (!VecIn2.getNode()) {
10240 VecIn2 = ExtractedFromVec;
10242 // Too many inputs.
10243 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10248 // If everything is good, we can make a shuffle operation.
10249 if (VecIn1.getNode()) {
10250 SmallVector<int, 8> Mask;
10251 for (unsigned i = 0; i != NumInScalars; ++i) {
10252 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10253 Mask.push_back(-1);
10257 // If extracting from the first vector, just use the index directly.
10258 SDValue Extract = N->getOperand(i);
10259 SDValue ExtVal = Extract.getOperand(1);
10260 if (Extract.getOperand(0) == VecIn1) {
10261 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10262 if (ExtIndex > VT.getVectorNumElements())
10265 Mask.push_back(ExtIndex);
10269 // Otherwise, use InIdx + VecSize
10270 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10271 Mask.push_back(Idx+NumInScalars);
10274 // We can't generate a shuffle node with mismatched input and output types.
10275 // Attempt to transform a single input vector to the correct type.
10276 if ((VT != VecIn1.getValueType())) {
10277 // We don't support shuffeling between TWO values of different types.
10278 if (VecIn2.getNode())
10281 // We only support widening of vectors which are half the size of the
10282 // output registers. For example XMM->YMM widening on X86 with AVX.
10283 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10286 // If the input vector type has a different base type to the output
10287 // vector type, bail out.
10288 if (VecIn1.getValueType().getVectorElementType() !=
10289 VT.getVectorElementType())
10292 // Widen the input vector by adding undef values.
10293 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10294 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10297 // If VecIn2 is unused then change it to undef.
10298 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10300 // Check that we were able to transform all incoming values to the same
10302 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10303 VecIn1.getValueType() != VT)
10306 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10307 if (!isTypeLegal(VT))
10310 // Return the new VECTOR_SHUFFLE node.
10314 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10320 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10321 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10322 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10323 // inputs come from at most two distinct vectors, turn this into a shuffle
10326 // If we only have one input vector, we don't need to do any concatenation.
10327 if (N->getNumOperands() == 1)
10328 return N->getOperand(0);
10330 // Check if all of the operands are undefs.
10331 EVT VT = N->getValueType(0);
10332 if (ISD::allOperandsUndef(N))
10333 return DAG.getUNDEF(VT);
10335 // Optimize concat_vectors where one of the vectors is undef.
10336 if (N->getNumOperands() == 2 &&
10337 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10338 SDValue In = N->getOperand(0);
10339 assert(In.getValueType().isVector() && "Must concat vectors");
10341 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10342 if (In->getOpcode() == ISD::BITCAST &&
10343 !In->getOperand(0)->getValueType(0).isVector()) {
10344 SDValue Scalar = In->getOperand(0);
10345 EVT SclTy = Scalar->getValueType(0);
10347 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10350 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10351 VT.getSizeInBits() / SclTy.getSizeInBits());
10352 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10355 SDLoc dl = SDLoc(N);
10356 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10357 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10361 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10362 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10363 if (N->getNumOperands() == 2 &&
10364 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10365 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10366 EVT VT = N->getValueType(0);
10367 SDValue N0 = N->getOperand(0);
10368 SDValue N1 = N->getOperand(1);
10369 SmallVector<SDValue, 8> Opnds;
10370 unsigned BuildVecNumElts = N0.getNumOperands();
10372 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10373 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10374 if (SclTy0.isFloatingPoint()) {
10375 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10376 Opnds.push_back(N0.getOperand(i));
10377 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10378 Opnds.push_back(N1.getOperand(i));
10380 // If BUILD_VECTOR are from built from integer, they may have different
10381 // operand types. Get the smaller type and truncate all operands to it.
10382 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10383 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10384 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10385 N0.getOperand(i)));
10386 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10387 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10388 N1.getOperand(i)));
10391 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10394 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10395 // nodes often generate nop CONCAT_VECTOR nodes.
10396 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10397 // place the incoming vectors at the exact same location.
10398 SDValue SingleSource = SDValue();
10399 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10401 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10402 SDValue Op = N->getOperand(i);
10404 if (Op.getOpcode() == ISD::UNDEF)
10407 // Check if this is the identity extract:
10408 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10411 // Find the single incoming vector for the extract_subvector.
10412 if (SingleSource.getNode()) {
10413 if (Op.getOperand(0) != SingleSource)
10416 SingleSource = Op.getOperand(0);
10418 // Check the source type is the same as the type of the result.
10419 // If not, this concat may extend the vector, so we can not
10420 // optimize it away.
10421 if (SingleSource.getValueType() != N->getValueType(0))
10425 unsigned IdentityIndex = i * PartNumElem;
10426 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10427 // The extract index must be constant.
10431 // Check that we are reading from the identity index.
10432 if (CS->getZExtValue() != IdentityIndex)
10436 if (SingleSource.getNode())
10437 return SingleSource;
10442 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10443 EVT NVT = N->getValueType(0);
10444 SDValue V = N->getOperand(0);
10446 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10448 // (extract_subvec (concat V1, V2, ...), i)
10451 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10453 if (V->getOperand(0).getValueType() != NVT)
10455 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10456 unsigned NumElems = NVT.getVectorNumElements();
10457 assert((Idx % NumElems) == 0 &&
10458 "IDX in concat is not a multiple of the result vector length.");
10459 return V->getOperand(Idx / NumElems);
10463 if (V->getOpcode() == ISD::BITCAST)
10464 V = V.getOperand(0);
10466 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10468 // Handle only simple case where vector being inserted and vector
10469 // being extracted are of same type, and are half size of larger vectors.
10470 EVT BigVT = V->getOperand(0).getValueType();
10471 EVT SmallVT = V->getOperand(1).getValueType();
10472 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10475 // Only handle cases where both indexes are constants with the same type.
10476 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10477 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10479 if (InsIdx && ExtIdx &&
10480 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10481 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10483 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10485 // indices are equal or bit offsets are equal => V1
10486 // otherwise => (extract_subvec V1, ExtIdx)
10487 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10488 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10489 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10490 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10491 DAG.getNode(ISD::BITCAST, dl,
10492 N->getOperand(0).getValueType(),
10493 V->getOperand(0)), N->getOperand(1));
10500 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10501 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10502 EVT VT = N->getValueType(0);
10503 unsigned NumElts = VT.getVectorNumElements();
10505 SDValue N0 = N->getOperand(0);
10506 SDValue N1 = N->getOperand(1);
10507 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10509 SmallVector<SDValue, 4> Ops;
10510 EVT ConcatVT = N0.getOperand(0).getValueType();
10511 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10512 unsigned NumConcats = NumElts / NumElemsPerConcat;
10514 // Look at every vector that's inserted. We're looking for exact
10515 // subvector-sized copies from a concatenated vector
10516 for (unsigned I = 0; I != NumConcats; ++I) {
10517 // Make sure we're dealing with a copy.
10518 unsigned Begin = I * NumElemsPerConcat;
10519 bool AllUndef = true, NoUndef = true;
10520 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10521 if (SVN->getMaskElt(J) >= 0)
10528 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10531 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10532 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10535 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10536 if (FirstElt < N0.getNumOperands())
10537 Ops.push_back(N0.getOperand(FirstElt));
10539 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10541 } else if (AllUndef) {
10542 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10543 } else { // Mixed with general masks and undefs, can't do optimization.
10548 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10551 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10552 EVT VT = N->getValueType(0);
10553 unsigned NumElts = VT.getVectorNumElements();
10555 SDValue N0 = N->getOperand(0);
10556 SDValue N1 = N->getOperand(1);
10558 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10560 // Canonicalize shuffle undef, undef -> undef
10561 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10562 return DAG.getUNDEF(VT);
10564 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10566 // Canonicalize shuffle v, v -> v, undef
10568 SmallVector<int, 8> NewMask;
10569 for (unsigned i = 0; i != NumElts; ++i) {
10570 int Idx = SVN->getMaskElt(i);
10571 if (Idx >= (int)NumElts) Idx -= NumElts;
10572 NewMask.push_back(Idx);
10574 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10578 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10579 if (N0.getOpcode() == ISD::UNDEF) {
10580 SmallVector<int, 8> NewMask;
10581 for (unsigned i = 0; i != NumElts; ++i) {
10582 int Idx = SVN->getMaskElt(i);
10584 if (Idx >= (int)NumElts)
10587 Idx = -1; // remove reference to lhs
10589 NewMask.push_back(Idx);
10591 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10595 // Remove references to rhs if it is undef
10596 if (N1.getOpcode() == ISD::UNDEF) {
10597 bool Changed = false;
10598 SmallVector<int, 8> NewMask;
10599 for (unsigned i = 0; i != NumElts; ++i) {
10600 int Idx = SVN->getMaskElt(i);
10601 if (Idx >= (int)NumElts) {
10605 NewMask.push_back(Idx);
10608 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10611 // If it is a splat, check if the argument vector is another splat or a
10612 // build_vector with all scalar elements the same.
10613 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10614 SDNode *V = N0.getNode();
10616 // If this is a bit convert that changes the element type of the vector but
10617 // not the number of vector elements, look through it. Be careful not to
10618 // look though conversions that change things like v4f32 to v2f64.
10619 if (V->getOpcode() == ISD::BITCAST) {
10620 SDValue ConvInput = V->getOperand(0);
10621 if (ConvInput.getValueType().isVector() &&
10622 ConvInput.getValueType().getVectorNumElements() == NumElts)
10623 V = ConvInput.getNode();
10626 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10627 assert(V->getNumOperands() == NumElts &&
10628 "BUILD_VECTOR has wrong number of operands");
10630 bool AllSame = true;
10631 for (unsigned i = 0; i != NumElts; ++i) {
10632 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10633 Base = V->getOperand(i);
10637 // Splat of <u, u, u, u>, return <u, u, u, u>
10638 if (!Base.getNode())
10640 for (unsigned i = 0; i != NumElts; ++i) {
10641 if (V->getOperand(i) != Base) {
10646 // Splat of <x, x, x, x>, return <x, x, x, x>
10652 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10653 Level < AfterLegalizeVectorOps &&
10654 (N1.getOpcode() == ISD::UNDEF ||
10655 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10656 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10657 SDValue V = partitionShuffleOfConcats(N, DAG);
10663 // If this shuffle node is simply a swizzle of another shuffle node,
10664 // then try to simplify it.
10665 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10666 N1.getOpcode() == ISD::UNDEF) {
10668 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10670 // The incoming shuffle must be of the same type as the result of the
10671 // current shuffle.
10672 assert(OtherSV->getOperand(0).getValueType() == VT &&
10673 "Shuffle types don't match");
10675 SmallVector<int, 4> Mask;
10676 // Compute the combined shuffle mask.
10677 for (unsigned i = 0; i != NumElts; ++i) {
10678 int Idx = SVN->getMaskElt(i);
10679 assert(Idx < (int)NumElts && "Index references undef operand");
10680 // Next, this index comes from the first value, which is the incoming
10681 // shuffle. Adopt the incoming index.
10683 Idx = OtherSV->getMaskElt(Idx);
10684 Mask.push_back(Idx);
10687 bool CommuteOperands = false;
10688 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10689 // To be valid, the combine shuffle mask should only reference elements
10690 // from one of the two vectors in input to the inner shufflevector.
10691 bool IsValidMask = true;
10692 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10693 // See if the combined mask only reference undefs or elements coming
10694 // from the first shufflevector operand.
10695 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10697 if (!IsValidMask) {
10698 IsValidMask = true;
10699 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10700 // Check that all the elements come from the second shuffle operand.
10701 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10702 CommuteOperands = IsValidMask;
10705 // Early exit if the combined shuffle mask is not valid.
10710 // See if this pair of shuffles can be safely folded according to either
10711 // of the following rules:
10712 // shuffle(shuffle(x, y), undef) -> x
10713 // shuffle(shuffle(x, undef), undef) -> x
10714 // shuffle(shuffle(x, y), undef) -> y
10715 bool IsIdentityMask = true;
10716 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10717 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10722 // The combined shuffle must map each index to itself.
10723 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10726 if (IsIdentityMask) {
10727 if (CommuteOperands)
10728 // optimize shuffle(shuffle(x, y), undef) -> y.
10729 return OtherSV->getOperand(1);
10731 // optimize shuffle(shuffle(x, undef), undef) -> x
10732 // optimize shuffle(shuffle(x, y), undef) -> x
10733 return OtherSV->getOperand(0);
10736 // It may still be beneficial to combine the two shuffles if the
10737 // resulting shuffle is legal.
10738 if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10739 if (!CommuteOperands)
10740 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10741 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10742 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10745 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10746 return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10751 // Canonicalize shuffles according to rules:
10752 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10753 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10754 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10755 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10756 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10757 TLI.isTypeLegal(VT)) {
10758 // The incoming shuffle must be of the same type as the result of the
10759 // current shuffle.
10760 assert(N1->getOperand(0).getValueType() == VT &&
10761 "Shuffle types don't match");
10763 SDValue SV0 = N1->getOperand(0);
10764 SDValue SV1 = N1->getOperand(1);
10765 bool HasSameOp0 = N0 == SV0;
10766 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10767 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10768 // Commute the operands of this shuffle so that next rule
10770 return DAG.getCommutedVectorShuffle(*SVN);
10773 // Try to fold according to rules:
10774 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10775 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10776 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10777 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10778 // Don't try to fold shuffles with illegal type.
10779 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10780 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10781 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10783 // The incoming shuffle must be of the same type as the result of the
10784 // current shuffle.
10785 assert(OtherSV->getOperand(0).getValueType() == VT &&
10786 "Shuffle types don't match");
10788 SDValue SV0 = OtherSV->getOperand(0);
10789 SDValue SV1 = OtherSV->getOperand(1);
10790 bool HasSameOp0 = N1 == SV0;
10791 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10792 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10796 SmallVector<int, 4> Mask;
10797 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10798 // operand, and SV1 as the second operand.
10799 for (unsigned i = 0; i != NumElts; ++i) {
10800 int Idx = SVN->getMaskElt(i);
10802 // Propagate Undef.
10803 Mask.push_back(Idx);
10807 if (Idx < (int)NumElts) {
10808 Idx = OtherSV->getMaskElt(Idx);
10809 if (IsSV1Undef && Idx >= (int) NumElts)
10810 Idx = -1; // Propagate Undef.
10812 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10814 Mask.push_back(Idx);
10817 // Avoid introducing shuffles with illegal mask.
10818 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10820 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10821 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10822 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10823 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10830 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10831 SDValue N0 = N->getOperand(0);
10832 SDValue N2 = N->getOperand(2);
10834 // If the input vector is a concatenation, and the insert replaces
10835 // one of the halves, we can optimize into a single concat_vectors.
10836 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10837 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10838 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10839 EVT VT = N->getValueType(0);
10841 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10842 // (concat_vectors Z, Y)
10844 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10845 N->getOperand(1), N0.getOperand(1));
10847 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10848 // (concat_vectors X, Z)
10849 if (InsIdx == VT.getVectorNumElements()/2)
10850 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10851 N0.getOperand(0), N->getOperand(1));
10857 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10858 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10859 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10860 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10861 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10862 EVT VT = N->getValueType(0);
10864 SDValue LHS = N->getOperand(0);
10865 SDValue RHS = N->getOperand(1);
10866 if (N->getOpcode() == ISD::AND) {
10867 if (RHS.getOpcode() == ISD::BITCAST)
10868 RHS = RHS.getOperand(0);
10869 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10870 SmallVector<int, 8> Indices;
10871 unsigned NumElts = RHS.getNumOperands();
10872 for (unsigned i = 0; i != NumElts; ++i) {
10873 SDValue Elt = RHS.getOperand(i);
10874 if (!isa<ConstantSDNode>(Elt))
10877 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10878 Indices.push_back(i);
10879 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10880 Indices.push_back(NumElts);
10885 // Let's see if the target supports this vector_shuffle.
10886 EVT RVT = RHS.getValueType();
10887 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10890 // Return the new VECTOR_SHUFFLE node.
10891 EVT EltVT = RVT.getVectorElementType();
10892 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10893 DAG.getConstant(0, EltVT));
10894 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10895 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10896 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10897 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10904 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10905 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10906 assert(N->getValueType(0).isVector() &&
10907 "SimplifyVBinOp only works on vectors!");
10909 SDValue LHS = N->getOperand(0);
10910 SDValue RHS = N->getOperand(1);
10911 SDValue Shuffle = XformToShuffleWithZero(N);
10912 if (Shuffle.getNode()) return Shuffle;
10914 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10916 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10917 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10918 // Check if both vectors are constants. If not bail out.
10919 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10920 cast<BuildVectorSDNode>(RHS)->isConstant()))
10923 SmallVector<SDValue, 8> Ops;
10924 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10925 SDValue LHSOp = LHS.getOperand(i);
10926 SDValue RHSOp = RHS.getOperand(i);
10928 // Can't fold divide by zero.
10929 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10930 N->getOpcode() == ISD::FDIV) {
10931 if ((RHSOp.getOpcode() == ISD::Constant &&
10932 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10933 (RHSOp.getOpcode() == ISD::ConstantFP &&
10934 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10938 EVT VT = LHSOp.getValueType();
10939 EVT RVT = RHSOp.getValueType();
10941 // Integer BUILD_VECTOR operands may have types larger than the element
10942 // size (e.g., when the element type is not legal). Prior to type
10943 // legalization, the types may not match between the two BUILD_VECTORS.
10944 // Truncate one of the operands to make them match.
10945 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10946 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10948 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10952 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10954 if (FoldOp.getOpcode() != ISD::UNDEF &&
10955 FoldOp.getOpcode() != ISD::Constant &&
10956 FoldOp.getOpcode() != ISD::ConstantFP)
10958 Ops.push_back(FoldOp);
10959 AddToWorkList(FoldOp.getNode());
10962 if (Ops.size() == LHS.getNumOperands())
10963 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10966 // Type legalization might introduce new shuffles in the DAG.
10967 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10968 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
10969 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10970 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10971 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10972 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10973 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10974 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10976 if (SVN0->getMask().equals(SVN1->getMask())) {
10977 EVT VT = N->getValueType(0);
10978 SDValue UndefVector = LHS.getOperand(1);
10979 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10980 LHS.getOperand(0), RHS.getOperand(0));
10981 AddUsersToWorkList(N);
10982 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10983 &SVN0->getMask()[0]);
10990 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10991 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10992 assert(N->getValueType(0).isVector() &&
10993 "SimplifyVUnaryOp only works on vectors!");
10995 SDValue N0 = N->getOperand(0);
10997 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11000 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11001 SmallVector<SDValue, 8> Ops;
11002 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11003 SDValue Op = N0.getOperand(i);
11004 if (Op.getOpcode() != ISD::UNDEF &&
11005 Op.getOpcode() != ISD::ConstantFP)
11007 EVT EltVT = Op.getValueType();
11008 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11009 if (FoldOp.getOpcode() != ISD::UNDEF &&
11010 FoldOp.getOpcode() != ISD::ConstantFP)
11012 Ops.push_back(FoldOp);
11013 AddToWorkList(FoldOp.getNode());
11016 if (Ops.size() != N0.getNumOperands())
11019 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11022 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11023 SDValue N1, SDValue N2){
11024 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11026 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11027 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11029 // If we got a simplified select_cc node back from SimplifySelectCC, then
11030 // break it down into a new SETCC node, and a new SELECT node, and then return
11031 // the SELECT node, since we were called with a SELECT node.
11032 if (SCC.getNode()) {
11033 // Check to see if we got a select_cc back (to turn into setcc/select).
11034 // Otherwise, just return whatever node we got back, like fabs.
11035 if (SCC.getOpcode() == ISD::SELECT_CC) {
11036 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11038 SCC.getOperand(0), SCC.getOperand(1),
11039 SCC.getOperand(4));
11040 AddToWorkList(SETCC.getNode());
11041 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11042 SCC.getOperand(2), SCC.getOperand(3), SETCC);
11050 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11051 /// are the two values being selected between, see if we can simplify the
11052 /// select. Callers of this should assume that TheSelect is deleted if this
11053 /// returns true. As such, they should return the appropriate thing (e.g. the
11054 /// node) back to the top-level of the DAG combiner loop to avoid it being
11056 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11059 // Cannot simplify select with vector condition
11060 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11062 // If this is a select from two identical things, try to pull the operation
11063 // through the select.
11064 if (LHS.getOpcode() != RHS.getOpcode() ||
11065 !LHS.hasOneUse() || !RHS.hasOneUse())
11068 // If this is a load and the token chain is identical, replace the select
11069 // of two loads with a load through a select of the address to load from.
11070 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11071 // constants have been dropped into the constant pool.
11072 if (LHS.getOpcode() == ISD::LOAD) {
11073 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11074 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11076 // Token chains must be identical.
11077 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11078 // Do not let this transformation reduce the number of volatile loads.
11079 LLD->isVolatile() || RLD->isVolatile() ||
11080 // If this is an EXTLOAD, the VT's must match.
11081 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11082 // If this is an EXTLOAD, the kind of extension must match.
11083 (LLD->getExtensionType() != RLD->getExtensionType() &&
11084 // The only exception is if one of the extensions is anyext.
11085 LLD->getExtensionType() != ISD::EXTLOAD &&
11086 RLD->getExtensionType() != ISD::EXTLOAD) ||
11087 // FIXME: this discards src value information. This is
11088 // over-conservative. It would be beneficial to be able to remember
11089 // both potential memory locations. Since we are discarding
11090 // src value info, don't do the transformation if the memory
11091 // locations are not in the default address space.
11092 LLD->getPointerInfo().getAddrSpace() != 0 ||
11093 RLD->getPointerInfo().getAddrSpace() != 0 ||
11094 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11095 LLD->getBasePtr().getValueType()))
11098 // Check that the select condition doesn't reach either load. If so,
11099 // folding this will induce a cycle into the DAG. If not, this is safe to
11100 // xform, so create a select of the addresses.
11102 if (TheSelect->getOpcode() == ISD::SELECT) {
11103 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11104 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11105 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11107 // The loads must not depend on one another.
11108 if (LLD->isPredecessorOf(RLD) ||
11109 RLD->isPredecessorOf(LLD))
11111 Addr = DAG.getSelect(SDLoc(TheSelect),
11112 LLD->getBasePtr().getValueType(),
11113 TheSelect->getOperand(0), LLD->getBasePtr(),
11114 RLD->getBasePtr());
11115 } else { // Otherwise SELECT_CC
11116 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11117 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11119 if ((LLD->hasAnyUseOfValue(1) &&
11120 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11121 (RLD->hasAnyUseOfValue(1) &&
11122 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11125 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11126 LLD->getBasePtr().getValueType(),
11127 TheSelect->getOperand(0),
11128 TheSelect->getOperand(1),
11129 LLD->getBasePtr(), RLD->getBasePtr(),
11130 TheSelect->getOperand(4));
11134 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11135 Load = DAG.getLoad(TheSelect->getValueType(0),
11137 // FIXME: Discards pointer and TBAA info.
11138 LLD->getChain(), Addr, MachinePointerInfo(),
11139 LLD->isVolatile(), LLD->isNonTemporal(),
11140 LLD->isInvariant(), LLD->getAlignment());
11142 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11143 RLD->getExtensionType() : LLD->getExtensionType(),
11145 TheSelect->getValueType(0),
11146 // FIXME: Discards pointer and TBAA info.
11147 LLD->getChain(), Addr, MachinePointerInfo(),
11148 LLD->getMemoryVT(), LLD->isVolatile(),
11149 LLD->isNonTemporal(), LLD->getAlignment());
11152 // Users of the select now use the result of the load.
11153 CombineTo(TheSelect, Load);
11155 // Users of the old loads now use the new load's chain. We know the
11156 // old-load value is dead now.
11157 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11158 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11165 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11166 /// where 'cond' is the comparison specified by CC.
11167 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11168 SDValue N2, SDValue N3,
11169 ISD::CondCode CC, bool NotExtCompare) {
11170 // (x ? y : y) -> y.
11171 if (N2 == N3) return N2;
11173 EVT VT = N2.getValueType();
11174 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11175 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11176 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11178 // Determine if the condition we're dealing with is constant
11179 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11180 N0, N1, CC, DL, false);
11181 if (SCC.getNode()) AddToWorkList(SCC.getNode());
11182 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11184 // fold select_cc true, x, y -> x
11185 if (SCCC && !SCCC->isNullValue())
11187 // fold select_cc false, x, y -> y
11188 if (SCCC && SCCC->isNullValue())
11191 // Check to see if we can simplify the select into an fabs node
11192 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11193 // Allow either -0.0 or 0.0
11194 if (CFP->getValueAPF().isZero()) {
11195 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11196 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11197 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11198 N2 == N3.getOperand(0))
11199 return DAG.getNode(ISD::FABS, DL, VT, N0);
11201 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11202 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11203 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11204 N2.getOperand(0) == N3)
11205 return DAG.getNode(ISD::FABS, DL, VT, N3);
11209 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11210 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11211 // in it. This is a win when the constant is not otherwise available because
11212 // it replaces two constant pool loads with one. We only do this if the FP
11213 // type is known to be legal, because if it isn't, then we are before legalize
11214 // types an we want the other legalization to happen first (e.g. to avoid
11215 // messing with soft float) and if the ConstantFP is not legal, because if
11216 // it is legal, we may not need to store the FP constant in a constant pool.
11217 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11218 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11219 if (TLI.isTypeLegal(N2.getValueType()) &&
11220 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11221 TargetLowering::Legal &&
11222 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11223 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11224 // If both constants have multiple uses, then we won't need to do an
11225 // extra load, they are likely around in registers for other users.
11226 (TV->hasOneUse() || FV->hasOneUse())) {
11227 Constant *Elts[] = {
11228 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11229 const_cast<ConstantFP*>(TV->getConstantFPValue())
11231 Type *FPTy = Elts[0]->getType();
11232 const DataLayout &TD = *TLI.getDataLayout();
11234 // Create a ConstantArray of the two constants.
11235 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11236 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11237 TD.getPrefTypeAlignment(FPTy));
11238 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11240 // Get the offsets to the 0 and 1 element of the array so that we can
11241 // select between them.
11242 SDValue Zero = DAG.getIntPtrConstant(0);
11243 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11244 SDValue One = DAG.getIntPtrConstant(EltSize);
11246 SDValue Cond = DAG.getSetCC(DL,
11247 getSetCCResultType(N0.getValueType()),
11249 AddToWorkList(Cond.getNode());
11250 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11252 AddToWorkList(CstOffset.getNode());
11253 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11255 AddToWorkList(CPIdx.getNode());
11256 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11257 MachinePointerInfo::getConstantPool(), false,
11258 false, false, Alignment);
11263 // Check to see if we can perform the "gzip trick", transforming
11264 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11265 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11266 (N1C->isNullValue() || // (a < 0) ? b : 0
11267 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11268 EVT XType = N0.getValueType();
11269 EVT AType = N2.getValueType();
11270 if (XType.bitsGE(AType)) {
11271 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11272 // single-bit constant.
11273 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11274 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11275 ShCtV = XType.getSizeInBits()-ShCtV-1;
11276 SDValue ShCt = DAG.getConstant(ShCtV,
11277 getShiftAmountTy(N0.getValueType()));
11278 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11280 AddToWorkList(Shift.getNode());
11282 if (XType.bitsGT(AType)) {
11283 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11284 AddToWorkList(Shift.getNode());
11287 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11290 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11292 DAG.getConstant(XType.getSizeInBits()-1,
11293 getShiftAmountTy(N0.getValueType())));
11294 AddToWorkList(Shift.getNode());
11296 if (XType.bitsGT(AType)) {
11297 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11298 AddToWorkList(Shift.getNode());
11301 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11305 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11306 // where y is has a single bit set.
11307 // A plaintext description would be, we can turn the SELECT_CC into an AND
11308 // when the condition can be materialized as an all-ones register. Any
11309 // single bit-test can be materialized as an all-ones register with
11310 // shift-left and shift-right-arith.
11311 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11312 N0->getValueType(0) == VT &&
11313 N1C && N1C->isNullValue() &&
11314 N2C && N2C->isNullValue()) {
11315 SDValue AndLHS = N0->getOperand(0);
11316 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11317 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11318 // Shift the tested bit over the sign bit.
11319 APInt AndMask = ConstAndRHS->getAPIntValue();
11321 DAG.getConstant(AndMask.countLeadingZeros(),
11322 getShiftAmountTy(AndLHS.getValueType()));
11323 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11325 // Now arithmetic right shift it all the way over, so the result is either
11326 // all-ones, or zero.
11328 DAG.getConstant(AndMask.getBitWidth()-1,
11329 getShiftAmountTy(Shl.getValueType()));
11330 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11332 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11336 // fold select C, 16, 0 -> shl C, 4
11337 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11338 TLI.getBooleanContents(N0.getValueType()) ==
11339 TargetLowering::ZeroOrOneBooleanContent) {
11341 // If the caller doesn't want us to simplify this into a zext of a compare,
11343 if (NotExtCompare && N2C->getAPIntValue() == 1)
11346 // Get a SetCC of the condition
11347 // NOTE: Don't create a SETCC if it's not legal on this target.
11348 if (!LegalOperations ||
11349 TLI.isOperationLegal(ISD::SETCC,
11350 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11352 // cast from setcc result type to select result type
11354 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11356 if (N2.getValueType().bitsLT(SCC.getValueType()))
11357 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11358 N2.getValueType());
11360 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11361 N2.getValueType(), SCC);
11363 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11364 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11365 N2.getValueType(), SCC);
11368 AddToWorkList(SCC.getNode());
11369 AddToWorkList(Temp.getNode());
11371 if (N2C->getAPIntValue() == 1)
11374 // shl setcc result by log2 n2c
11375 return DAG.getNode(
11376 ISD::SHL, DL, N2.getValueType(), Temp,
11377 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11378 getShiftAmountTy(Temp.getValueType())));
11382 // Check to see if this is the equivalent of setcc
11383 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11384 // otherwise, go ahead with the folds.
11385 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11386 EVT XType = N0.getValueType();
11387 if (!LegalOperations ||
11388 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11389 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11390 if (Res.getValueType() != VT)
11391 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11395 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11396 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11397 (!LegalOperations ||
11398 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11399 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11400 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11401 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11402 getShiftAmountTy(Ctlz.getValueType())));
11404 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11405 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11406 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11407 XType, DAG.getConstant(0, XType), N0);
11408 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11409 return DAG.getNode(ISD::SRL, DL, XType,
11410 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11411 DAG.getConstant(XType.getSizeInBits()-1,
11412 getShiftAmountTy(XType)));
11414 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11415 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11416 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11417 DAG.getConstant(XType.getSizeInBits()-1,
11418 getShiftAmountTy(N0.getValueType())));
11419 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11423 // Check to see if this is an integer abs.
11424 // select_cc setg[te] X, 0, X, -X ->
11425 // select_cc setgt X, -1, X, -X ->
11426 // select_cc setl[te] X, 0, -X, X ->
11427 // select_cc setlt X, 1, -X, X ->
11428 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11430 ConstantSDNode *SubC = nullptr;
11431 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11432 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11433 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11434 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11435 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11436 (N1C->isOne() && CC == ISD::SETLT)) &&
11437 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11438 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11440 EVT XType = N0.getValueType();
11441 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11442 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11444 DAG.getConstant(XType.getSizeInBits()-1,
11445 getShiftAmountTy(N0.getValueType())));
11446 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11448 AddToWorkList(Shift.getNode());
11449 AddToWorkList(Add.getNode());
11450 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11457 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11458 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11459 SDValue N1, ISD::CondCode Cond,
11460 SDLoc DL, bool foldBooleans) {
11461 TargetLowering::DAGCombinerInfo
11462 DagCombineInfo(DAG, Level, false, this);
11463 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11466 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11467 /// return a DAG expression to select that will generate the same value by
11468 /// multiplying by a magic number. See:
11469 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11470 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11471 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11475 // Avoid division by zero.
11476 if (!C->getAPIntValue())
11479 std::vector<SDNode*> Built;
11481 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11483 for (SDNode *N : Built)
11488 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11489 /// return a DAG expression to select that will generate the same value by
11490 /// multiplying by a magic number. See:
11491 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11492 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11493 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11497 // Avoid division by zero.
11498 if (!C->getAPIntValue())
11501 std::vector<SDNode*> Built;
11503 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11505 for (SDNode *N : Built)
11510 /// FindBaseOffset - Return true if base is a frame index, which is known not
11511 // to alias with anything but itself. Provides base object and offset as
11513 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11514 const GlobalValue *&GV, const void *&CV) {
11515 // Assume it is a primitive operation.
11516 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11518 // If it's an adding a simple constant then integrate the offset.
11519 if (Base.getOpcode() == ISD::ADD) {
11520 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11521 Base = Base.getOperand(0);
11522 Offset += C->getZExtValue();
11526 // Return the underlying GlobalValue, and update the Offset. Return false
11527 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11528 // by multiple nodes with different offsets.
11529 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11530 GV = G->getGlobal();
11531 Offset += G->getOffset();
11535 // Return the underlying Constant value, and update the Offset. Return false
11536 // for ConstantSDNodes since the same constant pool entry may be represented
11537 // by multiple nodes with different offsets.
11538 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11539 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11540 : (const void *)C->getConstVal();
11541 Offset += C->getOffset();
11544 // If it's any of the following then it can't alias with anything but itself.
11545 return isa<FrameIndexSDNode>(Base);
11548 /// isAlias - Return true if there is any possibility that the two addresses
11550 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11551 // If they are the same then they must be aliases.
11552 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11554 // If they are both volatile then they cannot be reordered.
11555 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11557 // Gather base node and offset information.
11558 SDValue Base1, Base2;
11559 int64_t Offset1, Offset2;
11560 const GlobalValue *GV1, *GV2;
11561 const void *CV1, *CV2;
11562 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11563 Base1, Offset1, GV1, CV1);
11564 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11565 Base2, Offset2, GV2, CV2);
11567 // If they have a same base address then check to see if they overlap.
11568 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11569 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11570 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11572 // It is possible for different frame indices to alias each other, mostly
11573 // when tail call optimization reuses return address slots for arguments.
11574 // To catch this case, look up the actual index of frame indices to compute
11575 // the real alias relationship.
11576 if (isFrameIndex1 && isFrameIndex2) {
11577 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11578 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11579 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11580 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11581 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11584 // Otherwise, if we know what the bases are, and they aren't identical, then
11585 // we know they cannot alias.
11586 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11589 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11590 // compared to the size and offset of the access, we may be able to prove they
11591 // do not alias. This check is conservative for now to catch cases created by
11592 // splitting vector types.
11593 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11594 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11595 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11596 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11597 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11598 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11599 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11601 // There is no overlap between these relatively aligned accesses of similar
11602 // size, return no alias.
11603 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11604 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11608 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11609 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11611 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11612 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11616 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11617 // Use alias analysis information.
11618 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11619 Op1->getSrcValueOffset());
11620 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11621 Op0->getSrcValueOffset() - MinOffset;
11622 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11623 Op1->getSrcValueOffset() - MinOffset;
11624 AliasAnalysis::AliasResult AAResult =
11625 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11627 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11628 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11630 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11631 if (AAResult == AliasAnalysis::NoAlias)
11635 // Otherwise we have to assume they alias.
11639 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11640 /// looking for aliasing nodes and adding them to the Aliases vector.
11641 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11642 SmallVectorImpl<SDValue> &Aliases) {
11643 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11644 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11646 // Get alias information for node.
11647 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11650 Chains.push_back(OriginalChain);
11651 unsigned Depth = 0;
11653 // Look at each chain and determine if it is an alias. If so, add it to the
11654 // aliases list. If not, then continue up the chain looking for the next
11656 while (!Chains.empty()) {
11657 SDValue Chain = Chains.back();
11660 // For TokenFactor nodes, look at each operand and only continue up the
11661 // chain until we find two aliases. If we've seen two aliases, assume we'll
11662 // find more and revert to original chain since the xform is unlikely to be
11665 // FIXME: The depth check could be made to return the last non-aliasing
11666 // chain we found before we hit a tokenfactor rather than the original
11668 if (Depth > 6 || Aliases.size() == 2) {
11670 Aliases.push_back(OriginalChain);
11674 // Don't bother if we've been before.
11675 if (!Visited.insert(Chain.getNode()))
11678 switch (Chain.getOpcode()) {
11679 case ISD::EntryToken:
11680 // Entry token is ideal chain operand, but handled in FindBetterChain.
11685 // Get alias information for Chain.
11686 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11687 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11689 // If chain is alias then stop here.
11690 if (!(IsLoad && IsOpLoad) &&
11691 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11692 Aliases.push_back(Chain);
11694 // Look further up the chain.
11695 Chains.push_back(Chain.getOperand(0));
11701 case ISD::TokenFactor:
11702 // We have to check each of the operands of the token factor for "small"
11703 // token factors, so we queue them up. Adding the operands to the queue
11704 // (stack) in reverse order maintains the original order and increases the
11705 // likelihood that getNode will find a matching token factor (CSE.)
11706 if (Chain.getNumOperands() > 16) {
11707 Aliases.push_back(Chain);
11710 for (unsigned n = Chain.getNumOperands(); n;)
11711 Chains.push_back(Chain.getOperand(--n));
11716 // For all other instructions we will just have to take what we can get.
11717 Aliases.push_back(Chain);
11722 // We need to be careful here to also search for aliases through the
11723 // value operand of a store, etc. Consider the following situation:
11725 // L1 = load Token1, %52
11726 // S1 = store Token1, L1, %51
11727 // L2 = load Token1, %52+8
11728 // S2 = store Token1, L2, %51+8
11729 // Token2 = Token(S1, S2)
11730 // L3 = load Token2, %53
11731 // S3 = store Token2, L3, %52
11732 // L4 = load Token2, %53+8
11733 // S4 = store Token2, L4, %52+8
11734 // If we search for aliases of S3 (which loads address %52), and we look
11735 // only through the chain, then we'll miss the trivial dependence on L1
11736 // (which also loads from %52). We then might change all loads and
11737 // stores to use Token1 as their chain operand, which could result in
11738 // copying %53 into %52 before copying %52 into %51 (which should
11741 // The problem is, however, that searching for such data dependencies
11742 // can become expensive, and the cost is not directly related to the
11743 // chain depth. Instead, we'll rule out such configurations here by
11744 // insisting that we've visited all chain users (except for users
11745 // of the original chain, which is not necessary). When doing this,
11746 // we need to look through nodes we don't care about (otherwise, things
11747 // like register copies will interfere with trivial cases).
11749 SmallVector<const SDNode *, 16> Worklist;
11750 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11751 IE = Visited.end(); I != IE; ++I)
11752 if (*I != OriginalChain.getNode())
11753 Worklist.push_back(*I);
11755 while (!Worklist.empty()) {
11756 const SDNode *M = Worklist.pop_back_val();
11758 // We have already visited M, and want to make sure we've visited any uses
11759 // of M that we care about. For uses that we've not visisted, and don't
11760 // care about, queue them to the worklist.
11762 for (SDNode::use_iterator UI = M->use_begin(),
11763 UIE = M->use_end(); UI != UIE; ++UI)
11764 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11765 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11766 // We've not visited this use, and we care about it (it could have an
11767 // ordering dependency with the original node).
11769 Aliases.push_back(OriginalChain);
11773 // We've not visited this use, but we don't care about it. Mark it as
11774 // visited and enqueue it to the worklist.
11775 Worklist.push_back(*UI);
11780 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11781 /// for a better chain (aliasing node.)
11782 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11783 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11785 // Accumulate all the aliases to this node.
11786 GatherAllAliases(N, OldChain, Aliases);
11788 // If no operands then chain to entry token.
11789 if (Aliases.size() == 0)
11790 return DAG.getEntryNode();
11792 // If a single operand then chain to it. We don't need to revisit it.
11793 if (Aliases.size() == 1)
11796 // Construct a custom tailored token factor.
11797 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11800 // SelectionDAG::Combine - This is the entry point for the file.
11802 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11803 CodeGenOpt::Level OptLevel) {
11804 /// run - This is the main entry point to this class.
11806 DAGCombiner(*this, AA, OptLevel).Run(Level);