1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 STATISTIC(NodesCombined , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
52 CombinerAA("combiner-alias-analysis", cl::Hidden,
53 cl::desc("Turn on alias analysis during testing"));
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57 cl::desc("Include global information in alias analysis"));
59 /// Hidden option to stress test load slicing, i.e., when this option
60 /// is enabled, load slicing bypasses most of its profitability guards.
62 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
63 cl::desc("Bypass the profitability model of load "
67 //------------------------------ DAGCombiner ---------------------------------//
71 const TargetLowering &TLI;
73 CodeGenOpt::Level OptLevel;
78 // Worklist of all of the nodes that need to be simplified.
80 // This has the semantics that when adding to the worklist,
81 // the item added must be next to be processed. It should
82 // also only appear once. The naive approach to this takes
85 // To reduce the insert/remove time to logarithmic, we use
86 // a set and a vector to maintain our worklist.
88 // The set contains the items on the worklist, but does not
89 // maintain the order they should be visited.
91 // The vector maintains the order nodes should be visited, but may
92 // contain duplicate or removed nodes. When choosing a node to
93 // visit, we pop off the order stack until we find an item that is
94 // also in the contents set. All operations are O(log N).
95 SmallPtrSet<SDNode*, 64> WorkListContents;
96 SmallVector<SDNode*, 64> WorkListOrder;
98 // AA - Used for DAG load/store alias analysis.
101 /// AddUsersToWorkList - When an instruction is simplified, add all users of
102 /// the instruction to the work lists because they might get more simplified
105 void AddUsersToWorkList(SDNode *N) {
106 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
111 /// visit - call the node-specific routine that knows how to fold each
112 /// particular type of node.
113 SDValue visit(SDNode *N);
116 /// AddToWorkList - Add to the work list making sure its instance is at the
117 /// back (next to be processed.)
118 void AddToWorkList(SDNode *N) {
119 WorkListContents.insert(N);
120 WorkListOrder.push_back(N);
123 /// removeFromWorkList - remove all instances of N from the worklist.
125 void removeFromWorkList(SDNode *N) {
126 WorkListContents.erase(N);
129 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
132 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
133 return CombineTo(N, &Res, 1, AddTo);
136 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
138 SDValue To[] = { Res0, Res1 };
139 return CombineTo(N, To, 2, AddTo);
142 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
146 /// SimplifyDemandedBits - Check the specified integer node value to see if
147 /// it can be simplified or if things it uses can be simplified by bit
148 /// propagation. If so, return true.
149 bool SimplifyDemandedBits(SDValue Op) {
150 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
151 APInt Demanded = APInt::getAllOnesValue(BitWidth);
152 return SimplifyDemandedBits(Op, Demanded);
155 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
157 bool CombineToPreIndexedLoadStore(SDNode *N);
158 bool CombineToPostIndexedLoadStore(SDNode *N);
159 bool SliceUpLoad(SDNode *N);
161 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
162 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
163 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
164 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
165 SDValue PromoteIntBinOp(SDValue Op);
166 SDValue PromoteIntShiftOp(SDValue Op);
167 SDValue PromoteExtend(SDValue Op);
168 bool PromoteLoad(SDValue Op);
170 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
171 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
172 ISD::NodeType ExtType);
174 /// combine - call the node-specific routine that knows how to fold each
175 /// particular type of node. If that doesn't do anything, try the
176 /// target-specific DAG combines.
177 SDValue combine(SDNode *N);
179 // Visitation implementation - Implement dag node combining for different
180 // node types. The semantics are as follows:
182 // SDValue.getNode() == 0 - No change was made
183 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
184 // otherwise - N should be replaced by the returned Operand.
186 SDValue visitTokenFactor(SDNode *N);
187 SDValue visitMERGE_VALUES(SDNode *N);
188 SDValue visitADD(SDNode *N);
189 SDValue visitSUB(SDNode *N);
190 SDValue visitADDC(SDNode *N);
191 SDValue visitSUBC(SDNode *N);
192 SDValue visitADDE(SDNode *N);
193 SDValue visitSUBE(SDNode *N);
194 SDValue visitMUL(SDNode *N);
195 SDValue visitSDIV(SDNode *N);
196 SDValue visitUDIV(SDNode *N);
197 SDValue visitSREM(SDNode *N);
198 SDValue visitUREM(SDNode *N);
199 SDValue visitMULHU(SDNode *N);
200 SDValue visitMULHS(SDNode *N);
201 SDValue visitSMUL_LOHI(SDNode *N);
202 SDValue visitUMUL_LOHI(SDNode *N);
203 SDValue visitSMULO(SDNode *N);
204 SDValue visitUMULO(SDNode *N);
205 SDValue visitSDIVREM(SDNode *N);
206 SDValue visitUDIVREM(SDNode *N);
207 SDValue visitAND(SDNode *N);
208 SDValue visitOR(SDNode *N);
209 SDValue visitXOR(SDNode *N);
210 SDValue SimplifyVBinOp(SDNode *N);
211 SDValue SimplifyVUnaryOp(SDNode *N);
212 SDValue visitSHL(SDNode *N);
213 SDValue visitSRA(SDNode *N);
214 SDValue visitSRL(SDNode *N);
215 SDValue visitCTLZ(SDNode *N);
216 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
217 SDValue visitCTTZ(SDNode *N);
218 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
219 SDValue visitCTPOP(SDNode *N);
220 SDValue visitSELECT(SDNode *N);
221 SDValue visitVSELECT(SDNode *N);
222 SDValue visitSELECT_CC(SDNode *N);
223 SDValue visitSETCC(SDNode *N);
224 SDValue visitSIGN_EXTEND(SDNode *N);
225 SDValue visitZERO_EXTEND(SDNode *N);
226 SDValue visitANY_EXTEND(SDNode *N);
227 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
228 SDValue visitTRUNCATE(SDNode *N);
229 SDValue visitBITCAST(SDNode *N);
230 SDValue visitBUILD_PAIR(SDNode *N);
231 SDValue visitFADD(SDNode *N);
232 SDValue visitFSUB(SDNode *N);
233 SDValue visitFMUL(SDNode *N);
234 SDValue visitFMA(SDNode *N);
235 SDValue visitFDIV(SDNode *N);
236 SDValue visitFREM(SDNode *N);
237 SDValue visitFCOPYSIGN(SDNode *N);
238 SDValue visitSINT_TO_FP(SDNode *N);
239 SDValue visitUINT_TO_FP(SDNode *N);
240 SDValue visitFP_TO_SINT(SDNode *N);
241 SDValue visitFP_TO_UINT(SDNode *N);
242 SDValue visitFP_ROUND(SDNode *N);
243 SDValue visitFP_ROUND_INREG(SDNode *N);
244 SDValue visitFP_EXTEND(SDNode *N);
245 SDValue visitFNEG(SDNode *N);
246 SDValue visitFABS(SDNode *N);
247 SDValue visitFCEIL(SDNode *N);
248 SDValue visitFTRUNC(SDNode *N);
249 SDValue visitFFLOOR(SDNode *N);
250 SDValue visitBRCOND(SDNode *N);
251 SDValue visitBR_CC(SDNode *N);
252 SDValue visitLOAD(SDNode *N);
253 SDValue visitSTORE(SDNode *N);
254 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
255 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
256 SDValue visitBUILD_VECTOR(SDNode *N);
257 SDValue visitCONCAT_VECTORS(SDNode *N);
258 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
259 SDValue visitVECTOR_SHUFFLE(SDNode *N);
261 SDValue XformToShuffleWithZero(SDNode *N);
262 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
264 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
266 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
267 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
268 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
269 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
270 SDValue N3, ISD::CondCode CC,
271 bool NotExtCompare = false);
272 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
273 SDLoc DL, bool foldBooleans = true);
274 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
276 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
277 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
278 SDValue BuildSDIV(SDNode *N);
279 SDValue BuildUDIV(SDNode *N);
280 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
281 bool DemandHighBits = true);
282 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
283 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
284 SDValue ReduceLoadWidth(SDNode *N);
285 SDValue ReduceLoadOpStoreWidth(SDNode *N);
286 SDValue TransformFPLoadStorePair(SDNode *N);
287 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
288 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
290 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
292 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
293 /// looking for aliasing nodes and adding them to the Aliases vector.
294 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
295 SmallVectorImpl<SDValue> &Aliases);
297 /// isAlias - Return true if there is any possibility that the two addresses
299 bool isAlias(SDValue Ptr1, int64_t Size1,
300 const Value *SrcValue1, int SrcValueOffset1,
301 unsigned SrcValueAlign1,
302 const MDNode *TBAAInfo1,
303 SDValue Ptr2, int64_t Size2,
304 const Value *SrcValue2, int SrcValueOffset2,
305 unsigned SrcValueAlign2,
306 const MDNode *TBAAInfo2) const;
308 /// isAlias - Return true if there is any possibility that the two addresses
310 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
312 /// FindAliasInfo - Extracts the relevant alias information from the memory
313 /// node. Returns true if the operand was a load.
314 bool FindAliasInfo(SDNode *N,
315 SDValue &Ptr, int64_t &Size,
316 const Value *&SrcValue, int &SrcValueOffset,
317 unsigned &SrcValueAlignment,
318 const MDNode *&TBAAInfo) const;
320 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
321 /// looking for a better chain (aliasing node.)
322 SDValue FindBetterChain(SDNode *N, SDValue Chain);
324 /// Merge consecutive store operations into a wide store.
325 /// This optimization uses wide integers or vectors when possible.
326 /// \return True if some memory operations were changed.
327 bool MergeConsecutiveStores(StoreSDNode *N);
330 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
331 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
332 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
333 AttributeSet FnAttrs =
334 DAG.getMachineFunction().getFunction()->getAttributes();
336 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
337 Attribute::OptimizeForSize) ||
338 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
341 /// Run - runs the dag combiner on all nodes in the work list
342 void Run(CombineLevel AtLevel);
344 SelectionDAG &getDAG() const { return DAG; }
346 /// getShiftAmountTy - Returns a type large enough to hold any valid
347 /// shift amount - before type legalization these can be huge.
348 EVT getShiftAmountTy(EVT LHSTy) {
349 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
350 if (LHSTy.isVector())
352 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
353 : TLI.getPointerTy();
356 /// isTypeLegal - This method returns true if we are running before type
357 /// legalization or if the specified VT is legal.
358 bool isTypeLegal(const EVT &VT) {
359 if (!LegalTypes) return true;
360 return TLI.isTypeLegal(VT);
363 /// getSetCCResultType - Convenience wrapper around
364 /// TargetLowering::getSetCCResultType
365 EVT getSetCCResultType(EVT VT) const {
366 return TLI.getSetCCResultType(*DAG.getContext(), VT);
373 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
374 /// nodes from the worklist.
375 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
378 explicit WorkListRemover(DAGCombiner &dc)
379 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
381 virtual void NodeDeleted(SDNode *N, SDNode *E) {
382 DC.removeFromWorkList(N);
387 //===----------------------------------------------------------------------===//
388 // TargetLowering::DAGCombinerInfo implementation
389 //===----------------------------------------------------------------------===//
391 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
392 ((DAGCombiner*)DC)->AddToWorkList(N);
395 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
396 ((DAGCombiner*)DC)->removeFromWorkList(N);
399 SDValue TargetLowering::DAGCombinerInfo::
400 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
401 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
404 SDValue TargetLowering::DAGCombinerInfo::
405 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
406 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
410 SDValue TargetLowering::DAGCombinerInfo::
411 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
412 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
415 void TargetLowering::DAGCombinerInfo::
416 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
417 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
420 //===----------------------------------------------------------------------===//
422 //===----------------------------------------------------------------------===//
424 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
425 /// specified expression for the same cost as the expression itself, or 2 if we
426 /// can compute the negated form more cheaply than the expression itself.
427 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
428 const TargetLowering &TLI,
429 const TargetOptions *Options,
430 unsigned Depth = 0) {
431 // fneg is removable even if it has multiple uses.
432 if (Op.getOpcode() == ISD::FNEG) return 2;
434 // Don't allow anything with multiple uses.
435 if (!Op.hasOneUse()) return 0;
437 // Don't recurse exponentially.
438 if (Depth > 6) return 0;
440 switch (Op.getOpcode()) {
441 default: return false;
442 case ISD::ConstantFP:
443 // Don't invert constant FP values after legalize. The negated constant
444 // isn't necessarily legal.
445 return LegalOperations ? 0 : 1;
447 // FIXME: determine better conditions for this xform.
448 if (!Options->UnsafeFPMath) return 0;
450 // After operation legalization, it might not be legal to create new FSUBs.
451 if (LegalOperations &&
452 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
455 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
456 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
459 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
460 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
463 // We can't turn -(A-B) into B-A when we honor signed zeros.
464 if (!Options->UnsafeFPMath) return 0;
466 // fold (fneg (fsub A, B)) -> (fsub B, A)
471 if (Options->HonorSignDependentRoundingFPMath()) return 0;
473 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
474 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
478 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
484 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
489 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
490 /// returns the newly negated expression.
491 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
492 bool LegalOperations, unsigned Depth = 0) {
493 // fneg is removable even if it has multiple uses.
494 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
496 // Don't allow anything with multiple uses.
497 assert(Op.hasOneUse() && "Unknown reuse!");
499 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
500 switch (Op.getOpcode()) {
501 default: llvm_unreachable("Unknown code");
502 case ISD::ConstantFP: {
503 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
505 return DAG.getConstantFP(V, Op.getValueType());
508 // FIXME: determine better conditions for this xform.
509 assert(DAG.getTarget().Options.UnsafeFPMath);
511 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
512 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
513 DAG.getTargetLoweringInfo(),
514 &DAG.getTarget().Options, Depth+1))
515 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
516 GetNegatedExpression(Op.getOperand(0), DAG,
517 LegalOperations, Depth+1),
519 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
520 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
521 GetNegatedExpression(Op.getOperand(1), DAG,
522 LegalOperations, Depth+1),
525 // We can't turn -(A-B) into B-A when we honor signed zeros.
526 assert(DAG.getTarget().Options.UnsafeFPMath);
528 // fold (fneg (fsub 0, B)) -> B
529 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
530 if (N0CFP->getValueAPF().isZero())
531 return Op.getOperand(1);
533 // fold (fneg (fsub A, B)) -> (fsub B, A)
534 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
535 Op.getOperand(1), Op.getOperand(0));
539 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
541 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
542 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
543 DAG.getTargetLoweringInfo(),
544 &DAG.getTarget().Options, Depth+1))
545 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
546 GetNegatedExpression(Op.getOperand(0), DAG,
547 LegalOperations, Depth+1),
550 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
551 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
553 GetNegatedExpression(Op.getOperand(1), DAG,
554 LegalOperations, Depth+1));
558 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
559 GetNegatedExpression(Op.getOperand(0), DAG,
560 LegalOperations, Depth+1));
562 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
563 GetNegatedExpression(Op.getOperand(0), DAG,
564 LegalOperations, Depth+1),
570 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
571 // that selects between the values 1 and 0, making it equivalent to a setcc.
572 // Also, set the incoming LHS, RHS, and CC references to the appropriate
573 // nodes based on the type of node we are checking. This simplifies life a
574 // bit for the callers.
575 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
577 if (N.getOpcode() == ISD::SETCC) {
578 LHS = N.getOperand(0);
579 RHS = N.getOperand(1);
580 CC = N.getOperand(2);
583 if (N.getOpcode() == ISD::SELECT_CC &&
584 N.getOperand(2).getOpcode() == ISD::Constant &&
585 N.getOperand(3).getOpcode() == ISD::Constant &&
586 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
587 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
588 LHS = N.getOperand(0);
589 RHS = N.getOperand(1);
590 CC = N.getOperand(4);
596 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
597 // one use. If this is true, it allows the users to invert the operation for
598 // free when it is profitable to do so.
599 static bool isOneUseSetCC(SDValue N) {
601 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
606 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
607 SDValue N0, SDValue N1) {
608 EVT VT = N0.getValueType();
609 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
610 if (isa<ConstantSDNode>(N1)) {
611 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
613 DAG.FoldConstantArithmetic(Opc, VT,
614 cast<ConstantSDNode>(N0.getOperand(1)),
615 cast<ConstantSDNode>(N1));
616 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
618 if (N0.hasOneUse()) {
619 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
620 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
621 N0.getOperand(0), N1);
622 AddToWorkList(OpNode.getNode());
623 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
627 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
628 if (isa<ConstantSDNode>(N0)) {
629 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
631 DAG.FoldConstantArithmetic(Opc, VT,
632 cast<ConstantSDNode>(N1.getOperand(1)),
633 cast<ConstantSDNode>(N0));
634 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
636 if (N1.hasOneUse()) {
637 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
638 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
639 N1.getOperand(0), N0);
640 AddToWorkList(OpNode.getNode());
641 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
648 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
650 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
652 DEBUG(dbgs() << "\nReplacing.1 ";
654 dbgs() << "\nWith: ";
655 To[0].getNode()->dump(&DAG);
656 dbgs() << " and " << NumTo-1 << " other values\n";
657 for (unsigned i = 0, e = NumTo; i != e; ++i)
658 assert((!To[i].getNode() ||
659 N->getValueType(i) == To[i].getValueType()) &&
660 "Cannot combine value to value of different type!"));
661 WorkListRemover DeadNodes(*this);
662 DAG.ReplaceAllUsesWith(N, To);
664 // Push the new nodes and any users onto the worklist
665 for (unsigned i = 0, e = NumTo; i != e; ++i) {
666 if (To[i].getNode()) {
667 AddToWorkList(To[i].getNode());
668 AddUsersToWorkList(To[i].getNode());
673 // Finally, if the node is now dead, remove it from the graph. The node
674 // may not be dead if the replacement process recursively simplified to
675 // something else needing this node.
676 if (N->use_empty()) {
677 // Nodes can be reintroduced into the worklist. Make sure we do not
678 // process a node that has been replaced.
679 removeFromWorkList(N);
681 // Finally, since the node is now dead, remove it from the graph.
684 return SDValue(N, 0);
688 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
689 // Replace all uses. If any nodes become isomorphic to other nodes and
690 // are deleted, make sure to remove them from our worklist.
691 WorkListRemover DeadNodes(*this);
692 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
694 // Push the new node and any (possibly new) users onto the worklist.
695 AddToWorkList(TLO.New.getNode());
696 AddUsersToWorkList(TLO.New.getNode());
698 // Finally, if the node is now dead, remove it from the graph. The node
699 // may not be dead if the replacement process recursively simplified to
700 // something else needing this node.
701 if (TLO.Old.getNode()->use_empty()) {
702 removeFromWorkList(TLO.Old.getNode());
704 // If the operands of this node are only used by the node, they will now
705 // be dead. Make sure to visit them first to delete dead nodes early.
706 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
707 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
708 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
710 DAG.DeleteNode(TLO.Old.getNode());
714 /// SimplifyDemandedBits - Check the specified integer node value to see if
715 /// it can be simplified or if things it uses can be simplified by bit
716 /// propagation. If so, return true.
717 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
718 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
719 APInt KnownZero, KnownOne;
720 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
724 AddToWorkList(Op.getNode());
726 // Replace the old value with the new one.
728 DEBUG(dbgs() << "\nReplacing.2 ";
729 TLO.Old.getNode()->dump(&DAG);
730 dbgs() << "\nWith: ";
731 TLO.New.getNode()->dump(&DAG);
734 CommitTargetLoweringOpt(TLO);
738 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
740 EVT VT = Load->getValueType(0);
741 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
743 DEBUG(dbgs() << "\nReplacing.9 ";
745 dbgs() << "\nWith: ";
746 Trunc.getNode()->dump(&DAG);
748 WorkListRemover DeadNodes(*this);
749 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
750 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
751 removeFromWorkList(Load);
752 DAG.DeleteNode(Load);
753 AddToWorkList(Trunc.getNode());
756 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
760 EVT MemVT = LD->getMemoryVT();
761 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
762 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
764 : LD->getExtensionType();
766 return DAG.getExtLoad(ExtType, dl, PVT,
767 LD->getChain(), LD->getBasePtr(),
768 LD->getPointerInfo(),
769 MemVT, LD->isVolatile(),
770 LD->isNonTemporal(), LD->getAlignment());
773 unsigned Opc = Op.getOpcode();
776 case ISD::AssertSext:
777 return DAG.getNode(ISD::AssertSext, dl, PVT,
778 SExtPromoteOperand(Op.getOperand(0), PVT),
780 case ISD::AssertZext:
781 return DAG.getNode(ISD::AssertZext, dl, PVT,
782 ZExtPromoteOperand(Op.getOperand(0), PVT),
784 case ISD::Constant: {
786 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
787 return DAG.getNode(ExtOpc, dl, PVT, Op);
791 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
793 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
796 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
797 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
799 EVT OldVT = Op.getValueType();
801 bool Replace = false;
802 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
803 if (NewOp.getNode() == 0)
805 AddToWorkList(NewOp.getNode());
808 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
809 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
810 DAG.getValueType(OldVT));
813 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
814 EVT OldVT = Op.getValueType();
816 bool Replace = false;
817 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
818 if (NewOp.getNode() == 0)
820 AddToWorkList(NewOp.getNode());
823 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
824 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
827 /// PromoteIntBinOp - Promote the specified integer binary operation if the
828 /// target indicates it is beneficial. e.g. On x86, it's usually better to
829 /// promote i16 operations to i32 since i16 instructions are longer.
830 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
831 if (!LegalOperations)
834 EVT VT = Op.getValueType();
835 if (VT.isVector() || !VT.isInteger())
838 // If operation type is 'undesirable', e.g. i16 on x86, consider
840 unsigned Opc = Op.getOpcode();
841 if (TLI.isTypeDesirableForOp(Opc, VT))
845 // Consult target whether it is a good idea to promote this operation and
846 // what's the right type to promote it to.
847 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
848 assert(PVT != VT && "Don't know what type to promote to!");
850 bool Replace0 = false;
851 SDValue N0 = Op.getOperand(0);
852 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
853 if (NN0.getNode() == 0)
856 bool Replace1 = false;
857 SDValue N1 = Op.getOperand(1);
862 NN1 = PromoteOperand(N1, PVT, Replace1);
863 if (NN1.getNode() == 0)
867 AddToWorkList(NN0.getNode());
869 AddToWorkList(NN1.getNode());
872 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
874 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
876 DEBUG(dbgs() << "\nPromoting ";
877 Op.getNode()->dump(&DAG));
879 return DAG.getNode(ISD::TRUNCATE, dl, VT,
880 DAG.getNode(Opc, dl, PVT, NN0, NN1));
885 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
886 /// target indicates it is beneficial. e.g. On x86, it's usually better to
887 /// promote i16 operations to i32 since i16 instructions are longer.
888 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
889 if (!LegalOperations)
892 EVT VT = Op.getValueType();
893 if (VT.isVector() || !VT.isInteger())
896 // If operation type is 'undesirable', e.g. i16 on x86, consider
898 unsigned Opc = Op.getOpcode();
899 if (TLI.isTypeDesirableForOp(Opc, VT))
903 // Consult target whether it is a good idea to promote this operation and
904 // what's the right type to promote it to.
905 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
906 assert(PVT != VT && "Don't know what type to promote to!");
908 bool Replace = false;
909 SDValue N0 = Op.getOperand(0);
911 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
912 else if (Opc == ISD::SRL)
913 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
915 N0 = PromoteOperand(N0, PVT, Replace);
916 if (N0.getNode() == 0)
919 AddToWorkList(N0.getNode());
921 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
923 DEBUG(dbgs() << "\nPromoting ";
924 Op.getNode()->dump(&DAG));
926 return DAG.getNode(ISD::TRUNCATE, dl, VT,
927 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
932 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
933 if (!LegalOperations)
936 EVT VT = Op.getValueType();
937 if (VT.isVector() || !VT.isInteger())
940 // If operation type is 'undesirable', e.g. i16 on x86, consider
942 unsigned Opc = Op.getOpcode();
943 if (TLI.isTypeDesirableForOp(Opc, VT))
947 // Consult target whether it is a good idea to promote this operation and
948 // what's the right type to promote it to.
949 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
950 assert(PVT != VT && "Don't know what type to promote to!");
951 // fold (aext (aext x)) -> (aext x)
952 // fold (aext (zext x)) -> (zext x)
953 // fold (aext (sext x)) -> (sext x)
954 DEBUG(dbgs() << "\nPromoting ";
955 Op.getNode()->dump(&DAG));
956 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
961 bool DAGCombiner::PromoteLoad(SDValue Op) {
962 if (!LegalOperations)
965 EVT VT = Op.getValueType();
966 if (VT.isVector() || !VT.isInteger())
969 // If operation type is 'undesirable', e.g. i16 on x86, consider
971 unsigned Opc = Op.getOpcode();
972 if (TLI.isTypeDesirableForOp(Opc, VT))
976 // Consult target whether it is a good idea to promote this operation and
977 // what's the right type to promote it to.
978 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
979 assert(PVT != VT && "Don't know what type to promote to!");
982 SDNode *N = Op.getNode();
983 LoadSDNode *LD = cast<LoadSDNode>(N);
984 EVT MemVT = LD->getMemoryVT();
985 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
986 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
988 : LD->getExtensionType();
989 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
990 LD->getChain(), LD->getBasePtr(),
991 LD->getPointerInfo(),
992 MemVT, LD->isVolatile(),
993 LD->isNonTemporal(), LD->getAlignment());
994 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
996 DEBUG(dbgs() << "\nPromoting ";
999 Result.getNode()->dump(&DAG);
1001 WorkListRemover DeadNodes(*this);
1002 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1003 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1004 removeFromWorkList(N);
1006 AddToWorkList(Result.getNode());
1013 //===----------------------------------------------------------------------===//
1014 // Main DAG Combiner implementation
1015 //===----------------------------------------------------------------------===//
1017 void DAGCombiner::Run(CombineLevel AtLevel) {
1018 // set the instance variables, so that the various visit routines may use it.
1020 LegalOperations = Level >= AfterLegalizeVectorOps;
1021 LegalTypes = Level >= AfterLegalizeTypes;
1023 // Add all the dag nodes to the worklist.
1024 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1025 E = DAG.allnodes_end(); I != E; ++I)
1028 // Create a dummy node (which is not added to allnodes), that adds a reference
1029 // to the root node, preventing it from being deleted, and tracking any
1030 // changes of the root.
1031 HandleSDNode Dummy(DAG.getRoot());
1033 // The root of the dag may dangle to deleted nodes until the dag combiner is
1034 // done. Set it to null to avoid confusion.
1035 DAG.setRoot(SDValue());
1037 // while the worklist isn't empty, find a node and
1038 // try and combine it.
1039 while (!WorkListContents.empty()) {
1041 // The WorkListOrder holds the SDNodes in order, but it may contain
1043 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1044 // worklist *should* contain, and check the node we want to visit is should
1045 // actually be visited.
1047 N = WorkListOrder.pop_back_val();
1048 } while (!WorkListContents.erase(N));
1050 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1051 // N is deleted from the DAG, since they too may now be dead or may have a
1052 // reduced number of uses, allowing other xforms.
1053 if (N->use_empty() && N != &Dummy) {
1054 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1055 AddToWorkList(N->getOperand(i).getNode());
1061 SDValue RV = combine(N);
1063 if (RV.getNode() == 0)
1068 // If we get back the same node we passed in, rather than a new node or
1069 // zero, we know that the node must have defined multiple values and
1070 // CombineTo was used. Since CombineTo takes care of the worklist
1071 // mechanics for us, we have no work to do in this case.
1072 if (RV.getNode() == N)
1075 assert(N->getOpcode() != ISD::DELETED_NODE &&
1076 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1077 "Node was deleted but visit returned new node!");
1079 DEBUG(dbgs() << "\nReplacing.3 ";
1081 dbgs() << "\nWith: ";
1082 RV.getNode()->dump(&DAG);
1085 // Transfer debug value.
1086 DAG.TransferDbgValues(SDValue(N, 0), RV);
1087 WorkListRemover DeadNodes(*this);
1088 if (N->getNumValues() == RV.getNode()->getNumValues())
1089 DAG.ReplaceAllUsesWith(N, RV.getNode());
1091 assert(N->getValueType(0) == RV.getValueType() &&
1092 N->getNumValues() == 1 && "Type mismatch");
1094 DAG.ReplaceAllUsesWith(N, &OpV);
1097 // Push the new node and any users onto the worklist
1098 AddToWorkList(RV.getNode());
1099 AddUsersToWorkList(RV.getNode());
1101 // Add any uses of the old node to the worklist in case this node is the
1102 // last one that uses them. They may become dead after this node is
1104 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1105 AddToWorkList(N->getOperand(i).getNode());
1107 // Finally, if the node is now dead, remove it from the graph. The node
1108 // may not be dead if the replacement process recursively simplified to
1109 // something else needing this node.
1110 if (N->use_empty()) {
1111 // Nodes can be reintroduced into the worklist. Make sure we do not
1112 // process a node that has been replaced.
1113 removeFromWorkList(N);
1115 // Finally, since the node is now dead, remove it from the graph.
1120 // If the root changed (e.g. it was a dead load, update the root).
1121 DAG.setRoot(Dummy.getValue());
1122 DAG.RemoveDeadNodes();
1125 SDValue DAGCombiner::visit(SDNode *N) {
1126 switch (N->getOpcode()) {
1128 case ISD::TokenFactor: return visitTokenFactor(N);
1129 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1130 case ISD::ADD: return visitADD(N);
1131 case ISD::SUB: return visitSUB(N);
1132 case ISD::ADDC: return visitADDC(N);
1133 case ISD::SUBC: return visitSUBC(N);
1134 case ISD::ADDE: return visitADDE(N);
1135 case ISD::SUBE: return visitSUBE(N);
1136 case ISD::MUL: return visitMUL(N);
1137 case ISD::SDIV: return visitSDIV(N);
1138 case ISD::UDIV: return visitUDIV(N);
1139 case ISD::SREM: return visitSREM(N);
1140 case ISD::UREM: return visitUREM(N);
1141 case ISD::MULHU: return visitMULHU(N);
1142 case ISD::MULHS: return visitMULHS(N);
1143 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1144 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1145 case ISD::SMULO: return visitSMULO(N);
1146 case ISD::UMULO: return visitUMULO(N);
1147 case ISD::SDIVREM: return visitSDIVREM(N);
1148 case ISD::UDIVREM: return visitUDIVREM(N);
1149 case ISD::AND: return visitAND(N);
1150 case ISD::OR: return visitOR(N);
1151 case ISD::XOR: return visitXOR(N);
1152 case ISD::SHL: return visitSHL(N);
1153 case ISD::SRA: return visitSRA(N);
1154 case ISD::SRL: return visitSRL(N);
1155 case ISD::CTLZ: return visitCTLZ(N);
1156 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1157 case ISD::CTTZ: return visitCTTZ(N);
1158 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1159 case ISD::CTPOP: return visitCTPOP(N);
1160 case ISD::SELECT: return visitSELECT(N);
1161 case ISD::VSELECT: return visitVSELECT(N);
1162 case ISD::SELECT_CC: return visitSELECT_CC(N);
1163 case ISD::SETCC: return visitSETCC(N);
1164 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1165 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1166 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1167 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1168 case ISD::TRUNCATE: return visitTRUNCATE(N);
1169 case ISD::BITCAST: return visitBITCAST(N);
1170 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1171 case ISD::FADD: return visitFADD(N);
1172 case ISD::FSUB: return visitFSUB(N);
1173 case ISD::FMUL: return visitFMUL(N);
1174 case ISD::FMA: return visitFMA(N);
1175 case ISD::FDIV: return visitFDIV(N);
1176 case ISD::FREM: return visitFREM(N);
1177 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1178 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1179 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1180 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1181 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1182 case ISD::FP_ROUND: return visitFP_ROUND(N);
1183 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1184 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1185 case ISD::FNEG: return visitFNEG(N);
1186 case ISD::FABS: return visitFABS(N);
1187 case ISD::FFLOOR: return visitFFLOOR(N);
1188 case ISD::FCEIL: return visitFCEIL(N);
1189 case ISD::FTRUNC: return visitFTRUNC(N);
1190 case ISD::BRCOND: return visitBRCOND(N);
1191 case ISD::BR_CC: return visitBR_CC(N);
1192 case ISD::LOAD: return visitLOAD(N);
1193 case ISD::STORE: return visitSTORE(N);
1194 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1195 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1196 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1197 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1198 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1199 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1204 SDValue DAGCombiner::combine(SDNode *N) {
1205 SDValue RV = visit(N);
1207 // If nothing happened, try a target-specific DAG combine.
1208 if (RV.getNode() == 0) {
1209 assert(N->getOpcode() != ISD::DELETED_NODE &&
1210 "Node was deleted but visit returned NULL!");
1212 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1213 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1215 // Expose the DAG combiner to the target combiner impls.
1216 TargetLowering::DAGCombinerInfo
1217 DagCombineInfo(DAG, Level, false, this);
1219 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1223 // If nothing happened still, try promoting the operation.
1224 if (RV.getNode() == 0) {
1225 switch (N->getOpcode()) {
1233 RV = PromoteIntBinOp(SDValue(N, 0));
1238 RV = PromoteIntShiftOp(SDValue(N, 0));
1240 case ISD::SIGN_EXTEND:
1241 case ISD::ZERO_EXTEND:
1242 case ISD::ANY_EXTEND:
1243 RV = PromoteExtend(SDValue(N, 0));
1246 if (PromoteLoad(SDValue(N, 0)))
1252 // If N is a commutative binary node, try commuting it to enable more
1254 if (RV.getNode() == 0 &&
1255 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1256 N->getNumValues() == 1) {
1257 SDValue N0 = N->getOperand(0);
1258 SDValue N1 = N->getOperand(1);
1260 // Constant operands are canonicalized to RHS.
1261 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1262 SDValue Ops[] = { N1, N0 };
1263 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1266 return SDValue(CSENode, 0);
1273 /// getInputChainForNode - Given a node, return its input chain if it has one,
1274 /// otherwise return a null sd operand.
1275 static SDValue getInputChainForNode(SDNode *N) {
1276 if (unsigned NumOps = N->getNumOperands()) {
1277 if (N->getOperand(0).getValueType() == MVT::Other)
1278 return N->getOperand(0);
1279 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1280 return N->getOperand(NumOps-1);
1281 for (unsigned i = 1; i < NumOps-1; ++i)
1282 if (N->getOperand(i).getValueType() == MVT::Other)
1283 return N->getOperand(i);
1288 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1289 // If N has two operands, where one has an input chain equal to the other,
1290 // the 'other' chain is redundant.
1291 if (N->getNumOperands() == 2) {
1292 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1293 return N->getOperand(0);
1294 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1295 return N->getOperand(1);
1298 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1299 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1300 SmallPtrSet<SDNode*, 16> SeenOps;
1301 bool Changed = false; // If we should replace this token factor.
1303 // Start out with this token factor.
1306 // Iterate through token factors. The TFs grows when new token factors are
1308 for (unsigned i = 0; i < TFs.size(); ++i) {
1309 SDNode *TF = TFs[i];
1311 // Check each of the operands.
1312 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1313 SDValue Op = TF->getOperand(i);
1315 switch (Op.getOpcode()) {
1316 case ISD::EntryToken:
1317 // Entry tokens don't need to be added to the list. They are
1322 case ISD::TokenFactor:
1323 if (Op.hasOneUse() &&
1324 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1325 // Queue up for processing.
1326 TFs.push_back(Op.getNode());
1327 // Clean up in case the token factor is removed.
1328 AddToWorkList(Op.getNode());
1335 // Only add if it isn't already in the list.
1336 if (SeenOps.insert(Op.getNode()))
1347 // If we've change things around then replace token factor.
1350 // The entry token is the only possible outcome.
1351 Result = DAG.getEntryNode();
1353 // New and improved token factor.
1354 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1355 MVT::Other, &Ops[0], Ops.size());
1358 // Don't add users to work list.
1359 return CombineTo(N, Result, false);
1365 /// MERGE_VALUES can always be eliminated.
1366 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1367 WorkListRemover DeadNodes(*this);
1368 // Replacing results may cause a different MERGE_VALUES to suddenly
1369 // be CSE'd with N, and carry its uses with it. Iterate until no
1370 // uses remain, to ensure that the node can be safely deleted.
1371 // First add the users of this node to the work list so that they
1372 // can be tried again once they have new operands.
1373 AddUsersToWorkList(N);
1375 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1376 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1377 } while (!N->use_empty());
1378 removeFromWorkList(N);
1380 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1384 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1385 SelectionDAG &DAG) {
1386 EVT VT = N0.getValueType();
1387 SDValue N00 = N0.getOperand(0);
1388 SDValue N01 = N0.getOperand(1);
1389 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1391 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1392 isa<ConstantSDNode>(N00.getOperand(1))) {
1393 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1394 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1395 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1396 N00.getOperand(0), N01),
1397 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1398 N00.getOperand(1), N01));
1399 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1405 SDValue DAGCombiner::visitADD(SDNode *N) {
1406 SDValue N0 = N->getOperand(0);
1407 SDValue N1 = N->getOperand(1);
1408 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1409 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1410 EVT VT = N0.getValueType();
1413 if (VT.isVector()) {
1414 SDValue FoldedVOp = SimplifyVBinOp(N);
1415 if (FoldedVOp.getNode()) return FoldedVOp;
1417 // fold (add x, 0) -> x, vector edition
1418 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1420 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1424 // fold (add x, undef) -> undef
1425 if (N0.getOpcode() == ISD::UNDEF)
1427 if (N1.getOpcode() == ISD::UNDEF)
1429 // fold (add c1, c2) -> c1+c2
1431 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1432 // canonicalize constant to RHS
1434 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1435 // fold (add x, 0) -> x
1436 if (N1C && N1C->isNullValue())
1438 // fold (add Sym, c) -> Sym+c
1439 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1440 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1441 GA->getOpcode() == ISD::GlobalAddress)
1442 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1444 (uint64_t)N1C->getSExtValue());
1445 // fold ((c1-A)+c2) -> (c1+c2)-A
1446 if (N1C && N0.getOpcode() == ISD::SUB)
1447 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1448 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1449 DAG.getConstant(N1C->getAPIntValue()+
1450 N0C->getAPIntValue(), VT),
1453 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1454 if (RADD.getNode() != 0)
1456 // fold ((0-A) + B) -> B-A
1457 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1458 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1459 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1460 // fold (A + (0-B)) -> A-B
1461 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1462 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1463 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1464 // fold (A+(B-A)) -> B
1465 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1466 return N1.getOperand(0);
1467 // fold ((B-A)+A) -> B
1468 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1469 return N0.getOperand(0);
1470 // fold (A+(B-(A+C))) to (B-C)
1471 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1472 N0 == N1.getOperand(1).getOperand(0))
1473 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1474 N1.getOperand(1).getOperand(1));
1475 // fold (A+(B-(C+A))) to (B-C)
1476 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1477 N0 == N1.getOperand(1).getOperand(1))
1478 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1479 N1.getOperand(1).getOperand(0));
1480 // fold (A+((B-A)+or-C)) to (B+or-C)
1481 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1482 N1.getOperand(0).getOpcode() == ISD::SUB &&
1483 N0 == N1.getOperand(0).getOperand(1))
1484 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1485 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1487 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1488 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1489 SDValue N00 = N0.getOperand(0);
1490 SDValue N01 = N0.getOperand(1);
1491 SDValue N10 = N1.getOperand(0);
1492 SDValue N11 = N1.getOperand(1);
1494 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1495 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1496 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1497 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1500 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1501 return SDValue(N, 0);
1503 // fold (a+b) -> (a|b) iff a and b share no bits.
1504 if (VT.isInteger() && !VT.isVector()) {
1505 APInt LHSZero, LHSOne;
1506 APInt RHSZero, RHSOne;
1507 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1509 if (LHSZero.getBoolValue()) {
1510 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1512 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1513 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1514 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1515 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1519 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1520 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1521 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1522 if (Result.getNode()) return Result;
1524 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1525 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1526 if (Result.getNode()) return Result;
1529 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1530 if (N1.getOpcode() == ISD::SHL &&
1531 N1.getOperand(0).getOpcode() == ISD::SUB)
1532 if (ConstantSDNode *C =
1533 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1534 if (C->getAPIntValue() == 0)
1535 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1536 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1537 N1.getOperand(0).getOperand(1),
1539 if (N0.getOpcode() == ISD::SHL &&
1540 N0.getOperand(0).getOpcode() == ISD::SUB)
1541 if (ConstantSDNode *C =
1542 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1543 if (C->getAPIntValue() == 0)
1544 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1545 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1546 N0.getOperand(0).getOperand(1),
1549 if (N1.getOpcode() == ISD::AND) {
1550 SDValue AndOp0 = N1.getOperand(0);
1551 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1552 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1553 unsigned DestBits = VT.getScalarType().getSizeInBits();
1555 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1556 // and similar xforms where the inner op is either ~0 or 0.
1557 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1559 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1563 // add (sext i1), X -> sub X, (zext i1)
1564 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1565 N0.getOperand(0).getValueType() == MVT::i1 &&
1566 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1568 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1569 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1575 SDValue DAGCombiner::visitADDC(SDNode *N) {
1576 SDValue N0 = N->getOperand(0);
1577 SDValue N1 = N->getOperand(1);
1578 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1580 EVT VT = N0.getValueType();
1582 // If the flag result is dead, turn this into an ADD.
1583 if (!N->hasAnyUseOfValue(1))
1584 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1585 DAG.getNode(ISD::CARRY_FALSE,
1586 SDLoc(N), MVT::Glue));
1588 // canonicalize constant to RHS.
1590 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1592 // fold (addc x, 0) -> x + no carry out
1593 if (N1C && N1C->isNullValue())
1594 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1595 SDLoc(N), MVT::Glue));
1597 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1598 APInt LHSZero, LHSOne;
1599 APInt RHSZero, RHSOne;
1600 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1602 if (LHSZero.getBoolValue()) {
1603 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1605 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1606 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1607 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1608 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1609 DAG.getNode(ISD::CARRY_FALSE,
1610 SDLoc(N), MVT::Glue));
1616 SDValue DAGCombiner::visitADDE(SDNode *N) {
1617 SDValue N0 = N->getOperand(0);
1618 SDValue N1 = N->getOperand(1);
1619 SDValue CarryIn = N->getOperand(2);
1620 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1621 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1623 // canonicalize constant to RHS
1625 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1628 // fold (adde x, y, false) -> (addc x, y)
1629 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1630 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1635 // Since it may not be valid to emit a fold to zero for vector initializers
1636 // check if we can before folding.
1637 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1639 bool LegalOperations, bool LegalTypes) {
1641 return DAG.getConstant(0, VT);
1642 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1643 // Produce a vector of zeros.
1644 EVT ElemTy = VT.getVectorElementType();
1645 if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) ==
1646 TargetLowering::TypePromoteInteger)
1647 ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy);
1648 assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) &&
1649 "Type for zero vector elements is not legal");
1650 SDValue El = DAG.getConstant(0, ElemTy);
1651 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1652 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1653 &Ops[0], Ops.size());
1658 SDValue DAGCombiner::visitSUB(SDNode *N) {
1659 SDValue N0 = N->getOperand(0);
1660 SDValue N1 = N->getOperand(1);
1661 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1662 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1663 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1664 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1665 EVT VT = N0.getValueType();
1668 if (VT.isVector()) {
1669 SDValue FoldedVOp = SimplifyVBinOp(N);
1670 if (FoldedVOp.getNode()) return FoldedVOp;
1672 // fold (sub x, 0) -> x, vector edition
1673 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1677 // fold (sub x, x) -> 0
1678 // FIXME: Refactor this and xor and other similar operations together.
1680 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1681 // fold (sub c1, c2) -> c1-c2
1683 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1684 // fold (sub x, c) -> (add x, -c)
1686 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1687 DAG.getConstant(-N1C->getAPIntValue(), VT));
1688 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1689 if (N0C && N0C->isAllOnesValue())
1690 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1691 // fold A-(A-B) -> B
1692 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1693 return N1.getOperand(1);
1694 // fold (A+B)-A -> B
1695 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1696 return N0.getOperand(1);
1697 // fold (A+B)-B -> A
1698 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1699 return N0.getOperand(0);
1700 // fold C2-(A+C1) -> (C2-C1)-A
1701 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1702 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1704 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1707 // fold ((A+(B+or-C))-B) -> A+or-C
1708 if (N0.getOpcode() == ISD::ADD &&
1709 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1710 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1711 N0.getOperand(1).getOperand(0) == N1)
1712 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1713 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1714 // fold ((A+(C+B))-B) -> A+C
1715 if (N0.getOpcode() == ISD::ADD &&
1716 N0.getOperand(1).getOpcode() == ISD::ADD &&
1717 N0.getOperand(1).getOperand(1) == N1)
1718 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1719 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1720 // fold ((A-(B-C))-C) -> A-B
1721 if (N0.getOpcode() == ISD::SUB &&
1722 N0.getOperand(1).getOpcode() == ISD::SUB &&
1723 N0.getOperand(1).getOperand(1) == N1)
1724 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1725 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1727 // If either operand of a sub is undef, the result is undef
1728 if (N0.getOpcode() == ISD::UNDEF)
1730 if (N1.getOpcode() == ISD::UNDEF)
1733 // If the relocation model supports it, consider symbol offsets.
1734 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1735 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1736 // fold (sub Sym, c) -> Sym-c
1737 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1738 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1740 (uint64_t)N1C->getSExtValue());
1741 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1742 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1743 if (GA->getGlobal() == GB->getGlobal())
1744 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1751 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1752 SDValue N0 = N->getOperand(0);
1753 SDValue N1 = N->getOperand(1);
1754 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1755 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1756 EVT VT = N0.getValueType();
1758 // If the flag result is dead, turn this into an SUB.
1759 if (!N->hasAnyUseOfValue(1))
1760 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1761 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1764 // fold (subc x, x) -> 0 + no borrow
1766 return CombineTo(N, DAG.getConstant(0, VT),
1767 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1770 // fold (subc x, 0) -> x + no borrow
1771 if (N1C && N1C->isNullValue())
1772 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1775 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1776 if (N0C && N0C->isAllOnesValue())
1777 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1778 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1784 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1785 SDValue N0 = N->getOperand(0);
1786 SDValue N1 = N->getOperand(1);
1787 SDValue CarryIn = N->getOperand(2);
1789 // fold (sube x, y, false) -> (subc x, y)
1790 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1791 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1796 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1797 /// elements are all the same constant or undefined.
1798 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1799 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1804 unsigned SplatBitSize;
1806 EVT EltVT = N->getValueType(0).getVectorElementType();
1807 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1809 EltVT.getSizeInBits() >= SplatBitSize);
1812 SDValue DAGCombiner::visitMUL(SDNode *N) {
1813 SDValue N0 = N->getOperand(0);
1814 SDValue N1 = N->getOperand(1);
1815 EVT VT = N0.getValueType();
1817 // fold (mul x, undef) -> 0
1818 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1819 return DAG.getConstant(0, VT);
1821 bool N0IsConst = false;
1822 bool N1IsConst = false;
1823 APInt ConstValue0, ConstValue1;
1825 if (VT.isVector()) {
1826 SDValue FoldedVOp = SimplifyVBinOp(N);
1827 if (FoldedVOp.getNode()) return FoldedVOp;
1829 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1830 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1832 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1833 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1835 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1836 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1840 // fold (mul c1, c2) -> c1*c2
1841 if (N0IsConst && N1IsConst)
1842 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1844 // canonicalize constant to RHS
1845 if (N0IsConst && !N1IsConst)
1846 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1847 // fold (mul x, 0) -> 0
1848 if (N1IsConst && ConstValue1 == 0)
1850 // We require a splat of the entire scalar bit width for non-contiguous
1853 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1854 // fold (mul x, 1) -> x
1855 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1857 // fold (mul x, -1) -> 0-x
1858 if (N1IsConst && ConstValue1.isAllOnesValue())
1859 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1860 DAG.getConstant(0, VT), N0);
1861 // fold (mul x, (1 << c)) -> x << c
1862 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1863 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1864 DAG.getConstant(ConstValue1.logBase2(),
1865 getShiftAmountTy(N0.getValueType())));
1866 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1867 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1868 unsigned Log2Val = (-ConstValue1).logBase2();
1869 // FIXME: If the input is something that is easily negated (e.g. a
1870 // single-use add), we should put the negate there.
1871 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1872 DAG.getConstant(0, VT),
1873 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1874 DAG.getConstant(Log2Val,
1875 getShiftAmountTy(N0.getValueType()))));
1879 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1880 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1881 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1882 isa<ConstantSDNode>(N0.getOperand(1)))) {
1883 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1884 N1, N0.getOperand(1));
1885 AddToWorkList(C3.getNode());
1886 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1887 N0.getOperand(0), C3);
1890 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1893 SDValue Sh(0,0), Y(0,0);
1894 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1895 if (N0.getOpcode() == ISD::SHL &&
1896 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1897 isa<ConstantSDNode>(N0.getOperand(1))) &&
1898 N0.getNode()->hasOneUse()) {
1900 } else if (N1.getOpcode() == ISD::SHL &&
1901 isa<ConstantSDNode>(N1.getOperand(1)) &&
1902 N1.getNode()->hasOneUse()) {
1907 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1908 Sh.getOperand(0), Y);
1909 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1910 Mul, Sh.getOperand(1));
1914 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1915 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1916 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1917 isa<ConstantSDNode>(N0.getOperand(1))))
1918 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1919 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1920 N0.getOperand(0), N1),
1921 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1922 N0.getOperand(1), N1));
1925 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1926 if (RMUL.getNode() != 0)
1932 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1933 SDValue N0 = N->getOperand(0);
1934 SDValue N1 = N->getOperand(1);
1935 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1936 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1937 EVT VT = N->getValueType(0);
1940 if (VT.isVector()) {
1941 SDValue FoldedVOp = SimplifyVBinOp(N);
1942 if (FoldedVOp.getNode()) return FoldedVOp;
1945 // fold (sdiv c1, c2) -> c1/c2
1946 if (N0C && N1C && !N1C->isNullValue())
1947 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1948 // fold (sdiv X, 1) -> X
1949 if (N1C && N1C->getAPIntValue() == 1LL)
1951 // fold (sdiv X, -1) -> 0-X
1952 if (N1C && N1C->isAllOnesValue())
1953 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1954 DAG.getConstant(0, VT), N0);
1955 // If we know the sign bits of both operands are zero, strength reduce to a
1956 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1957 if (!VT.isVector()) {
1958 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1959 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1962 // fold (sdiv X, pow2) -> simple ops after legalize
1963 if (N1C && !N1C->isNullValue() &&
1964 (N1C->getAPIntValue().isPowerOf2() ||
1965 (-N1C->getAPIntValue()).isPowerOf2())) {
1966 // If dividing by powers of two is cheap, then don't perform the following
1968 if (TLI.isPow2DivCheap())
1971 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1973 // Splat the sign bit into the register
1974 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1975 DAG.getConstant(VT.getSizeInBits()-1,
1976 getShiftAmountTy(N0.getValueType())));
1977 AddToWorkList(SGN.getNode());
1979 // Add (N0 < 0) ? abs2 - 1 : 0;
1980 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1981 DAG.getConstant(VT.getSizeInBits() - lg2,
1982 getShiftAmountTy(SGN.getValueType())));
1983 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1984 AddToWorkList(SRL.getNode());
1985 AddToWorkList(ADD.getNode()); // Divide by pow2
1986 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1987 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1989 // If we're dividing by a positive value, we're done. Otherwise, we must
1990 // negate the result.
1991 if (N1C->getAPIntValue().isNonNegative())
1994 AddToWorkList(SRA.getNode());
1995 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1996 DAG.getConstant(0, VT), SRA);
1999 // if integer divide is expensive and we satisfy the requirements, emit an
2000 // alternate sequence.
2001 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2002 SDValue Op = BuildSDIV(N);
2003 if (Op.getNode()) return Op;
2007 if (N0.getOpcode() == ISD::UNDEF)
2008 return DAG.getConstant(0, VT);
2009 // X / undef -> undef
2010 if (N1.getOpcode() == ISD::UNDEF)
2016 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2017 SDValue N0 = N->getOperand(0);
2018 SDValue N1 = N->getOperand(1);
2019 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2020 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2021 EVT VT = N->getValueType(0);
2024 if (VT.isVector()) {
2025 SDValue FoldedVOp = SimplifyVBinOp(N);
2026 if (FoldedVOp.getNode()) return FoldedVOp;
2029 // fold (udiv c1, c2) -> c1/c2
2030 if (N0C && N1C && !N1C->isNullValue())
2031 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2032 // fold (udiv x, (1 << c)) -> x >>u c
2033 if (N1C && N1C->getAPIntValue().isPowerOf2())
2034 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2035 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2036 getShiftAmountTy(N0.getValueType())));
2037 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2038 if (N1.getOpcode() == ISD::SHL) {
2039 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2040 if (SHC->getAPIntValue().isPowerOf2()) {
2041 EVT ADDVT = N1.getOperand(1).getValueType();
2042 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2044 DAG.getConstant(SHC->getAPIntValue()
2047 AddToWorkList(Add.getNode());
2048 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2052 // fold (udiv x, c) -> alternate
2053 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2054 SDValue Op = BuildUDIV(N);
2055 if (Op.getNode()) return Op;
2059 if (N0.getOpcode() == ISD::UNDEF)
2060 return DAG.getConstant(0, VT);
2061 // X / undef -> undef
2062 if (N1.getOpcode() == ISD::UNDEF)
2068 SDValue DAGCombiner::visitSREM(SDNode *N) {
2069 SDValue N0 = N->getOperand(0);
2070 SDValue N1 = N->getOperand(1);
2071 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2072 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2073 EVT VT = N->getValueType(0);
2075 // fold (srem c1, c2) -> c1%c2
2076 if (N0C && N1C && !N1C->isNullValue())
2077 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2078 // If we know the sign bits of both operands are zero, strength reduce to a
2079 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2080 if (!VT.isVector()) {
2081 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2082 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2085 // If X/C can be simplified by the division-by-constant logic, lower
2086 // X%C to the equivalent of X-X/C*C.
2087 if (N1C && !N1C->isNullValue()) {
2088 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2089 AddToWorkList(Div.getNode());
2090 SDValue OptimizedDiv = combine(Div.getNode());
2091 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2092 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2094 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2095 AddToWorkList(Mul.getNode());
2101 if (N0.getOpcode() == ISD::UNDEF)
2102 return DAG.getConstant(0, VT);
2103 // X % undef -> undef
2104 if (N1.getOpcode() == ISD::UNDEF)
2110 SDValue DAGCombiner::visitUREM(SDNode *N) {
2111 SDValue N0 = N->getOperand(0);
2112 SDValue N1 = N->getOperand(1);
2113 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2114 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2115 EVT VT = N->getValueType(0);
2117 // fold (urem c1, c2) -> c1%c2
2118 if (N0C && N1C && !N1C->isNullValue())
2119 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2120 // fold (urem x, pow2) -> (and x, pow2-1)
2121 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2122 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2123 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2124 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2125 if (N1.getOpcode() == ISD::SHL) {
2126 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2127 if (SHC->getAPIntValue().isPowerOf2()) {
2129 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2130 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2132 AddToWorkList(Add.getNode());
2133 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2138 // If X/C can be simplified by the division-by-constant logic, lower
2139 // X%C to the equivalent of X-X/C*C.
2140 if (N1C && !N1C->isNullValue()) {
2141 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2142 AddToWorkList(Div.getNode());
2143 SDValue OptimizedDiv = combine(Div.getNode());
2144 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2145 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2147 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2148 AddToWorkList(Mul.getNode());
2154 if (N0.getOpcode() == ISD::UNDEF)
2155 return DAG.getConstant(0, VT);
2156 // X % undef -> undef
2157 if (N1.getOpcode() == ISD::UNDEF)
2163 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2164 SDValue N0 = N->getOperand(0);
2165 SDValue N1 = N->getOperand(1);
2166 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2167 EVT VT = N->getValueType(0);
2170 // fold (mulhs x, 0) -> 0
2171 if (N1C && N1C->isNullValue())
2173 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2174 if (N1C && N1C->getAPIntValue() == 1)
2175 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2176 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2177 getShiftAmountTy(N0.getValueType())));
2178 // fold (mulhs x, undef) -> 0
2179 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2180 return DAG.getConstant(0, VT);
2182 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2184 if (VT.isSimple() && !VT.isVector()) {
2185 MVT Simple = VT.getSimpleVT();
2186 unsigned SimpleSize = Simple.getSizeInBits();
2187 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2188 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2189 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2190 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2191 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2192 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2193 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2194 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2201 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2202 SDValue N0 = N->getOperand(0);
2203 SDValue N1 = N->getOperand(1);
2204 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2205 EVT VT = N->getValueType(0);
2208 // fold (mulhu x, 0) -> 0
2209 if (N1C && N1C->isNullValue())
2211 // fold (mulhu x, 1) -> 0
2212 if (N1C && N1C->getAPIntValue() == 1)
2213 return DAG.getConstant(0, N0.getValueType());
2214 // fold (mulhu x, undef) -> 0
2215 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2216 return DAG.getConstant(0, VT);
2218 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2220 if (VT.isSimple() && !VT.isVector()) {
2221 MVT Simple = VT.getSimpleVT();
2222 unsigned SimpleSize = Simple.getSizeInBits();
2223 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2224 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2225 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2226 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2227 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2228 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2229 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2230 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2237 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2238 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2239 /// that are being performed. Return true if a simplification was made.
2241 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2243 // If the high half is not needed, just compute the low half.
2244 bool HiExists = N->hasAnyUseOfValue(1);
2246 (!LegalOperations ||
2247 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2248 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2249 N->op_begin(), N->getNumOperands());
2250 return CombineTo(N, Res, Res);
2253 // If the low half is not needed, just compute the high half.
2254 bool LoExists = N->hasAnyUseOfValue(0);
2256 (!LegalOperations ||
2257 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2258 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2259 N->op_begin(), N->getNumOperands());
2260 return CombineTo(N, Res, Res);
2263 // If both halves are used, return as it is.
2264 if (LoExists && HiExists)
2267 // If the two computed results can be simplified separately, separate them.
2269 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2270 N->op_begin(), N->getNumOperands());
2271 AddToWorkList(Lo.getNode());
2272 SDValue LoOpt = combine(Lo.getNode());
2273 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2274 (!LegalOperations ||
2275 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2276 return CombineTo(N, LoOpt, LoOpt);
2280 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2281 N->op_begin(), N->getNumOperands());
2282 AddToWorkList(Hi.getNode());
2283 SDValue HiOpt = combine(Hi.getNode());
2284 if (HiOpt.getNode() && HiOpt != Hi &&
2285 (!LegalOperations ||
2286 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2287 return CombineTo(N, HiOpt, HiOpt);
2293 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2294 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2295 if (Res.getNode()) return Res;
2297 EVT VT = N->getValueType(0);
2300 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2302 if (VT.isSimple() && !VT.isVector()) {
2303 MVT Simple = VT.getSimpleVT();
2304 unsigned SimpleSize = Simple.getSizeInBits();
2305 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2306 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2307 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2308 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2309 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2310 // Compute the high part as N1.
2311 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2312 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2313 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2314 // Compute the low part as N0.
2315 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2316 return CombineTo(N, Lo, Hi);
2323 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2324 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2325 if (Res.getNode()) return Res;
2327 EVT VT = N->getValueType(0);
2330 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2332 if (VT.isSimple() && !VT.isVector()) {
2333 MVT Simple = VT.getSimpleVT();
2334 unsigned SimpleSize = Simple.getSizeInBits();
2335 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2336 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2337 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2338 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2339 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2340 // Compute the high part as N1.
2341 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2342 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2343 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2344 // Compute the low part as N0.
2345 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2346 return CombineTo(N, Lo, Hi);
2353 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2354 // (smulo x, 2) -> (saddo x, x)
2355 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2356 if (C2->getAPIntValue() == 2)
2357 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2358 N->getOperand(0), N->getOperand(0));
2363 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2364 // (umulo x, 2) -> (uaddo x, x)
2365 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2366 if (C2->getAPIntValue() == 2)
2367 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2368 N->getOperand(0), N->getOperand(0));
2373 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2374 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2375 if (Res.getNode()) return Res;
2380 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2381 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2382 if (Res.getNode()) return Res;
2387 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2388 /// two operands of the same opcode, try to simplify it.
2389 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2390 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2391 EVT VT = N0.getValueType();
2392 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2394 // Bail early if none of these transforms apply.
2395 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2397 // For each of OP in AND/OR/XOR:
2398 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2399 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2400 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2401 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2403 // do not sink logical op inside of a vector extend, since it may combine
2405 EVT Op0VT = N0.getOperand(0).getValueType();
2406 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2407 N0.getOpcode() == ISD::SIGN_EXTEND ||
2408 // Avoid infinite looping with PromoteIntBinOp.
2409 (N0.getOpcode() == ISD::ANY_EXTEND &&
2410 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2411 (N0.getOpcode() == ISD::TRUNCATE &&
2412 (!TLI.isZExtFree(VT, Op0VT) ||
2413 !TLI.isTruncateFree(Op0VT, VT)) &&
2414 TLI.isTypeLegal(Op0VT))) &&
2416 Op0VT == N1.getOperand(0).getValueType() &&
2417 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2418 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2419 N0.getOperand(0).getValueType(),
2420 N0.getOperand(0), N1.getOperand(0));
2421 AddToWorkList(ORNode.getNode());
2422 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2425 // For each of OP in SHL/SRL/SRA/AND...
2426 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2427 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2428 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2429 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2430 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2431 N0.getOperand(1) == N1.getOperand(1)) {
2432 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2433 N0.getOperand(0).getValueType(),
2434 N0.getOperand(0), N1.getOperand(0));
2435 AddToWorkList(ORNode.getNode());
2436 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2437 ORNode, N0.getOperand(1));
2440 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2441 // Only perform this optimization after type legalization and before
2442 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2443 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2444 // we don't want to undo this promotion.
2445 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2447 if ((N0.getOpcode() == ISD::BITCAST ||
2448 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2449 Level == AfterLegalizeTypes) {
2450 SDValue In0 = N0.getOperand(0);
2451 SDValue In1 = N1.getOperand(0);
2452 EVT In0Ty = In0.getValueType();
2453 EVT In1Ty = In1.getValueType();
2455 // If both incoming values are integers, and the original types are the
2457 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2458 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2459 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2460 AddToWorkList(Op.getNode());
2465 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2466 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2467 // If both shuffles use the same mask, and both shuffle within a single
2468 // vector, then it is worthwhile to move the swizzle after the operation.
2469 // The type-legalizer generates this pattern when loading illegal
2470 // vector types from memory. In many cases this allows additional shuffle
2472 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2473 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2474 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2475 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2476 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2478 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2479 "Inputs to shuffles are not the same type");
2481 unsigned NumElts = VT.getVectorNumElements();
2483 // Check that both shuffles use the same mask. The masks are known to be of
2484 // the same length because the result vector type is the same.
2485 bool SameMask = true;
2486 for (unsigned i = 0; i != NumElts; ++i) {
2487 int Idx0 = SVN0->getMaskElt(i);
2488 int Idx1 = SVN1->getMaskElt(i);
2496 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2497 N0.getOperand(0), N1.getOperand(0));
2498 AddToWorkList(Op.getNode());
2499 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2500 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2507 SDValue DAGCombiner::visitAND(SDNode *N) {
2508 SDValue N0 = N->getOperand(0);
2509 SDValue N1 = N->getOperand(1);
2510 SDValue LL, LR, RL, RR, CC0, CC1;
2511 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2512 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2513 EVT VT = N1.getValueType();
2514 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2517 if (VT.isVector()) {
2518 SDValue FoldedVOp = SimplifyVBinOp(N);
2519 if (FoldedVOp.getNode()) return FoldedVOp;
2521 // fold (and x, 0) -> 0, vector edition
2522 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2524 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2527 // fold (and x, -1) -> x, vector edition
2528 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2530 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2534 // fold (and x, undef) -> 0
2535 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2536 return DAG.getConstant(0, VT);
2537 // fold (and c1, c2) -> c1&c2
2539 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2540 // canonicalize constant to RHS
2542 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2543 // fold (and x, -1) -> x
2544 if (N1C && N1C->isAllOnesValue())
2546 // if (and x, c) is known to be zero, return 0
2547 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2548 APInt::getAllOnesValue(BitWidth)))
2549 return DAG.getConstant(0, VT);
2551 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2552 if (RAND.getNode() != 0)
2554 // fold (and (or x, C), D) -> D if (C & D) == D
2555 if (N1C && N0.getOpcode() == ISD::OR)
2556 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2557 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2559 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2560 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2561 SDValue N0Op0 = N0.getOperand(0);
2562 APInt Mask = ~N1C->getAPIntValue();
2563 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2564 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2565 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2566 N0.getValueType(), N0Op0);
2568 // Replace uses of the AND with uses of the Zero extend node.
2571 // We actually want to replace all uses of the any_extend with the
2572 // zero_extend, to avoid duplicating things. This will later cause this
2573 // AND to be folded.
2574 CombineTo(N0.getNode(), Zext);
2575 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2578 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2579 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2580 // already be zero by virtue of the width of the base type of the load.
2582 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2584 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2585 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2586 N0.getOpcode() == ISD::LOAD) {
2587 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2588 N0 : N0.getOperand(0) );
2590 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2591 // This can be a pure constant or a vector splat, in which case we treat the
2592 // vector as a scalar and use the splat value.
2593 APInt Constant = APInt::getNullValue(1);
2594 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2595 Constant = C->getAPIntValue();
2596 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2597 APInt SplatValue, SplatUndef;
2598 unsigned SplatBitSize;
2600 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2601 SplatBitSize, HasAnyUndefs);
2603 // Undef bits can contribute to a possible optimisation if set, so
2605 SplatValue |= SplatUndef;
2607 // The splat value may be something like "0x00FFFFFF", which means 0 for
2608 // the first vector value and FF for the rest, repeating. We need a mask
2609 // that will apply equally to all members of the vector, so AND all the
2610 // lanes of the constant together.
2611 EVT VT = Vector->getValueType(0);
2612 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2614 // If the splat value has been compressed to a bitlength lower
2615 // than the size of the vector lane, we need to re-expand it to
2617 if (BitWidth > SplatBitSize)
2618 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2619 SplatBitSize < BitWidth;
2620 SplatBitSize = SplatBitSize * 2)
2621 SplatValue |= SplatValue.shl(SplatBitSize);
2623 Constant = APInt::getAllOnesValue(BitWidth);
2624 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2625 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2629 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2630 // actually legal and isn't going to get expanded, else this is a false
2632 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2633 Load->getMemoryVT());
2635 // Resize the constant to the same size as the original memory access before
2636 // extension. If it is still the AllOnesValue then this AND is completely
2639 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2642 switch (Load->getExtensionType()) {
2643 default: B = false; break;
2644 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2646 case ISD::NON_EXTLOAD: B = true; break;
2649 if (B && Constant.isAllOnesValue()) {
2650 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2651 // preserve semantics once we get rid of the AND.
2652 SDValue NewLoad(Load, 0);
2653 if (Load->getExtensionType() == ISD::EXTLOAD) {
2654 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2655 Load->getValueType(0), SDLoc(Load),
2656 Load->getChain(), Load->getBasePtr(),
2657 Load->getOffset(), Load->getMemoryVT(),
2658 Load->getMemOperand());
2659 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2660 if (Load->getNumValues() == 3) {
2661 // PRE/POST_INC loads have 3 values.
2662 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2663 NewLoad.getValue(2) };
2664 CombineTo(Load, To, 3, true);
2666 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2670 // Fold the AND away, taking care not to fold to the old load node if we
2672 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2674 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2677 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2678 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2679 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2680 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2682 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2683 LL.getValueType().isInteger()) {
2684 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2685 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2686 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2687 LR.getValueType(), LL, RL);
2688 AddToWorkList(ORNode.getNode());
2689 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2691 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2692 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2693 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2694 LR.getValueType(), LL, RL);
2695 AddToWorkList(ANDNode.getNode());
2696 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2698 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2699 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2700 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2701 LR.getValueType(), LL, RL);
2702 AddToWorkList(ORNode.getNode());
2703 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2706 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2707 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2708 Op0 == Op1 && LL.getValueType().isInteger() &&
2709 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2710 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2711 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2712 cast<ConstantSDNode>(RR)->isNullValue()))) {
2713 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2714 LL, DAG.getConstant(1, LL.getValueType()));
2715 AddToWorkList(ADDNode.getNode());
2716 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2717 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2719 // canonicalize equivalent to ll == rl
2720 if (LL == RR && LR == RL) {
2721 Op1 = ISD::getSetCCSwappedOperands(Op1);
2724 if (LL == RL && LR == RR) {
2725 bool isInteger = LL.getValueType().isInteger();
2726 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2727 if (Result != ISD::SETCC_INVALID &&
2728 (!LegalOperations ||
2729 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2730 TLI.isOperationLegal(ISD::SETCC,
2731 getSetCCResultType(N0.getSimpleValueType())))))
2732 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2737 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2738 if (N0.getOpcode() == N1.getOpcode()) {
2739 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2740 if (Tmp.getNode()) return Tmp;
2743 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2744 // fold (and (sra)) -> (and (srl)) when possible.
2745 if (!VT.isVector() &&
2746 SimplifyDemandedBits(SDValue(N, 0)))
2747 return SDValue(N, 0);
2749 // fold (zext_inreg (extload x)) -> (zextload x)
2750 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2751 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2752 EVT MemVT = LN0->getMemoryVT();
2753 // If we zero all the possible extended bits, then we can turn this into
2754 // a zextload if we are running before legalize or the operation is legal.
2755 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2756 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2757 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2758 ((!LegalOperations && !LN0->isVolatile()) ||
2759 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2760 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2761 LN0->getChain(), LN0->getBasePtr(),
2762 LN0->getPointerInfo(), MemVT,
2763 LN0->isVolatile(), LN0->isNonTemporal(),
2764 LN0->getAlignment());
2766 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2767 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2770 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2771 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2773 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2774 EVT MemVT = LN0->getMemoryVT();
2775 // If we zero all the possible extended bits, then we can turn this into
2776 // a zextload if we are running before legalize or the operation is legal.
2777 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2778 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2779 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2780 ((!LegalOperations && !LN0->isVolatile()) ||
2781 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2782 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2784 LN0->getBasePtr(), LN0->getPointerInfo(),
2786 LN0->isVolatile(), LN0->isNonTemporal(),
2787 LN0->getAlignment());
2789 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2790 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2794 // fold (and (load x), 255) -> (zextload x, i8)
2795 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2796 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2797 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2798 (N0.getOpcode() == ISD::ANY_EXTEND &&
2799 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2800 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2801 LoadSDNode *LN0 = HasAnyExt
2802 ? cast<LoadSDNode>(N0.getOperand(0))
2803 : cast<LoadSDNode>(N0);
2804 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2805 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2806 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2807 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2808 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2809 EVT LoadedVT = LN0->getMemoryVT();
2811 if (ExtVT == LoadedVT &&
2812 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2813 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2816 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2817 LN0->getChain(), LN0->getBasePtr(),
2818 LN0->getPointerInfo(),
2819 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2820 LN0->getAlignment());
2822 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2823 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2826 // Do not change the width of a volatile load.
2827 // Do not generate loads of non-round integer types since these can
2828 // be expensive (and would be wrong if the type is not byte sized).
2829 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2830 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2831 EVT PtrType = LN0->getOperand(1).getValueType();
2833 unsigned Alignment = LN0->getAlignment();
2834 SDValue NewPtr = LN0->getBasePtr();
2836 // For big endian targets, we need to add an offset to the pointer
2837 // to load the correct bytes. For little endian systems, we merely
2838 // need to read fewer bytes from the same pointer.
2839 if (TLI.isBigEndian()) {
2840 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2841 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2842 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2843 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2844 NewPtr, DAG.getConstant(PtrOff, PtrType));
2845 Alignment = MinAlign(Alignment, PtrOff);
2848 AddToWorkList(NewPtr.getNode());
2850 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2852 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2853 LN0->getChain(), NewPtr,
2854 LN0->getPointerInfo(),
2855 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2858 CombineTo(LN0, Load, Load.getValue(1));
2859 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2865 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2866 VT.getSizeInBits() <= 64) {
2867 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2868 APInt ADDC = ADDI->getAPIntValue();
2869 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2870 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2871 // immediate for an add, but it is legal if its top c2 bits are set,
2872 // transform the ADD so the immediate doesn't need to be materialized
2874 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2875 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2876 SRLI->getZExtValue());
2877 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2879 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2881 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2882 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2883 CombineTo(N0.getNode(), NewAdd);
2884 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2892 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2893 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2894 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2895 N0.getOperand(1), false);
2896 if (BSwap.getNode())
2903 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2905 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2906 bool DemandHighBits) {
2907 if (!LegalOperations)
2910 EVT VT = N->getValueType(0);
2911 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2913 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2916 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2917 bool LookPassAnd0 = false;
2918 bool LookPassAnd1 = false;
2919 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2921 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2923 if (N0.getOpcode() == ISD::AND) {
2924 if (!N0.getNode()->hasOneUse())
2926 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2927 if (!N01C || N01C->getZExtValue() != 0xFF00)
2929 N0 = N0.getOperand(0);
2930 LookPassAnd0 = true;
2933 if (N1.getOpcode() == ISD::AND) {
2934 if (!N1.getNode()->hasOneUse())
2936 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2937 if (!N11C || N11C->getZExtValue() != 0xFF)
2939 N1 = N1.getOperand(0);
2940 LookPassAnd1 = true;
2943 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2945 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2947 if (!N0.getNode()->hasOneUse() ||
2948 !N1.getNode()->hasOneUse())
2951 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2952 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2955 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2958 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2959 SDValue N00 = N0->getOperand(0);
2960 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2961 if (!N00.getNode()->hasOneUse())
2963 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2964 if (!N001C || N001C->getZExtValue() != 0xFF)
2966 N00 = N00.getOperand(0);
2967 LookPassAnd0 = true;
2970 SDValue N10 = N1->getOperand(0);
2971 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2972 if (!N10.getNode()->hasOneUse())
2974 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2975 if (!N101C || N101C->getZExtValue() != 0xFF00)
2977 N10 = N10.getOperand(0);
2978 LookPassAnd1 = true;
2984 // Make sure everything beyond the low halfword gets set to zero since the SRL
2985 // 16 will clear the top bits.
2986 unsigned OpSizeInBits = VT.getSizeInBits();
2987 if (DemandHighBits && OpSizeInBits > 16) {
2988 // If the left-shift isn't masked out then the only way this is a bswap is
2989 // if all bits beyond the low 8 are 0. In that case the entire pattern
2990 // reduces to a left shift anyway: leave it for other parts of the combiner.
2994 // However, if the right shift isn't masked out then it might be because
2995 // it's not needed. See if we can spot that too.
2996 if (!LookPassAnd1 &&
2997 !DAG.MaskedValueIsZero(
2998 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3002 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3003 if (OpSizeInBits > 16)
3004 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3005 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3009 /// isBSwapHWordElement - Return true if the specified node is an element
3010 /// that makes up a 32-bit packed halfword byteswap. i.e.
3011 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3012 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3013 if (!N.getNode()->hasOneUse())
3016 unsigned Opc = N.getOpcode();
3017 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3020 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3025 switch (N1C->getZExtValue()) {
3028 case 0xFF: Num = 0; break;
3029 case 0xFF00: Num = 1; break;
3030 case 0xFF0000: Num = 2; break;
3031 case 0xFF000000: Num = 3; break;
3034 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3035 SDValue N0 = N.getOperand(0);
3036 if (Opc == ISD::AND) {
3037 if (Num == 0 || Num == 2) {
3039 // (x >> 8) & 0xff0000
3040 if (N0.getOpcode() != ISD::SRL)
3042 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3043 if (!C || C->getZExtValue() != 8)
3046 // (x << 8) & 0xff00
3047 // (x << 8) & 0xff000000
3048 if (N0.getOpcode() != ISD::SHL)
3050 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3051 if (!C || C->getZExtValue() != 8)
3054 } else if (Opc == ISD::SHL) {
3056 // (x & 0xff0000) << 8
3057 if (Num != 0 && Num != 2)
3059 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3060 if (!C || C->getZExtValue() != 8)
3062 } else { // Opc == ISD::SRL
3063 // (x & 0xff00) >> 8
3064 // (x & 0xff000000) >> 8
3065 if (Num != 1 && Num != 3)
3067 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3068 if (!C || C->getZExtValue() != 8)
3075 Parts[Num] = N0.getOperand(0).getNode();
3079 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3080 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3081 /// => (rotl (bswap x), 16)
3082 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3083 if (!LegalOperations)
3086 EVT VT = N->getValueType(0);
3089 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3092 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3094 // (or (or (and), (and)), (or (and), (and)))
3095 // (or (or (or (and), (and)), (and)), (and))
3096 if (N0.getOpcode() != ISD::OR)
3098 SDValue N00 = N0.getOperand(0);
3099 SDValue N01 = N0.getOperand(1);
3101 if (N1.getOpcode() == ISD::OR &&
3102 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3103 // (or (or (and), (and)), (or (and), (and)))
3104 SDValue N000 = N00.getOperand(0);
3105 if (!isBSwapHWordElement(N000, Parts))
3108 SDValue N001 = N00.getOperand(1);
3109 if (!isBSwapHWordElement(N001, Parts))
3111 SDValue N010 = N01.getOperand(0);
3112 if (!isBSwapHWordElement(N010, Parts))
3114 SDValue N011 = N01.getOperand(1);
3115 if (!isBSwapHWordElement(N011, Parts))
3118 // (or (or (or (and), (and)), (and)), (and))
3119 if (!isBSwapHWordElement(N1, Parts))
3121 if (!isBSwapHWordElement(N01, Parts))
3123 if (N00.getOpcode() != ISD::OR)
3125 SDValue N000 = N00.getOperand(0);
3126 if (!isBSwapHWordElement(N000, Parts))
3128 SDValue N001 = N00.getOperand(1);
3129 if (!isBSwapHWordElement(N001, Parts))
3133 // Make sure the parts are all coming from the same node.
3134 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3137 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3138 SDValue(Parts[0],0));
3140 // Result of the bswap should be rotated by 16. If it's not legal, then
3141 // do (x << 16) | (x >> 16).
3142 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3143 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3144 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3145 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3146 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3147 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3148 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3149 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3152 SDValue DAGCombiner::visitOR(SDNode *N) {
3153 SDValue N0 = N->getOperand(0);
3154 SDValue N1 = N->getOperand(1);
3155 SDValue LL, LR, RL, RR, CC0, CC1;
3156 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3157 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3158 EVT VT = N1.getValueType();
3161 if (VT.isVector()) {
3162 SDValue FoldedVOp = SimplifyVBinOp(N);
3163 if (FoldedVOp.getNode()) return FoldedVOp;
3165 // fold (or x, 0) -> x, vector edition
3166 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3168 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3171 // fold (or x, -1) -> -1, vector edition
3172 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3174 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3178 // fold (or x, undef) -> -1
3179 if (!LegalOperations &&
3180 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3181 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3182 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3184 // fold (or c1, c2) -> c1|c2
3186 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3187 // canonicalize constant to RHS
3189 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3190 // fold (or x, 0) -> x
3191 if (N1C && N1C->isNullValue())
3193 // fold (or x, -1) -> -1
3194 if (N1C && N1C->isAllOnesValue())
3196 // fold (or x, c) -> c iff (x & ~c) == 0
3197 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3200 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3201 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3202 if (BSwap.getNode() != 0)
3204 BSwap = MatchBSwapHWordLow(N, N0, N1);
3205 if (BSwap.getNode() != 0)
3209 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3210 if (ROR.getNode() != 0)
3212 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3213 // iff (c1 & c2) == 0.
3214 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3215 isa<ConstantSDNode>(N0.getOperand(1))) {
3216 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3217 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3218 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3219 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3220 N0.getOperand(0), N1),
3221 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3223 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3224 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3225 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3226 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3228 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3229 LL.getValueType().isInteger()) {
3230 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3231 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3232 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3233 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3234 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3235 LR.getValueType(), LL, RL);
3236 AddToWorkList(ORNode.getNode());
3237 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3239 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3240 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3241 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3242 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3243 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3244 LR.getValueType(), LL, RL);
3245 AddToWorkList(ANDNode.getNode());
3246 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3249 // canonicalize equivalent to ll == rl
3250 if (LL == RR && LR == RL) {
3251 Op1 = ISD::getSetCCSwappedOperands(Op1);
3254 if (LL == RL && LR == RR) {
3255 bool isInteger = LL.getValueType().isInteger();
3256 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3257 if (Result != ISD::SETCC_INVALID &&
3258 (!LegalOperations ||
3259 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3260 TLI.isOperationLegal(ISD::SETCC,
3261 getSetCCResultType(N0.getValueType())))))
3262 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3267 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3268 if (N0.getOpcode() == N1.getOpcode()) {
3269 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3270 if (Tmp.getNode()) return Tmp;
3273 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3274 if (N0.getOpcode() == ISD::AND &&
3275 N1.getOpcode() == ISD::AND &&
3276 N0.getOperand(1).getOpcode() == ISD::Constant &&
3277 N1.getOperand(1).getOpcode() == ISD::Constant &&
3278 // Don't increase # computations.
3279 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3280 // We can only do this xform if we know that bits from X that are set in C2
3281 // but not in C1 are already zero. Likewise for Y.
3282 const APInt &LHSMask =
3283 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3284 const APInt &RHSMask =
3285 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3287 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3288 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3289 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3290 N0.getOperand(0), N1.getOperand(0));
3291 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3292 DAG.getConstant(LHSMask | RHSMask, VT));
3296 // See if this is some rotate idiom.
3297 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3298 return SDValue(Rot, 0);
3300 // Simplify the operands using demanded-bits information.
3301 if (!VT.isVector() &&
3302 SimplifyDemandedBits(SDValue(N, 0)))
3303 return SDValue(N, 0);
3308 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3309 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3310 if (Op.getOpcode() == ISD::AND) {
3311 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3312 Mask = Op.getOperand(1);
3313 Op = Op.getOperand(0);
3319 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3327 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3328 // idioms for rotate, and if the target supports rotation instructions, generate
3330 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3331 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3332 EVT VT = LHS.getValueType();
3333 if (!TLI.isTypeLegal(VT)) return 0;
3335 // The target must have at least one rotate flavor.
3336 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3337 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3338 if (!HasROTL && !HasROTR) return 0;
3340 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3341 SDValue LHSShift; // The shift.
3342 SDValue LHSMask; // AND value if any.
3343 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3344 return 0; // Not part of a rotate.
3346 SDValue RHSShift; // The shift.
3347 SDValue RHSMask; // AND value if any.
3348 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3349 return 0; // Not part of a rotate.
3351 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3352 return 0; // Not shifting the same value.
3354 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3355 return 0; // Shifts must disagree.
3357 // Canonicalize shl to left side in a shl/srl pair.
3358 if (RHSShift.getOpcode() == ISD::SHL) {
3359 std::swap(LHS, RHS);
3360 std::swap(LHSShift, RHSShift);
3361 std::swap(LHSMask , RHSMask );
3364 unsigned OpSizeInBits = VT.getSizeInBits();
3365 SDValue LHSShiftArg = LHSShift.getOperand(0);
3366 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3367 SDValue RHSShiftArg = RHSShift.getOperand(0);
3368 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3370 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3371 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3372 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3373 RHSShiftAmt.getOpcode() == ISD::Constant) {
3374 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3375 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3376 if ((LShVal + RShVal) != OpSizeInBits)
3379 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3380 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3382 // If there is an AND of either shifted operand, apply it to the result.
3383 if (LHSMask.getNode() || RHSMask.getNode()) {
3384 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3386 if (LHSMask.getNode()) {
3387 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3388 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3390 if (RHSMask.getNode()) {
3391 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3392 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3395 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3398 return Rot.getNode();
3401 // If there is a mask here, and we have a variable shift, we can't be sure
3402 // that we're masking out the right stuff.
3403 if (LHSMask.getNode() || RHSMask.getNode())
3406 // If the shift amount is sign/zext/any-extended just peel it off.
3407 SDValue LExtOp0 = LHSShiftAmt;
3408 SDValue RExtOp0 = RHSShiftAmt;
3409 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3410 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3411 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3412 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3413 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3414 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3415 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3416 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3417 LExtOp0 = LHSShiftAmt.getOperand(0);
3418 RExtOp0 = RHSShiftAmt.getOperand(0);
3421 if (RExtOp0.getOpcode() == ISD::SUB && RExtOp0.getOperand(1) == LExtOp0) {
3422 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3424 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3425 // (rotr x, (sub 32, y))
3426 if (ConstantSDNode *SUBC =
3427 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3428 if (SUBC->getAPIntValue() == OpSizeInBits) {
3429 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3430 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3431 } else if (LHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3432 LHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3433 // fold (or (shl (*ext x), (*ext y)),
3434 // (srl (*ext x), (*ext (sub 32, y)))) ->
3435 // (*ext (rotl x, y))
3436 // fold (or (shl (*ext x), (*ext y)),
3437 // (srl (*ext x), (*ext (sub 32, y)))) ->
3438 // (*ext (rotr x, (sub 32, y)))
3439 SDValue LArgExtOp0 = LHSShiftArg.getOperand(0);
3440 EVT LArgVT = LArgExtOp0.getValueType();
3441 bool HasROTRWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTR, LArgVT);
3442 bool HasROTLWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTL, LArgVT);
3443 if (HasROTRWithLArg || HasROTLWithLArg) {
3444 if (LArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3446 DAG.getNode(HasROTLWithLArg ? ISD::ROTL : ISD::ROTR, DL, LArgVT,
3447 LArgExtOp0, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3448 return DAG.getNode(LHSShiftArg.getOpcode(), DL, VT, V).getNode();
3453 } else if (LExtOp0.getOpcode() == ISD::SUB &&
3454 RExtOp0 == LExtOp0.getOperand(1)) {
3455 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3457 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3458 // (rotl x, (sub 32, y))
3459 if (ConstantSDNode *SUBC =
3460 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3461 if (SUBC->getAPIntValue() == OpSizeInBits) {
3462 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3463 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3464 } else if (RHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3465 RHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3466 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3467 // (srl (*ext x), (*ext y))) ->
3468 // (*ext (rotl x, y))
3469 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3470 // (srl (*ext x), (*ext y))) ->
3471 // (*ext (rotr x, (sub 32, y)))
3472 SDValue RArgExtOp0 = RHSShiftArg.getOperand(0);
3473 EVT RArgVT = RArgExtOp0.getValueType();
3474 bool HasROTRWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTR, RArgVT);
3475 bool HasROTLWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTL, RArgVT);
3476 if (HasROTRWithRArg || HasROTLWithRArg) {
3477 if (RArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3479 DAG.getNode(HasROTRWithRArg ? ISD::ROTR : ISD::ROTL, DL, RArgVT,
3480 RArgExtOp0, HasROTR ? RHSShiftAmt : LHSShiftAmt);
3481 return DAG.getNode(RHSShiftArg.getOpcode(), DL, VT, V).getNode();
3491 SDValue DAGCombiner::visitXOR(SDNode *N) {
3492 SDValue N0 = N->getOperand(0);
3493 SDValue N1 = N->getOperand(1);
3494 SDValue LHS, RHS, CC;
3495 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3496 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3497 EVT VT = N0.getValueType();
3500 if (VT.isVector()) {
3501 SDValue FoldedVOp = SimplifyVBinOp(N);
3502 if (FoldedVOp.getNode()) return FoldedVOp;
3504 // fold (xor x, 0) -> x, vector edition
3505 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3507 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3511 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3512 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3513 return DAG.getConstant(0, VT);
3514 // fold (xor x, undef) -> undef
3515 if (N0.getOpcode() == ISD::UNDEF)
3517 if (N1.getOpcode() == ISD::UNDEF)
3519 // fold (xor c1, c2) -> c1^c2
3521 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3522 // canonicalize constant to RHS
3524 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3525 // fold (xor x, 0) -> x
3526 if (N1C && N1C->isNullValue())
3529 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3530 if (RXOR.getNode() != 0)
3533 // fold !(x cc y) -> (x !cc y)
3534 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3535 bool isInt = LHS.getValueType().isInteger();
3536 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3539 if (!LegalOperations ||
3540 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3541 switch (N0.getOpcode()) {
3543 llvm_unreachable("Unhandled SetCC Equivalent!");
3545 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3546 case ISD::SELECT_CC:
3547 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3548 N0.getOperand(3), NotCC);
3553 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3554 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3555 N0.getNode()->hasOneUse() &&
3556 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3557 SDValue V = N0.getOperand(0);
3558 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3559 DAG.getConstant(1, V.getValueType()));
3560 AddToWorkList(V.getNode());
3561 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3564 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3565 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3566 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3567 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3568 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3569 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3570 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3571 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3572 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3573 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3576 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3577 if (N1C && N1C->isAllOnesValue() &&
3578 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3579 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3580 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3581 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3582 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3583 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3584 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3585 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3588 // fold (xor (and x, y), y) -> (and (not x), y)
3589 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3590 N0->getOperand(1) == N1 && isTypeLegal(VT.getScalarType())) {
3591 SDValue X = N0->getOperand(0);
3592 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3593 AddToWorkList(NotX.getNode());
3594 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3596 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3597 if (N1C && N0.getOpcode() == ISD::XOR) {
3598 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3599 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3601 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3602 DAG.getConstant(N1C->getAPIntValue() ^
3603 N00C->getAPIntValue(), VT));
3605 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3606 DAG.getConstant(N1C->getAPIntValue() ^
3607 N01C->getAPIntValue(), VT));
3609 // fold (xor x, x) -> 0
3611 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3613 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3614 if (N0.getOpcode() == N1.getOpcode()) {
3615 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3616 if (Tmp.getNode()) return Tmp;
3619 // Simplify the expression using non-local knowledge.
3620 if (!VT.isVector() &&
3621 SimplifyDemandedBits(SDValue(N, 0)))
3622 return SDValue(N, 0);
3627 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3628 /// the shift amount is a constant.
3629 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3630 SDNode *LHS = N->getOperand(0).getNode();
3631 if (!LHS->hasOneUse()) return SDValue();
3633 // We want to pull some binops through shifts, so that we have (and (shift))
3634 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3635 // thing happens with address calculations, so it's important to canonicalize
3637 bool HighBitSet = false; // Can we transform this if the high bit is set?
3639 switch (LHS->getOpcode()) {
3640 default: return SDValue();
3643 HighBitSet = false; // We can only transform sra if the high bit is clear.
3646 HighBitSet = true; // We can only transform sra if the high bit is set.
3649 if (N->getOpcode() != ISD::SHL)
3650 return SDValue(); // only shl(add) not sr[al](add).
3651 HighBitSet = false; // We can only transform sra if the high bit is clear.
3655 // We require the RHS of the binop to be a constant as well.
3656 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3657 if (!BinOpCst) return SDValue();
3659 // FIXME: disable this unless the input to the binop is a shift by a constant.
3660 // If it is not a shift, it pessimizes some common cases like:
3662 // void foo(int *X, int i) { X[i & 1235] = 1; }
3663 // int bar(int *X, int i) { return X[i & 255]; }
3664 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3665 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3666 BinOpLHSVal->getOpcode() != ISD::SRA &&
3667 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3668 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3671 EVT VT = N->getValueType(0);
3673 // If this is a signed shift right, and the high bit is modified by the
3674 // logical operation, do not perform the transformation. The highBitSet
3675 // boolean indicates the value of the high bit of the constant which would
3676 // cause it to be modified for this operation.
3677 if (N->getOpcode() == ISD::SRA) {
3678 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3679 if (BinOpRHSSignSet != HighBitSet)
3683 // Fold the constants, shifting the binop RHS by the shift amount.
3684 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3686 LHS->getOperand(1), N->getOperand(1));
3688 // Create the new shift.
3689 SDValue NewShift = DAG.getNode(N->getOpcode(),
3690 SDLoc(LHS->getOperand(0)),
3691 VT, LHS->getOperand(0), N->getOperand(1));
3693 // Create the new binop.
3694 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3697 SDValue DAGCombiner::visitSHL(SDNode *N) {
3698 SDValue N0 = N->getOperand(0);
3699 SDValue N1 = N->getOperand(1);
3700 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3701 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3702 EVT VT = N0.getValueType();
3703 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3705 // fold (shl c1, c2) -> c1<<c2
3707 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3708 // fold (shl 0, x) -> 0
3709 if (N0C && N0C->isNullValue())
3711 // fold (shl x, c >= size(x)) -> undef
3712 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3713 return DAG.getUNDEF(VT);
3714 // fold (shl x, 0) -> x
3715 if (N1C && N1C->isNullValue())
3717 // fold (shl undef, x) -> 0
3718 if (N0.getOpcode() == ISD::UNDEF)
3719 return DAG.getConstant(0, VT);
3720 // if (shl x, c) is known to be zero, return 0
3721 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3722 APInt::getAllOnesValue(OpSizeInBits)))
3723 return DAG.getConstant(0, VT);
3724 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3725 if (N1.getOpcode() == ISD::TRUNCATE &&
3726 N1.getOperand(0).getOpcode() == ISD::AND &&
3727 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3728 SDValue N101 = N1.getOperand(0).getOperand(1);
3729 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3730 EVT TruncVT = N1.getValueType();
3731 SDValue N100 = N1.getOperand(0).getOperand(0);
3732 APInt TruncC = N101C->getAPIntValue();
3733 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3734 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3735 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3736 DAG.getNode(ISD::TRUNCATE,
3739 DAG.getConstant(TruncC, TruncVT)));
3743 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3744 return SDValue(N, 0);
3746 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3747 if (N1C && N0.getOpcode() == ISD::SHL &&
3748 N0.getOperand(1).getOpcode() == ISD::Constant) {
3749 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3750 uint64_t c2 = N1C->getZExtValue();
3751 if (c1 + c2 >= OpSizeInBits)
3752 return DAG.getConstant(0, VT);
3753 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3754 DAG.getConstant(c1 + c2, N1.getValueType()));
3757 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3758 // For this to be valid, the second form must not preserve any of the bits
3759 // that are shifted out by the inner shift in the first form. This means
3760 // the outer shift size must be >= the number of bits added by the ext.
3761 // As a corollary, we don't care what kind of ext it is.
3762 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3763 N0.getOpcode() == ISD::ANY_EXTEND ||
3764 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3765 N0.getOperand(0).getOpcode() == ISD::SHL &&
3766 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3768 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3769 uint64_t c2 = N1C->getZExtValue();
3770 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3771 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3772 if (c2 >= OpSizeInBits - InnerShiftSize) {
3773 if (c1 + c2 >= OpSizeInBits)
3774 return DAG.getConstant(0, VT);
3775 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3776 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3777 N0.getOperand(0)->getOperand(0)),
3778 DAG.getConstant(c1 + c2, N1.getValueType()));
3782 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3783 // Only fold this if the inner zext has no other uses to avoid increasing
3784 // the total number of instructions.
3785 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3786 N0.getOperand(0).getOpcode() == ISD::SRL &&
3787 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3789 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3790 if (c1 < VT.getSizeInBits()) {
3791 uint64_t c2 = N1C->getZExtValue();
3793 SDValue NewOp0 = N0.getOperand(0);
3794 EVT CountVT = NewOp0.getOperand(1).getValueType();
3795 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3796 NewOp0, DAG.getConstant(c2, CountVT));
3797 AddToWorkList(NewSHL.getNode());
3798 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3803 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3804 // (and (srl x, (sub c1, c2), MASK)
3805 // Only fold this if the inner shift has no other uses -- if it does, folding
3806 // this will increase the total number of instructions.
3807 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3808 N0.getOperand(1).getOpcode() == ISD::Constant) {
3809 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3810 if (c1 < VT.getSizeInBits()) {
3811 uint64_t c2 = N1C->getZExtValue();
3812 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3813 VT.getSizeInBits() - c1);
3816 Mask = Mask.shl(c2-c1);
3817 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3818 DAG.getConstant(c2-c1, N1.getValueType()));
3820 Mask = Mask.lshr(c1-c2);
3821 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3822 DAG.getConstant(c1-c2, N1.getValueType()));
3824 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3825 DAG.getConstant(Mask, VT));
3828 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3829 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3830 SDValue HiBitsMask =
3831 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3832 VT.getSizeInBits() -
3833 N1C->getZExtValue()),
3835 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3840 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3841 if (NewSHL.getNode())
3848 SDValue DAGCombiner::visitSRA(SDNode *N) {
3849 SDValue N0 = N->getOperand(0);
3850 SDValue N1 = N->getOperand(1);
3851 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3852 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3853 EVT VT = N0.getValueType();
3854 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3856 // fold (sra c1, c2) -> (sra c1, c2)
3858 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3859 // fold (sra 0, x) -> 0
3860 if (N0C && N0C->isNullValue())
3862 // fold (sra -1, x) -> -1
3863 if (N0C && N0C->isAllOnesValue())
3865 // fold (sra x, (setge c, size(x))) -> undef
3866 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3867 return DAG.getUNDEF(VT);
3868 // fold (sra x, 0) -> x
3869 if (N1C && N1C->isNullValue())
3871 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3873 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3874 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3875 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3877 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3878 ExtVT, VT.getVectorNumElements());
3879 if ((!LegalOperations ||
3880 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3881 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3882 N0.getOperand(0), DAG.getValueType(ExtVT));
3885 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3886 if (N1C && N0.getOpcode() == ISD::SRA) {
3887 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3888 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3889 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3890 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3891 DAG.getConstant(Sum, N1C->getValueType(0)));
3895 // fold (sra (shl X, m), (sub result_size, n))
3896 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3897 // result_size - n != m.
3898 // If truncate is free for the target sext(shl) is likely to result in better
3900 if (N0.getOpcode() == ISD::SHL) {
3901 // Get the two constanst of the shifts, CN0 = m, CN = n.
3902 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3904 // Determine what the truncate's result bitsize and type would be.
3906 EVT::getIntegerVT(*DAG.getContext(),
3907 OpSizeInBits - N1C->getZExtValue());
3908 // Determine the residual right-shift amount.
3909 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3911 // If the shift is not a no-op (in which case this should be just a sign
3912 // extend already), the truncated to type is legal, sign_extend is legal
3913 // on that type, and the truncate to that type is both legal and free,
3914 // perform the transform.
3915 if ((ShiftAmt > 0) &&
3916 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3917 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3918 TLI.isTruncateFree(VT, TruncVT)) {
3920 SDValue Amt = DAG.getConstant(ShiftAmt,
3921 getShiftAmountTy(N0.getOperand(0).getValueType()));
3922 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3923 N0.getOperand(0), Amt);
3924 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3926 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3927 N->getValueType(0), Trunc);
3932 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3933 if (N1.getOpcode() == ISD::TRUNCATE &&
3934 N1.getOperand(0).getOpcode() == ISD::AND &&
3935 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3936 SDValue N101 = N1.getOperand(0).getOperand(1);
3937 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3938 EVT TruncVT = N1.getValueType();
3939 SDValue N100 = N1.getOperand(0).getOperand(0);
3940 APInt TruncC = N101C->getAPIntValue();
3941 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3942 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3943 DAG.getNode(ISD::AND, SDLoc(N),
3945 DAG.getNode(ISD::TRUNCATE,
3948 DAG.getConstant(TruncC, TruncVT)));
3952 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3953 // if c1 is equal to the number of bits the trunc removes
3954 if (N0.getOpcode() == ISD::TRUNCATE &&
3955 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3956 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3957 N0.getOperand(0).hasOneUse() &&
3958 N0.getOperand(0).getOperand(1).hasOneUse() &&
3959 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3960 EVT LargeVT = N0.getOperand(0).getValueType();
3961 ConstantSDNode *LargeShiftAmt =
3962 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3964 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3965 LargeShiftAmt->getZExtValue()) {
3967 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3968 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3969 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3970 N0.getOperand(0).getOperand(0), Amt);
3971 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3975 // Simplify, based on bits shifted out of the LHS.
3976 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3977 return SDValue(N, 0);
3980 // If the sign bit is known to be zero, switch this to a SRL.
3981 if (DAG.SignBitIsZero(N0))
3982 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3985 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3986 if (NewSRA.getNode())
3993 SDValue DAGCombiner::visitSRL(SDNode *N) {
3994 SDValue N0 = N->getOperand(0);
3995 SDValue N1 = N->getOperand(1);
3996 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3997 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3998 EVT VT = N0.getValueType();
3999 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4001 // fold (srl c1, c2) -> c1 >>u c2
4003 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4004 // fold (srl 0, x) -> 0
4005 if (N0C && N0C->isNullValue())
4007 // fold (srl x, c >= size(x)) -> undef
4008 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4009 return DAG.getUNDEF(VT);
4010 // fold (srl x, 0) -> x
4011 if (N1C && N1C->isNullValue())
4013 // if (srl x, c) is known to be zero, return 0
4014 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4015 APInt::getAllOnesValue(OpSizeInBits)))
4016 return DAG.getConstant(0, VT);
4018 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4019 if (N1C && N0.getOpcode() == ISD::SRL &&
4020 N0.getOperand(1).getOpcode() == ISD::Constant) {
4021 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4022 uint64_t c2 = N1C->getZExtValue();
4023 if (c1 + c2 >= OpSizeInBits)
4024 return DAG.getConstant(0, VT);
4025 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4026 DAG.getConstant(c1 + c2, N1.getValueType()));
4029 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4030 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4031 N0.getOperand(0).getOpcode() == ISD::SRL &&
4032 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4034 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4035 uint64_t c2 = N1C->getZExtValue();
4036 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4037 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4038 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4039 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4040 if (c1 + OpSizeInBits == InnerShiftSize) {
4041 if (c1 + c2 >= InnerShiftSize)
4042 return DAG.getConstant(0, VT);
4043 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4044 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4045 N0.getOperand(0)->getOperand(0),
4046 DAG.getConstant(c1 + c2, ShiftCountVT)));
4050 // fold (srl (shl x, c), c) -> (and x, cst2)
4051 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4052 N0.getValueSizeInBits() <= 64) {
4053 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4054 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4055 DAG.getConstant(~0ULL >> ShAmt, VT));
4058 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4059 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4060 // Shifting in all undef bits?
4061 EVT SmallVT = N0.getOperand(0).getValueType();
4062 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4063 return DAG.getUNDEF(VT);
4065 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4066 uint64_t ShiftAmt = N1C->getZExtValue();
4067 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4069 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4070 AddToWorkList(SmallShift.getNode());
4071 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4072 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4073 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4074 DAG.getConstant(Mask, VT));
4078 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4079 // bit, which is unmodified by sra.
4080 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4081 if (N0.getOpcode() == ISD::SRA)
4082 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4085 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4086 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4087 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4088 APInt KnownZero, KnownOne;
4089 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4091 // If any of the input bits are KnownOne, then the input couldn't be all
4092 // zeros, thus the result of the srl will always be zero.
4093 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4095 // If all of the bits input the to ctlz node are known to be zero, then
4096 // the result of the ctlz is "32" and the result of the shift is one.
4097 APInt UnknownBits = ~KnownZero;
4098 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4100 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4101 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4102 // Okay, we know that only that the single bit specified by UnknownBits
4103 // could be set on input to the CTLZ node. If this bit is set, the SRL
4104 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4105 // to an SRL/XOR pair, which is likely to simplify more.
4106 unsigned ShAmt = UnknownBits.countTrailingZeros();
4107 SDValue Op = N0.getOperand(0);
4110 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4111 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4112 AddToWorkList(Op.getNode());
4115 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4116 Op, DAG.getConstant(1, VT));
4120 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4121 if (N1.getOpcode() == ISD::TRUNCATE &&
4122 N1.getOperand(0).getOpcode() == ISD::AND &&
4123 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4124 SDValue N101 = N1.getOperand(0).getOperand(1);
4125 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4126 EVT TruncVT = N1.getValueType();
4127 SDValue N100 = N1.getOperand(0).getOperand(0);
4128 APInt TruncC = N101C->getAPIntValue();
4129 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4130 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4131 DAG.getNode(ISD::AND, SDLoc(N),
4133 DAG.getNode(ISD::TRUNCATE,
4136 DAG.getConstant(TruncC, TruncVT)));
4140 // fold operands of srl based on knowledge that the low bits are not
4142 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4143 return SDValue(N, 0);
4146 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4147 if (NewSRL.getNode())
4151 // Attempt to convert a srl of a load into a narrower zero-extending load.
4152 SDValue NarrowLoad = ReduceLoadWidth(N);
4153 if (NarrowLoad.getNode())
4156 // Here is a common situation. We want to optimize:
4159 // %b = and i32 %a, 2
4160 // %c = srl i32 %b, 1
4161 // brcond i32 %c ...
4167 // %c = setcc eq %b, 0
4170 // However when after the source operand of SRL is optimized into AND, the SRL
4171 // itself may not be optimized further. Look for it and add the BRCOND into
4173 if (N->hasOneUse()) {
4174 SDNode *Use = *N->use_begin();
4175 if (Use->getOpcode() == ISD::BRCOND)
4177 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4178 // Also look pass the truncate.
4179 Use = *Use->use_begin();
4180 if (Use->getOpcode() == ISD::BRCOND)
4188 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4189 SDValue N0 = N->getOperand(0);
4190 EVT VT = N->getValueType(0);
4192 // fold (ctlz c1) -> c2
4193 if (isa<ConstantSDNode>(N0))
4194 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4198 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4199 SDValue N0 = N->getOperand(0);
4200 EVT VT = N->getValueType(0);
4202 // fold (ctlz_zero_undef c1) -> c2
4203 if (isa<ConstantSDNode>(N0))
4204 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4208 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4209 SDValue N0 = N->getOperand(0);
4210 EVT VT = N->getValueType(0);
4212 // fold (cttz c1) -> c2
4213 if (isa<ConstantSDNode>(N0))
4214 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4218 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4219 SDValue N0 = N->getOperand(0);
4220 EVT VT = N->getValueType(0);
4222 // fold (cttz_zero_undef c1) -> c2
4223 if (isa<ConstantSDNode>(N0))
4224 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4228 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4229 SDValue N0 = N->getOperand(0);
4230 EVT VT = N->getValueType(0);
4232 // fold (ctpop c1) -> c2
4233 if (isa<ConstantSDNode>(N0))
4234 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4238 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4239 SDValue N0 = N->getOperand(0);
4240 SDValue N1 = N->getOperand(1);
4241 SDValue N2 = N->getOperand(2);
4242 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4243 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4244 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4245 EVT VT = N->getValueType(0);
4246 EVT VT0 = N0.getValueType();
4248 // fold (select C, X, X) -> X
4251 // fold (select true, X, Y) -> X
4252 if (N0C && !N0C->isNullValue())
4254 // fold (select false, X, Y) -> Y
4255 if (N0C && N0C->isNullValue())
4257 // fold (select C, 1, X) -> (or C, X)
4258 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4259 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4260 // fold (select C, 0, 1) -> (xor C, 1)
4261 if (VT.isInteger() &&
4264 TLI.getBooleanContents(false) ==
4265 TargetLowering::ZeroOrOneBooleanContent)) &&
4266 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4269 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4270 N0, DAG.getConstant(1, VT0));
4271 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4272 N0, DAG.getConstant(1, VT0));
4273 AddToWorkList(XORNode.getNode());
4275 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4276 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4278 // fold (select C, 0, X) -> (and (not C), X)
4279 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4280 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4281 AddToWorkList(NOTNode.getNode());
4282 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4284 // fold (select C, X, 1) -> (or (not C), X)
4285 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4286 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4287 AddToWorkList(NOTNode.getNode());
4288 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4290 // fold (select C, X, 0) -> (and C, X)
4291 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4292 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4293 // fold (select X, X, Y) -> (or X, Y)
4294 // fold (select X, 1, Y) -> (or X, Y)
4295 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4296 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4297 // fold (select X, Y, X) -> (and X, Y)
4298 // fold (select X, Y, 0) -> (and X, Y)
4299 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4300 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4302 // If we can fold this based on the true/false value, do so.
4303 if (SimplifySelectOps(N, N1, N2))
4304 return SDValue(N, 0); // Don't revisit N.
4306 // fold selects based on a setcc into other things, such as min/max/abs
4307 if (N0.getOpcode() == ISD::SETCC) {
4309 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4310 // having to say they don't support SELECT_CC on every type the DAG knows
4311 // about, since there is no way to mark an opcode illegal at all value types
4312 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4313 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4314 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4315 N0.getOperand(0), N0.getOperand(1),
4316 N1, N2, N0.getOperand(2));
4317 return SimplifySelect(SDLoc(N), N0, N1, N2);
4323 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4324 SDValue N0 = N->getOperand(0);
4325 SDValue N1 = N->getOperand(1);
4326 SDValue N2 = N->getOperand(2);
4329 // Canonicalize integer abs.
4330 // vselect (setg[te] X, 0), X, -X ->
4331 // vselect (setgt X, -1), X, -X ->
4332 // vselect (setl[te] X, 0), -X, X ->
4333 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4334 if (N0.getOpcode() == ISD::SETCC) {
4335 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4336 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4338 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4340 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4341 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4342 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4343 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4344 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4345 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4346 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4349 EVT VT = LHS.getValueType();
4350 SDValue Shift = DAG.getNode(
4351 ISD::SRA, DL, VT, LHS,
4352 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4353 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4354 AddToWorkList(Shift.getNode());
4355 AddToWorkList(Add.getNode());
4356 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4363 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4364 SDValue N0 = N->getOperand(0);
4365 SDValue N1 = N->getOperand(1);
4366 SDValue N2 = N->getOperand(2);
4367 SDValue N3 = N->getOperand(3);
4368 SDValue N4 = N->getOperand(4);
4369 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4371 // fold select_cc lhs, rhs, x, x, cc -> x
4375 // Determine if the condition we're dealing with is constant
4376 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4377 N0, N1, CC, SDLoc(N), false);
4378 if (SCC.getNode()) {
4379 AddToWorkList(SCC.getNode());
4381 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4382 if (!SCCC->isNullValue())
4383 return N2; // cond always true -> true val
4385 return N3; // cond always false -> false val
4388 // Fold to a simpler select_cc
4389 if (SCC.getOpcode() == ISD::SETCC)
4390 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4391 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4395 // If we can fold this based on the true/false value, do so.
4396 if (SimplifySelectOps(N, N2, N3))
4397 return SDValue(N, 0); // Don't revisit N.
4399 // fold select_cc into other things, such as min/max/abs
4400 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4403 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4404 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4405 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4409 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4410 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4411 // transformation. Returns true if extension are possible and the above
4412 // mentioned transformation is profitable.
4413 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4415 SmallVectorImpl<SDNode *> &ExtendNodes,
4416 const TargetLowering &TLI) {
4417 bool HasCopyToRegUses = false;
4418 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4419 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4420 UE = N0.getNode()->use_end();
4425 if (UI.getUse().getResNo() != N0.getResNo())
4427 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4428 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4429 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4430 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4431 // Sign bits will be lost after a zext.
4434 for (unsigned i = 0; i != 2; ++i) {
4435 SDValue UseOp = User->getOperand(i);
4438 if (!isa<ConstantSDNode>(UseOp))
4443 ExtendNodes.push_back(User);
4446 // If truncates aren't free and there are users we can't
4447 // extend, it isn't worthwhile.
4450 // Remember if this value is live-out.
4451 if (User->getOpcode() == ISD::CopyToReg)
4452 HasCopyToRegUses = true;
4455 if (HasCopyToRegUses) {
4456 bool BothLiveOut = false;
4457 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4459 SDUse &Use = UI.getUse();
4460 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4466 // Both unextended and extended values are live out. There had better be
4467 // a good reason for the transformation.
4468 return ExtendNodes.size();
4473 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4474 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4475 ISD::NodeType ExtType) {
4476 // Extend SetCC uses if necessary.
4477 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4478 SDNode *SetCC = SetCCs[i];
4479 SmallVector<SDValue, 4> Ops;
4481 for (unsigned j = 0; j != 2; ++j) {
4482 SDValue SOp = SetCC->getOperand(j);
4484 Ops.push_back(ExtLoad);
4486 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4489 Ops.push_back(SetCC->getOperand(2));
4490 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4491 &Ops[0], Ops.size()));
4495 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4496 SDValue N0 = N->getOperand(0);
4497 EVT VT = N->getValueType(0);
4499 // fold (sext c1) -> c1
4500 if (isa<ConstantSDNode>(N0))
4501 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4503 // fold (sext (sext x)) -> (sext x)
4504 // fold (sext (aext x)) -> (sext x)
4505 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4506 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4509 if (N0.getOpcode() == ISD::TRUNCATE) {
4510 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4511 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4512 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4513 if (NarrowLoad.getNode()) {
4514 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4515 if (NarrowLoad.getNode() != N0.getNode()) {
4516 CombineTo(N0.getNode(), NarrowLoad);
4517 // CombineTo deleted the truncate, if needed, but not what's under it.
4520 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4523 // See if the value being truncated is already sign extended. If so, just
4524 // eliminate the trunc/sext pair.
4525 SDValue Op = N0.getOperand(0);
4526 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4527 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4528 unsigned DestBits = VT.getScalarType().getSizeInBits();
4529 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4531 if (OpBits == DestBits) {
4532 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4533 // bits, it is already ready.
4534 if (NumSignBits > DestBits-MidBits)
4536 } else if (OpBits < DestBits) {
4537 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4538 // bits, just sext from i32.
4539 if (NumSignBits > OpBits-MidBits)
4540 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4542 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4543 // bits, just truncate to i32.
4544 if (NumSignBits > OpBits-MidBits)
4545 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4548 // fold (sext (truncate x)) -> (sextinreg x).
4549 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4550 N0.getValueType())) {
4551 if (OpBits < DestBits)
4552 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4553 else if (OpBits > DestBits)
4554 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4555 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4556 DAG.getValueType(N0.getValueType()));
4560 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4561 // None of the supported targets knows how to perform load and sign extend
4562 // on vectors in one instruction. We only perform this transformation on
4564 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4565 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4566 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4567 bool DoXform = true;
4568 SmallVector<SDNode*, 4> SetCCs;
4569 if (!N0.hasOneUse())
4570 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4572 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4573 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4575 LN0->getBasePtr(), LN0->getPointerInfo(),
4577 LN0->isVolatile(), LN0->isNonTemporal(),
4578 LN0->getAlignment());
4579 CombineTo(N, ExtLoad);
4580 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4581 N0.getValueType(), ExtLoad);
4582 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4583 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4585 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4589 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4590 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4591 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4592 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4593 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4594 EVT MemVT = LN0->getMemoryVT();
4595 if ((!LegalOperations && !LN0->isVolatile()) ||
4596 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4597 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4599 LN0->getBasePtr(), LN0->getPointerInfo(),
4601 LN0->isVolatile(), LN0->isNonTemporal(),
4602 LN0->getAlignment());
4603 CombineTo(N, ExtLoad);
4604 CombineTo(N0.getNode(),
4605 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4606 N0.getValueType(), ExtLoad),
4607 ExtLoad.getValue(1));
4608 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4612 // fold (sext (and/or/xor (load x), cst)) ->
4613 // (and/or/xor (sextload x), (sext cst))
4614 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4615 N0.getOpcode() == ISD::XOR) &&
4616 isa<LoadSDNode>(N0.getOperand(0)) &&
4617 N0.getOperand(1).getOpcode() == ISD::Constant &&
4618 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4619 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4620 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4621 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4622 bool DoXform = true;
4623 SmallVector<SDNode*, 4> SetCCs;
4624 if (!N0.hasOneUse())
4625 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4628 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4629 LN0->getChain(), LN0->getBasePtr(),
4630 LN0->getPointerInfo(),
4633 LN0->isNonTemporal(),
4634 LN0->getAlignment());
4635 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4636 Mask = Mask.sext(VT.getSizeInBits());
4637 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4638 ExtLoad, DAG.getConstant(Mask, VT));
4639 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4640 SDLoc(N0.getOperand(0)),
4641 N0.getOperand(0).getValueType(), ExtLoad);
4643 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4644 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4646 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4651 if (N0.getOpcode() == ISD::SETCC) {
4652 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4653 // Only do this before legalize for now.
4654 if (VT.isVector() && !LegalOperations &&
4655 TLI.getBooleanContents(true) ==
4656 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4657 EVT N0VT = N0.getOperand(0).getValueType();
4658 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4659 // of the same size as the compared operands. Only optimize sext(setcc())
4660 // if this is the case.
4661 EVT SVT = getSetCCResultType(N0VT);
4663 // We know that the # elements of the results is the same as the
4664 // # elements of the compare (and the # elements of the compare result
4665 // for that matter). Check to see that they are the same size. If so,
4666 // we know that the element size of the sext'd result matches the
4667 // element size of the compare operands.
4668 if (VT.getSizeInBits() == SVT.getSizeInBits())
4669 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4671 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4673 // If the desired elements are smaller or larger than the source
4674 // elements we can use a matching integer vector type and then
4675 // truncate/sign extend
4676 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4677 if (SVT == MatchingVectorType) {
4678 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4679 N0.getOperand(0), N0.getOperand(1),
4680 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4681 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4685 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4686 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4688 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4690 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4691 NegOne, DAG.getConstant(0, VT),
4692 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4693 if (SCC.getNode()) return SCC;
4694 if (!VT.isVector() &&
4695 (!LegalOperations ||
4696 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4697 return DAG.getSelect(SDLoc(N), VT,
4698 DAG.getSetCC(SDLoc(N),
4699 getSetCCResultType(VT),
4700 N0.getOperand(0), N0.getOperand(1),
4701 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4702 NegOne, DAG.getConstant(0, VT));
4706 // fold (sext x) -> (zext x) if the sign bit is known zero.
4707 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4708 DAG.SignBitIsZero(N0))
4709 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4714 // isTruncateOf - If N is a truncate of some other value, return true, record
4715 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4716 // This function computes KnownZero to avoid a duplicated call to
4717 // ComputeMaskedBits in the caller.
4718 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4721 if (N->getOpcode() == ISD::TRUNCATE) {
4722 Op = N->getOperand(0);
4723 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4727 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4728 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4731 SDValue Op0 = N->getOperand(0);
4732 SDValue Op1 = N->getOperand(1);
4733 assert(Op0.getValueType() == Op1.getValueType());
4735 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4736 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4737 if (COp0 && COp0->isNullValue())
4739 else if (COp1 && COp1->isNullValue())
4744 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4746 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4752 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4753 SDValue N0 = N->getOperand(0);
4754 EVT VT = N->getValueType(0);
4756 // fold (zext c1) -> c1
4757 if (isa<ConstantSDNode>(N0))
4758 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4759 // fold (zext (zext x)) -> (zext x)
4760 // fold (zext (aext x)) -> (zext x)
4761 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4762 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4765 // fold (zext (truncate x)) -> (zext x) or
4766 // (zext (truncate x)) -> (truncate x)
4767 // This is valid when the truncated bits of x are already zero.
4768 // FIXME: We should extend this to work for vectors too.
4771 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4772 APInt TruncatedBits =
4773 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4774 APInt(Op.getValueSizeInBits(), 0) :
4775 APInt::getBitsSet(Op.getValueSizeInBits(),
4776 N0.getValueSizeInBits(),
4777 std::min(Op.getValueSizeInBits(),
4778 VT.getSizeInBits()));
4779 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4780 if (VT.bitsGT(Op.getValueType()))
4781 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4782 if (VT.bitsLT(Op.getValueType()))
4783 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4789 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4790 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4791 if (N0.getOpcode() == ISD::TRUNCATE) {
4792 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4793 if (NarrowLoad.getNode()) {
4794 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4795 if (NarrowLoad.getNode() != N0.getNode()) {
4796 CombineTo(N0.getNode(), NarrowLoad);
4797 // CombineTo deleted the truncate, if needed, but not what's under it.
4800 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4804 // fold (zext (truncate x)) -> (and x, mask)
4805 if (N0.getOpcode() == ISD::TRUNCATE &&
4806 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4808 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4809 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4810 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4811 if (NarrowLoad.getNode()) {
4812 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4813 if (NarrowLoad.getNode() != N0.getNode()) {
4814 CombineTo(N0.getNode(), NarrowLoad);
4815 // CombineTo deleted the truncate, if needed, but not what's under it.
4818 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4821 SDValue Op = N0.getOperand(0);
4822 if (Op.getValueType().bitsLT(VT)) {
4823 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4824 AddToWorkList(Op.getNode());
4825 } else if (Op.getValueType().bitsGT(VT)) {
4826 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4827 AddToWorkList(Op.getNode());
4829 return DAG.getZeroExtendInReg(Op, SDLoc(N),
4830 N0.getValueType().getScalarType());
4833 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4834 // if either of the casts is not free.
4835 if (N0.getOpcode() == ISD::AND &&
4836 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4837 N0.getOperand(1).getOpcode() == ISD::Constant &&
4838 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4839 N0.getValueType()) ||
4840 !TLI.isZExtFree(N0.getValueType(), VT))) {
4841 SDValue X = N0.getOperand(0).getOperand(0);
4842 if (X.getValueType().bitsLT(VT)) {
4843 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4844 } else if (X.getValueType().bitsGT(VT)) {
4845 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4847 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4848 Mask = Mask.zext(VT.getSizeInBits());
4849 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4850 X, DAG.getConstant(Mask, VT));
4853 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4854 // None of the supported targets knows how to perform load and vector_zext
4855 // on vectors in one instruction. We only perform this transformation on
4857 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4858 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4859 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4860 bool DoXform = true;
4861 SmallVector<SDNode*, 4> SetCCs;
4862 if (!N0.hasOneUse())
4863 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4865 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4866 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4868 LN0->getBasePtr(), LN0->getPointerInfo(),
4870 LN0->isVolatile(), LN0->isNonTemporal(),
4871 LN0->getAlignment());
4872 CombineTo(N, ExtLoad);
4873 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4874 N0.getValueType(), ExtLoad);
4875 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4877 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4879 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4883 // fold (zext (and/or/xor (load x), cst)) ->
4884 // (and/or/xor (zextload x), (zext cst))
4885 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4886 N0.getOpcode() == ISD::XOR) &&
4887 isa<LoadSDNode>(N0.getOperand(0)) &&
4888 N0.getOperand(1).getOpcode() == ISD::Constant &&
4889 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4890 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4891 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4892 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4893 bool DoXform = true;
4894 SmallVector<SDNode*, 4> SetCCs;
4895 if (!N0.hasOneUse())
4896 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4899 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4900 LN0->getChain(), LN0->getBasePtr(),
4901 LN0->getPointerInfo(),
4904 LN0->isNonTemporal(),
4905 LN0->getAlignment());
4906 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4907 Mask = Mask.zext(VT.getSizeInBits());
4908 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4909 ExtLoad, DAG.getConstant(Mask, VT));
4910 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4911 SDLoc(N0.getOperand(0)),
4912 N0.getOperand(0).getValueType(), ExtLoad);
4914 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4915 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4917 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4922 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4923 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4924 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4925 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4926 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4927 EVT MemVT = LN0->getMemoryVT();
4928 if ((!LegalOperations && !LN0->isVolatile()) ||
4929 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4930 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4932 LN0->getBasePtr(), LN0->getPointerInfo(),
4934 LN0->isVolatile(), LN0->isNonTemporal(),
4935 LN0->getAlignment());
4936 CombineTo(N, ExtLoad);
4937 CombineTo(N0.getNode(),
4938 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4940 ExtLoad.getValue(1));
4941 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4945 if (N0.getOpcode() == ISD::SETCC) {
4946 if (!LegalOperations && VT.isVector()) {
4947 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4948 // Only do this before legalize for now.
4949 EVT N0VT = N0.getOperand(0).getValueType();
4950 EVT EltVT = VT.getVectorElementType();
4951 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4952 DAG.getConstant(1, EltVT));
4953 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4954 // We know that the # elements of the results is the same as the
4955 // # elements of the compare (and the # elements of the compare result
4956 // for that matter). Check to see that they are the same size. If so,
4957 // we know that the element size of the sext'd result matches the
4958 // element size of the compare operands.
4959 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4960 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4962 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4963 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4964 &OneOps[0], OneOps.size()));
4966 // If the desired elements are smaller or larger than the source
4967 // elements we can use a matching integer vector type and then
4968 // truncate/sign extend
4969 EVT MatchingElementType =
4970 EVT::getIntegerVT(*DAG.getContext(),
4971 N0VT.getScalarType().getSizeInBits());
4972 EVT MatchingVectorType =
4973 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4974 N0VT.getVectorNumElements());
4976 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4978 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4979 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4980 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4981 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4982 &OneOps[0], OneOps.size()));
4985 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4987 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4988 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4989 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4990 if (SCC.getNode()) return SCC;
4993 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4994 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4995 isa<ConstantSDNode>(N0.getOperand(1)) &&
4996 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4998 SDValue ShAmt = N0.getOperand(1);
4999 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5000 if (N0.getOpcode() == ISD::SHL) {
5001 SDValue InnerZExt = N0.getOperand(0);
5002 // If the original shl may be shifting out bits, do not perform this
5004 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5005 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5006 if (ShAmtVal > KnownZeroBits)
5012 // Ensure that the shift amount is wide enough for the shifted value.
5013 if (VT.getSizeInBits() >= 256)
5014 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5016 return DAG.getNode(N0.getOpcode(), DL, VT,
5017 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5024 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5025 SDValue N0 = N->getOperand(0);
5026 EVT VT = N->getValueType(0);
5028 // fold (aext c1) -> c1
5029 if (isa<ConstantSDNode>(N0))
5030 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5031 // fold (aext (aext x)) -> (aext x)
5032 // fold (aext (zext x)) -> (zext x)
5033 // fold (aext (sext x)) -> (sext x)
5034 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5035 N0.getOpcode() == ISD::ZERO_EXTEND ||
5036 N0.getOpcode() == ISD::SIGN_EXTEND)
5037 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5039 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5040 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5041 if (N0.getOpcode() == ISD::TRUNCATE) {
5042 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5043 if (NarrowLoad.getNode()) {
5044 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5045 if (NarrowLoad.getNode() != N0.getNode()) {
5046 CombineTo(N0.getNode(), NarrowLoad);
5047 // CombineTo deleted the truncate, if needed, but not what's under it.
5050 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5054 // fold (aext (truncate x))
5055 if (N0.getOpcode() == ISD::TRUNCATE) {
5056 SDValue TruncOp = N0.getOperand(0);
5057 if (TruncOp.getValueType() == VT)
5058 return TruncOp; // x iff x size == zext size.
5059 if (TruncOp.getValueType().bitsGT(VT))
5060 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5061 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5064 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5065 // if the trunc is not free.
5066 if (N0.getOpcode() == ISD::AND &&
5067 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5068 N0.getOperand(1).getOpcode() == ISD::Constant &&
5069 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5070 N0.getValueType())) {
5071 SDValue X = N0.getOperand(0).getOperand(0);
5072 if (X.getValueType().bitsLT(VT)) {
5073 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5074 } else if (X.getValueType().bitsGT(VT)) {
5075 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5077 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5078 Mask = Mask.zext(VT.getSizeInBits());
5079 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5080 X, DAG.getConstant(Mask, VT));
5083 // fold (aext (load x)) -> (aext (truncate (extload x)))
5084 // None of the supported targets knows how to perform load and any_ext
5085 // on vectors in one instruction. We only perform this transformation on
5087 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5088 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5089 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5090 bool DoXform = true;
5091 SmallVector<SDNode*, 4> SetCCs;
5092 if (!N0.hasOneUse())
5093 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5095 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5096 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5098 LN0->getBasePtr(), LN0->getPointerInfo(),
5100 LN0->isVolatile(), LN0->isNonTemporal(),
5101 LN0->getAlignment());
5102 CombineTo(N, ExtLoad);
5103 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5104 N0.getValueType(), ExtLoad);
5105 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5106 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5108 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5112 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5113 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5114 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5115 if (N0.getOpcode() == ISD::LOAD &&
5116 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5118 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5119 EVT MemVT = LN0->getMemoryVT();
5120 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5121 VT, LN0->getChain(), LN0->getBasePtr(),
5122 LN0->getPointerInfo(), MemVT,
5123 LN0->isVolatile(), LN0->isNonTemporal(),
5124 LN0->getAlignment());
5125 CombineTo(N, ExtLoad);
5126 CombineTo(N0.getNode(),
5127 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5128 N0.getValueType(), ExtLoad),
5129 ExtLoad.getValue(1));
5130 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5133 if (N0.getOpcode() == ISD::SETCC) {
5134 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5135 // Only do this before legalize for now.
5136 if (VT.isVector() && !LegalOperations) {
5137 EVT N0VT = N0.getOperand(0).getValueType();
5138 // We know that the # elements of the results is the same as the
5139 // # elements of the compare (and the # elements of the compare result
5140 // for that matter). Check to see that they are the same size. If so,
5141 // we know that the element size of the sext'd result matches the
5142 // element size of the compare operands.
5143 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5144 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5146 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5147 // If the desired elements are smaller or larger than the source
5148 // elements we can use a matching integer vector type and then
5149 // truncate/sign extend
5151 EVT MatchingElementType =
5152 EVT::getIntegerVT(*DAG.getContext(),
5153 N0VT.getScalarType().getSizeInBits());
5154 EVT MatchingVectorType =
5155 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5156 N0VT.getVectorNumElements());
5158 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5160 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5161 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5165 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5167 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5168 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5169 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5177 /// GetDemandedBits - See if the specified operand can be simplified with the
5178 /// knowledge that only the bits specified by Mask are used. If so, return the
5179 /// simpler operand, otherwise return a null SDValue.
5180 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5181 switch (V.getOpcode()) {
5183 case ISD::Constant: {
5184 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5185 assert(CV != 0 && "Const value should be ConstSDNode.");
5186 const APInt &CVal = CV->getAPIntValue();
5187 APInt NewVal = CVal & Mask;
5189 return DAG.getConstant(NewVal, V.getValueType());
5194 // If the LHS or RHS don't contribute bits to the or, drop them.
5195 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5196 return V.getOperand(1);
5197 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5198 return V.getOperand(0);
5201 // Only look at single-use SRLs.
5202 if (!V.getNode()->hasOneUse())
5204 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5205 // See if we can recursively simplify the LHS.
5206 unsigned Amt = RHSC->getZExtValue();
5208 // Watch out for shift count overflow though.
5209 if (Amt >= Mask.getBitWidth()) break;
5210 APInt NewMask = Mask << Amt;
5211 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5212 if (SimplifyLHS.getNode())
5213 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5214 SimplifyLHS, V.getOperand(1));
5220 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5221 /// bits and then truncated to a narrower type and where N is a multiple
5222 /// of number of bits of the narrower type, transform it to a narrower load
5223 /// from address + N / num of bits of new type. If the result is to be
5224 /// extended, also fold the extension to form a extending load.
5225 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5226 unsigned Opc = N->getOpcode();
5228 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5229 SDValue N0 = N->getOperand(0);
5230 EVT VT = N->getValueType(0);
5233 // This transformation isn't valid for vector loads.
5237 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5239 if (Opc == ISD::SIGN_EXTEND_INREG) {
5240 ExtType = ISD::SEXTLOAD;
5241 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5242 } else if (Opc == ISD::SRL) {
5243 // Another special-case: SRL is basically zero-extending a narrower value.
5244 ExtType = ISD::ZEXTLOAD;
5246 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5247 if (!N01) return SDValue();
5248 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5249 VT.getSizeInBits() - N01->getZExtValue());
5251 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5254 unsigned EVTBits = ExtVT.getSizeInBits();
5256 // Do not generate loads of non-round integer types since these can
5257 // be expensive (and would be wrong if the type is not byte sized).
5258 if (!ExtVT.isRound())
5262 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5263 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5264 ShAmt = N01->getZExtValue();
5265 // Is the shift amount a multiple of size of VT?
5266 if ((ShAmt & (EVTBits-1)) == 0) {
5267 N0 = N0.getOperand(0);
5268 // Is the load width a multiple of size of VT?
5269 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5273 // At this point, we must have a load or else we can't do the transform.
5274 if (!isa<LoadSDNode>(N0)) return SDValue();
5276 // Because a SRL must be assumed to *need* to zero-extend the high bits
5277 // (as opposed to anyext the high bits), we can't combine the zextload
5278 // lowering of SRL and an sextload.
5279 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5282 // If the shift amount is larger than the input type then we're not
5283 // accessing any of the loaded bytes. If the load was a zextload/extload
5284 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5285 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5290 // If the load is shifted left (and the result isn't shifted back right),
5291 // we can fold the truncate through the shift.
5292 unsigned ShLeftAmt = 0;
5293 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5294 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5295 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5296 ShLeftAmt = N01->getZExtValue();
5297 N0 = N0.getOperand(0);
5301 // If we haven't found a load, we can't narrow it. Don't transform one with
5302 // multiple uses, this would require adding a new load.
5303 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5306 // Don't change the width of a volatile load.
5307 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5308 if (LN0->isVolatile())
5311 // Verify that we are actually reducing a load width here.
5312 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5315 // For the transform to be legal, the load must produce only two values
5316 // (the value loaded and the chain). Don't transform a pre-increment
5317 // load, for example, which produces an extra value. Otherwise the
5318 // transformation is not equivalent, and the downstream logic to replace
5319 // uses gets things wrong.
5320 if (LN0->getNumValues() > 2)
5323 // If the load that we're shrinking is an extload and we're not just
5324 // discarding the extension we can't simply shrink the load. Bail.
5325 // TODO: It would be possible to merge the extensions in some cases.
5326 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5327 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5330 EVT PtrType = N0.getOperand(1).getValueType();
5332 if (PtrType == MVT::Untyped || PtrType.isExtended())
5333 // It's not possible to generate a constant of extended or untyped type.
5336 // For big endian targets, we need to adjust the offset to the pointer to
5337 // load the correct bytes.
5338 if (TLI.isBigEndian()) {
5339 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5340 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5341 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5344 uint64_t PtrOff = ShAmt / 8;
5345 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5346 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5347 PtrType, LN0->getBasePtr(),
5348 DAG.getConstant(PtrOff, PtrType));
5349 AddToWorkList(NewPtr.getNode());
5352 if (ExtType == ISD::NON_EXTLOAD)
5353 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5354 LN0->getPointerInfo().getWithOffset(PtrOff),
5355 LN0->isVolatile(), LN0->isNonTemporal(),
5356 LN0->isInvariant(), NewAlign);
5358 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5359 LN0->getPointerInfo().getWithOffset(PtrOff),
5360 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5363 // Replace the old load's chain with the new load's chain.
5364 WorkListRemover DeadNodes(*this);
5365 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5367 // Shift the result left, if we've swallowed a left shift.
5368 SDValue Result = Load;
5369 if (ShLeftAmt != 0) {
5370 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5371 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5373 // If the shift amount is as large as the result size (but, presumably,
5374 // no larger than the source) then the useful bits of the result are
5375 // zero; we can't simply return the shortened shift, because the result
5376 // of that operation is undefined.
5377 if (ShLeftAmt >= VT.getSizeInBits())
5378 Result = DAG.getConstant(0, VT);
5380 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5381 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5384 // Return the new loaded value.
5388 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5389 SDValue N0 = N->getOperand(0);
5390 SDValue N1 = N->getOperand(1);
5391 EVT VT = N->getValueType(0);
5392 EVT EVT = cast<VTSDNode>(N1)->getVT();
5393 unsigned VTBits = VT.getScalarType().getSizeInBits();
5394 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5396 // fold (sext_in_reg c1) -> c1
5397 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5398 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5400 // If the input is already sign extended, just drop the extension.
5401 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5404 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5405 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5406 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5407 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5408 N0.getOperand(0), N1);
5410 // fold (sext_in_reg (sext x)) -> (sext x)
5411 // fold (sext_in_reg (aext x)) -> (sext x)
5412 // if x is small enough.
5413 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5414 SDValue N00 = N0.getOperand(0);
5415 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5416 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5417 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5420 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5421 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5422 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5424 // fold operands of sext_in_reg based on knowledge that the top bits are not
5426 if (SimplifyDemandedBits(SDValue(N, 0)))
5427 return SDValue(N, 0);
5429 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5430 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5431 SDValue NarrowLoad = ReduceLoadWidth(N);
5432 if (NarrowLoad.getNode())
5435 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5436 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5437 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5438 if (N0.getOpcode() == ISD::SRL) {
5439 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5440 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5441 // We can turn this into an SRA iff the input to the SRL is already sign
5443 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5444 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5445 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5446 N0.getOperand(0), N0.getOperand(1));
5450 // fold (sext_inreg (extload x)) -> (sextload x)
5451 if (ISD::isEXTLoad(N0.getNode()) &&
5452 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5453 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5454 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5455 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5456 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5457 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5459 LN0->getBasePtr(), LN0->getPointerInfo(),
5461 LN0->isVolatile(), LN0->isNonTemporal(),
5462 LN0->getAlignment());
5463 CombineTo(N, ExtLoad);
5464 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5465 AddToWorkList(ExtLoad.getNode());
5466 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5468 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5469 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5471 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5472 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5473 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5474 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5475 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5477 LN0->getBasePtr(), LN0->getPointerInfo(),
5479 LN0->isVolatile(), LN0->isNonTemporal(),
5480 LN0->getAlignment());
5481 CombineTo(N, ExtLoad);
5482 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5483 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5486 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5487 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5488 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5489 N0.getOperand(1), false);
5490 if (BSwap.getNode() != 0)
5491 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5498 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5499 SDValue N0 = N->getOperand(0);
5500 EVT VT = N->getValueType(0);
5501 bool isLE = TLI.isLittleEndian();
5504 if (N0.getValueType() == N->getValueType(0))
5506 // fold (truncate c1) -> c1
5507 if (isa<ConstantSDNode>(N0))
5508 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5509 // fold (truncate (truncate x)) -> (truncate x)
5510 if (N0.getOpcode() == ISD::TRUNCATE)
5511 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5512 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5513 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5514 N0.getOpcode() == ISD::SIGN_EXTEND ||
5515 N0.getOpcode() == ISD::ANY_EXTEND) {
5516 if (N0.getOperand(0).getValueType().bitsLT(VT))
5517 // if the source is smaller than the dest, we still need an extend
5518 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5520 if (N0.getOperand(0).getValueType().bitsGT(VT))
5521 // if the source is larger than the dest, than we just need the truncate
5522 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5523 // if the source and dest are the same type, we can drop both the extend
5524 // and the truncate.
5525 return N0.getOperand(0);
5528 // Fold extract-and-trunc into a narrow extract. For example:
5529 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5530 // i32 y = TRUNCATE(i64 x)
5532 // v16i8 b = BITCAST (v2i64 val)
5533 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5535 // Note: We only run this optimization after type legalization (which often
5536 // creates this pattern) and before operation legalization after which
5537 // we need to be more careful about the vector instructions that we generate.
5538 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5539 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5541 EVT VecTy = N0.getOperand(0).getValueType();
5542 EVT ExTy = N0.getValueType();
5543 EVT TrTy = N->getValueType(0);
5545 unsigned NumElem = VecTy.getVectorNumElements();
5546 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5548 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5549 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5551 SDValue EltNo = N0->getOperand(1);
5552 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5553 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5554 EVT IndexTy = TLI.getVectorIdxTy();
5555 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5557 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5558 NVT, N0.getOperand(0));
5560 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5562 DAG.getConstant(Index, IndexTy));
5566 // Fold a series of buildvector, bitcast, and truncate if possible.
5568 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5569 // (2xi32 (buildvector x, y)).
5570 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5571 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5572 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5573 N0.getOperand(0).hasOneUse()) {
5575 SDValue BuildVect = N0.getOperand(0);
5576 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5577 EVT TruncVecEltTy = VT.getVectorElementType();
5579 // Check that the element types match.
5580 if (BuildVectEltTy == TruncVecEltTy) {
5581 // Now we only need to compute the offset of the truncated elements.
5582 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5583 unsigned TruncVecNumElts = VT.getVectorNumElements();
5584 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5586 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5587 "Invalid number of elements");
5589 SmallVector<SDValue, 8> Opnds;
5590 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5591 Opnds.push_back(BuildVect.getOperand(i));
5593 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5598 // See if we can simplify the input to this truncate through knowledge that
5599 // only the low bits are being used.
5600 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5601 // Currently we only perform this optimization on scalars because vectors
5602 // may have different active low bits.
5603 if (!VT.isVector()) {
5605 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5606 VT.getSizeInBits()));
5607 if (Shorter.getNode())
5608 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5610 // fold (truncate (load x)) -> (smaller load x)
5611 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5612 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5613 SDValue Reduced = ReduceLoadWidth(N);
5614 if (Reduced.getNode())
5617 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5618 // where ... are all 'undef'.
5619 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5620 SmallVector<EVT, 8> VTs;
5623 unsigned NumDefs = 0;
5625 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5626 SDValue X = N0.getOperand(i);
5627 if (X.getOpcode() != ISD::UNDEF) {
5632 // Stop if more than one members are non-undef.
5635 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5636 VT.getVectorElementType(),
5637 X.getValueType().getVectorNumElements()));
5641 return DAG.getUNDEF(VT);
5644 assert(V.getNode() && "The single defined operand is empty!");
5645 SmallVector<SDValue, 8> Opnds;
5646 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5648 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5651 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5652 AddToWorkList(NV.getNode());
5653 Opnds.push_back(NV);
5655 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5656 &Opnds[0], Opnds.size());
5660 // Simplify the operands using demanded-bits information.
5661 if (!VT.isVector() &&
5662 SimplifyDemandedBits(SDValue(N, 0)))
5663 return SDValue(N, 0);
5668 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5669 SDValue Elt = N->getOperand(i);
5670 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5671 return Elt.getNode();
5672 return Elt.getOperand(Elt.getResNo()).getNode();
5675 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5676 /// if load locations are consecutive.
5677 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5678 assert(N->getOpcode() == ISD::BUILD_PAIR);
5680 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5681 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5682 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5683 LD1->getPointerInfo().getAddrSpace() !=
5684 LD2->getPointerInfo().getAddrSpace())
5686 EVT LD1VT = LD1->getValueType(0);
5688 if (ISD::isNON_EXTLoad(LD2) &&
5690 // If both are volatile this would reduce the number of volatile loads.
5691 // If one is volatile it might be ok, but play conservative and bail out.
5692 !LD1->isVolatile() &&
5693 !LD2->isVolatile() &&
5694 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5695 unsigned Align = LD1->getAlignment();
5696 unsigned NewAlign = TLI.getDataLayout()->
5697 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5699 if (NewAlign <= Align &&
5700 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5701 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5702 LD1->getBasePtr(), LD1->getPointerInfo(),
5703 false, false, false, Align);
5709 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5710 SDValue N0 = N->getOperand(0);
5711 EVT VT = N->getValueType(0);
5713 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5714 // Only do this before legalize, since afterward the target may be depending
5715 // on the bitconvert.
5716 // First check to see if this is all constant.
5718 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5720 bool isSimple = true;
5721 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5722 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5723 N0.getOperand(i).getOpcode() != ISD::Constant &&
5724 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5729 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5730 assert(!DestEltVT.isVector() &&
5731 "Element type of vector ValueType must not be vector!");
5733 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5736 // If the input is a constant, let getNode fold it.
5737 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5738 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5739 if (Res.getNode() != N) {
5740 if (!LegalOperations ||
5741 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5744 // Folding it resulted in an illegal node, and it's too late to
5745 // do that. Clean up the old node and forego the transformation.
5746 // Ideally this won't happen very often, because instcombine
5747 // and the earlier dagcombine runs (where illegal nodes are
5748 // permitted) should have folded most of them already.
5749 DAG.DeleteNode(Res.getNode());
5753 // (conv (conv x, t1), t2) -> (conv x, t2)
5754 if (N0.getOpcode() == ISD::BITCAST)
5755 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5758 // fold (conv (load x)) -> (load (conv*)x)
5759 // If the resultant load doesn't need a higher alignment than the original!
5760 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5761 // Do not change the width of a volatile load.
5762 !cast<LoadSDNode>(N0)->isVolatile() &&
5763 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5764 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5765 unsigned Align = TLI.getDataLayout()->
5766 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5767 unsigned OrigAlign = LN0->getAlignment();
5769 if (Align <= OrigAlign) {
5770 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5771 LN0->getBasePtr(), LN0->getPointerInfo(),
5772 LN0->isVolatile(), LN0->isNonTemporal(),
5773 LN0->isInvariant(), OrigAlign);
5775 CombineTo(N0.getNode(),
5776 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5777 N0.getValueType(), Load),
5783 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5784 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5785 // This often reduces constant pool loads.
5786 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5787 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5788 N0.getNode()->hasOneUse() && VT.isInteger() &&
5789 !VT.isVector() && !N0.getValueType().isVector()) {
5790 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5792 AddToWorkList(NewConv.getNode());
5794 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5795 if (N0.getOpcode() == ISD::FNEG)
5796 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5797 NewConv, DAG.getConstant(SignBit, VT));
5798 assert(N0.getOpcode() == ISD::FABS);
5799 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5800 NewConv, DAG.getConstant(~SignBit, VT));
5803 // fold (bitconvert (fcopysign cst, x)) ->
5804 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5805 // Note that we don't handle (copysign x, cst) because this can always be
5806 // folded to an fneg or fabs.
5807 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5808 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5809 VT.isInteger() && !VT.isVector()) {
5810 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5811 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5812 if (isTypeLegal(IntXVT)) {
5813 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5814 IntXVT, N0.getOperand(1));
5815 AddToWorkList(X.getNode());
5817 // If X has a different width than the result/lhs, sext it or truncate it.
5818 unsigned VTWidth = VT.getSizeInBits();
5819 if (OrigXWidth < VTWidth) {
5820 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5821 AddToWorkList(X.getNode());
5822 } else if (OrigXWidth > VTWidth) {
5823 // To get the sign bit in the right place, we have to shift it right
5824 // before truncating.
5825 X = DAG.getNode(ISD::SRL, SDLoc(X),
5826 X.getValueType(), X,
5827 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5828 AddToWorkList(X.getNode());
5829 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5830 AddToWorkList(X.getNode());
5833 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5834 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5835 X, DAG.getConstant(SignBit, VT));
5836 AddToWorkList(X.getNode());
5838 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5839 VT, N0.getOperand(0));
5840 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5841 Cst, DAG.getConstant(~SignBit, VT));
5842 AddToWorkList(Cst.getNode());
5844 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5848 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5849 if (N0.getOpcode() == ISD::BUILD_PAIR) {
5850 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5851 if (CombineLD.getNode())
5858 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5859 EVT VT = N->getValueType(0);
5860 return CombineConsecutiveLoads(N, VT);
5863 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5864 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
5865 /// destination element value type.
5866 SDValue DAGCombiner::
5867 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5868 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5870 // If this is already the right type, we're done.
5871 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5873 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5874 unsigned DstBitSize = DstEltVT.getSizeInBits();
5876 // If this is a conversion of N elements of one type to N elements of another
5877 // type, convert each element. This handles FP<->INT cases.
5878 if (SrcBitSize == DstBitSize) {
5879 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5880 BV->getValueType(0).getVectorNumElements());
5882 // Due to the FP element handling below calling this routine recursively,
5883 // we can end up with a scalar-to-vector node here.
5884 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5885 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5886 DAG.getNode(ISD::BITCAST, SDLoc(BV),
5887 DstEltVT, BV->getOperand(0)));
5889 SmallVector<SDValue, 8> Ops;
5890 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5891 SDValue Op = BV->getOperand(i);
5892 // If the vector element type is not legal, the BUILD_VECTOR operands
5893 // are promoted and implicitly truncated. Make that explicit here.
5894 if (Op.getValueType() != SrcEltVT)
5895 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5896 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5898 AddToWorkList(Ops.back().getNode());
5900 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5901 &Ops[0], Ops.size());
5904 // Otherwise, we're growing or shrinking the elements. To avoid having to
5905 // handle annoying details of growing/shrinking FP values, we convert them to
5907 if (SrcEltVT.isFloatingPoint()) {
5908 // Convert the input float vector to a int vector where the elements are the
5910 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5911 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5912 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5916 // Now we know the input is an integer vector. If the output is a FP type,
5917 // convert to integer first, then to FP of the right size.
5918 if (DstEltVT.isFloatingPoint()) {
5919 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5920 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5921 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5923 // Next, convert to FP elements of the same size.
5924 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5927 // Okay, we know the src/dst types are both integers of differing types.
5928 // Handling growing first.
5929 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5930 if (SrcBitSize < DstBitSize) {
5931 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5933 SmallVector<SDValue, 8> Ops;
5934 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5935 i += NumInputsPerOutput) {
5936 bool isLE = TLI.isLittleEndian();
5937 APInt NewBits = APInt(DstBitSize, 0);
5938 bool EltIsUndef = true;
5939 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5940 // Shift the previously computed bits over.
5941 NewBits <<= SrcBitSize;
5942 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5943 if (Op.getOpcode() == ISD::UNDEF) continue;
5946 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5947 zextOrTrunc(SrcBitSize).zext(DstBitSize);
5951 Ops.push_back(DAG.getUNDEF(DstEltVT));
5953 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5956 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5957 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5958 &Ops[0], Ops.size());
5961 // Finally, this must be the case where we are shrinking elements: each input
5962 // turns into multiple outputs.
5963 bool isS2V = ISD::isScalarToVector(BV);
5964 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5965 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5966 NumOutputsPerInput*BV->getNumOperands());
5967 SmallVector<SDValue, 8> Ops;
5969 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5970 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5971 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5972 Ops.push_back(DAG.getUNDEF(DstEltVT));
5976 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5977 getAPIntValue().zextOrTrunc(SrcBitSize);
5979 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5980 APInt ThisVal = OpVal.trunc(DstBitSize);
5981 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5982 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5983 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5984 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5986 OpVal = OpVal.lshr(DstBitSize);
5989 // For big endian targets, swap the order of the pieces of each element.
5990 if (TLI.isBigEndian())
5991 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5994 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5995 &Ops[0], Ops.size());
5998 SDValue DAGCombiner::visitFADD(SDNode *N) {
5999 SDValue N0 = N->getOperand(0);
6000 SDValue N1 = N->getOperand(1);
6001 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6002 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6003 EVT VT = N->getValueType(0);
6006 if (VT.isVector()) {
6007 SDValue FoldedVOp = SimplifyVBinOp(N);
6008 if (FoldedVOp.getNode()) return FoldedVOp;
6011 // fold (fadd c1, c2) -> c1 + c2
6013 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6014 // canonicalize constant to RHS
6015 if (N0CFP && !N1CFP)
6016 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6017 // fold (fadd A, 0) -> A
6018 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6019 N1CFP->getValueAPF().isZero())
6021 // fold (fadd A, (fneg B)) -> (fsub A, B)
6022 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6023 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6024 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6025 GetNegatedExpression(N1, DAG, LegalOperations));
6026 // fold (fadd (fneg A), B) -> (fsub B, A)
6027 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6028 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6029 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6030 GetNegatedExpression(N0, DAG, LegalOperations));
6032 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6033 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6034 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6035 isa<ConstantFPSDNode>(N0.getOperand(1)))
6036 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6037 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6038 N0.getOperand(1), N1));
6040 // No FP constant should be created after legalization as Instruction
6041 // Selection pass has hard time in dealing with FP constant.
6043 // We don't need test this condition for transformation like following, as
6044 // the DAG being transformed implies it is legal to take FP constant as
6047 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6049 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6051 // If allow, fold (fadd (fneg x), x) -> 0.0
6052 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6053 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6054 return DAG.getConstantFP(0.0, VT);
6056 // If allow, fold (fadd x, (fneg x)) -> 0.0
6057 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6058 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6059 return DAG.getConstantFP(0.0, VT);
6061 // In unsafe math mode, we can fold chains of FADD's of the same value
6062 // into multiplications. This transform is not safe in general because
6063 // we are reducing the number of rounding steps.
6064 if (DAG.getTarget().Options.UnsafeFPMath &&
6065 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6067 if (N0.getOpcode() == ISD::FMUL) {
6068 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6069 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6071 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6072 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6073 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6075 DAG.getConstantFP(1.0, VT));
6076 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6080 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6081 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6082 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6084 DAG.getConstantFP(1.0, VT));
6085 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6089 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6090 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6091 N1.getOperand(0) == N1.getOperand(1) &&
6092 N0.getOperand(1) == N1.getOperand(0)) {
6093 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6095 DAG.getConstantFP(2.0, VT));
6096 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6097 N0.getOperand(1), NewCFP);
6100 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6101 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6102 N1.getOperand(0) == N1.getOperand(1) &&
6103 N0.getOperand(0) == N1.getOperand(0)) {
6104 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6106 DAG.getConstantFP(2.0, VT));
6107 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6108 N0.getOperand(0), NewCFP);
6112 if (N1.getOpcode() == ISD::FMUL) {
6113 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6114 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6116 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6117 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6118 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6120 DAG.getConstantFP(1.0, VT));
6121 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6125 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6126 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6127 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6129 DAG.getConstantFP(1.0, VT));
6130 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6135 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6136 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6137 N0.getOperand(0) == N0.getOperand(1) &&
6138 N1.getOperand(1) == N0.getOperand(0)) {
6139 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6141 DAG.getConstantFP(2.0, VT));
6142 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6143 N1.getOperand(1), NewCFP);
6146 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6147 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6148 N0.getOperand(0) == N0.getOperand(1) &&
6149 N1.getOperand(0) == N0.getOperand(0)) {
6150 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6152 DAG.getConstantFP(2.0, VT));
6153 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6154 N1.getOperand(0), NewCFP);
6158 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6159 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6160 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6161 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6162 (N0.getOperand(0) == N1))
6163 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6164 N1, DAG.getConstantFP(3.0, VT));
6167 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6168 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6169 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6170 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6171 N1.getOperand(0) == N0)
6172 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6173 N0, DAG.getConstantFP(3.0, VT));
6176 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6177 if (AllowNewFpConst &&
6178 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6179 N0.getOperand(0) == N0.getOperand(1) &&
6180 N1.getOperand(0) == N1.getOperand(1) &&
6181 N0.getOperand(0) == N1.getOperand(0))
6182 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6184 DAG.getConstantFP(4.0, VT));
6187 // FADD -> FMA combines:
6188 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6189 DAG.getTarget().Options.UnsafeFPMath) &&
6190 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6191 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6193 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6194 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6195 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6196 N0.getOperand(0), N0.getOperand(1), N1);
6198 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6199 // Note: Commutes FADD operands.
6200 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6201 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6202 N1.getOperand(0), N1.getOperand(1), N0);
6208 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6209 SDValue N0 = N->getOperand(0);
6210 SDValue N1 = N->getOperand(1);
6211 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6212 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6213 EVT VT = N->getValueType(0);
6217 if (VT.isVector()) {
6218 SDValue FoldedVOp = SimplifyVBinOp(N);
6219 if (FoldedVOp.getNode()) return FoldedVOp;
6222 // fold (fsub c1, c2) -> c1-c2
6224 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6225 // fold (fsub A, 0) -> A
6226 if (DAG.getTarget().Options.UnsafeFPMath &&
6227 N1CFP && N1CFP->getValueAPF().isZero())
6229 // fold (fsub 0, B) -> -B
6230 if (DAG.getTarget().Options.UnsafeFPMath &&
6231 N0CFP && N0CFP->getValueAPF().isZero()) {
6232 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6233 return GetNegatedExpression(N1, DAG, LegalOperations);
6234 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6235 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6237 // fold (fsub A, (fneg B)) -> (fadd A, B)
6238 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6239 return DAG.getNode(ISD::FADD, dl, VT, N0,
6240 GetNegatedExpression(N1, DAG, LegalOperations));
6242 // If 'unsafe math' is enabled, fold
6243 // (fsub x, x) -> 0.0 &
6244 // (fsub x, (fadd x, y)) -> (fneg y) &
6245 // (fsub x, (fadd y, x)) -> (fneg y)
6246 if (DAG.getTarget().Options.UnsafeFPMath) {
6248 return DAG.getConstantFP(0.0f, VT);
6250 if (N1.getOpcode() == ISD::FADD) {
6251 SDValue N10 = N1->getOperand(0);
6252 SDValue N11 = N1->getOperand(1);
6254 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6255 &DAG.getTarget().Options))
6256 return GetNegatedExpression(N11, DAG, LegalOperations);
6258 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6259 &DAG.getTarget().Options))
6260 return GetNegatedExpression(N10, DAG, LegalOperations);
6264 // FSUB -> FMA combines:
6265 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6266 DAG.getTarget().Options.UnsafeFPMath) &&
6267 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6268 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6270 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6271 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6272 return DAG.getNode(ISD::FMA, dl, VT,
6273 N0.getOperand(0), N0.getOperand(1),
6274 DAG.getNode(ISD::FNEG, dl, VT, N1));
6276 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6277 // Note: Commutes FSUB operands.
6278 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6279 return DAG.getNode(ISD::FMA, dl, VT,
6280 DAG.getNode(ISD::FNEG, dl, VT,
6282 N1.getOperand(1), N0);
6284 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6285 if (N0.getOpcode() == ISD::FNEG &&
6286 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6287 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6288 SDValue N00 = N0.getOperand(0).getOperand(0);
6289 SDValue N01 = N0.getOperand(0).getOperand(1);
6290 return DAG.getNode(ISD::FMA, dl, VT,
6291 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6292 DAG.getNode(ISD::FNEG, dl, VT, N1));
6299 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6300 SDValue N0 = N->getOperand(0);
6301 SDValue N1 = N->getOperand(1);
6302 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6303 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6304 EVT VT = N->getValueType(0);
6305 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6308 if (VT.isVector()) {
6309 SDValue FoldedVOp = SimplifyVBinOp(N);
6310 if (FoldedVOp.getNode()) return FoldedVOp;
6313 // fold (fmul c1, c2) -> c1*c2
6315 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6316 // canonicalize constant to RHS
6317 if (N0CFP && !N1CFP)
6318 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6319 // fold (fmul A, 0) -> 0
6320 if (DAG.getTarget().Options.UnsafeFPMath &&
6321 N1CFP && N1CFP->getValueAPF().isZero())
6323 // fold (fmul A, 0) -> 0, vector edition.
6324 if (DAG.getTarget().Options.UnsafeFPMath &&
6325 ISD::isBuildVectorAllZeros(N1.getNode()))
6327 // fold (fmul A, 1.0) -> A
6328 if (N1CFP && N1CFP->isExactlyValue(1.0))
6330 // fold (fmul X, 2.0) -> (fadd X, X)
6331 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6332 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6333 // fold (fmul X, -1.0) -> (fneg X)
6334 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6335 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6336 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6338 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6339 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6340 &DAG.getTarget().Options)) {
6341 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6342 &DAG.getTarget().Options)) {
6343 // Both can be negated for free, check to see if at least one is cheaper
6345 if (LHSNeg == 2 || RHSNeg == 2)
6346 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6347 GetNegatedExpression(N0, DAG, LegalOperations),
6348 GetNegatedExpression(N1, DAG, LegalOperations));
6352 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6353 if (DAG.getTarget().Options.UnsafeFPMath &&
6354 N1CFP && N0.getOpcode() == ISD::FMUL &&
6355 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6356 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6357 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6358 N0.getOperand(1), N1));
6363 SDValue DAGCombiner::visitFMA(SDNode *N) {
6364 SDValue N0 = N->getOperand(0);
6365 SDValue N1 = N->getOperand(1);
6366 SDValue N2 = N->getOperand(2);
6367 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6368 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6369 EVT VT = N->getValueType(0);
6372 if (DAG.getTarget().Options.UnsafeFPMath) {
6373 if (N0CFP && N0CFP->isZero())
6375 if (N1CFP && N1CFP->isZero())
6378 if (N0CFP && N0CFP->isExactlyValue(1.0))
6379 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6380 if (N1CFP && N1CFP->isExactlyValue(1.0))
6381 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6383 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6384 if (N0CFP && !N1CFP)
6385 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6387 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6388 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6389 N2.getOpcode() == ISD::FMUL &&
6390 N0 == N2.getOperand(0) &&
6391 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6392 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6393 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6397 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6398 if (DAG.getTarget().Options.UnsafeFPMath &&
6399 N0.getOpcode() == ISD::FMUL && N1CFP &&
6400 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6401 return DAG.getNode(ISD::FMA, dl, VT,
6403 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6407 // (fma x, 1, y) -> (fadd x, y)
6408 // (fma x, -1, y) -> (fadd (fneg x), y)
6410 if (N1CFP->isExactlyValue(1.0))
6411 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6413 if (N1CFP->isExactlyValue(-1.0) &&
6414 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6415 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6416 AddToWorkList(RHSNeg.getNode());
6417 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6421 // (fma x, c, x) -> (fmul x, (c+1))
6422 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6423 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6424 DAG.getNode(ISD::FADD, dl, VT,
6425 N1, DAG.getConstantFP(1.0, VT)));
6427 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6428 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6429 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6430 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6431 DAG.getNode(ISD::FADD, dl, VT,
6432 N1, DAG.getConstantFP(-1.0, VT)));
6438 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6439 SDValue N0 = N->getOperand(0);
6440 SDValue N1 = N->getOperand(1);
6441 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6442 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6443 EVT VT = N->getValueType(0);
6444 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6447 if (VT.isVector()) {
6448 SDValue FoldedVOp = SimplifyVBinOp(N);
6449 if (FoldedVOp.getNode()) return FoldedVOp;
6452 // fold (fdiv c1, c2) -> c1/c2
6454 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6456 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6457 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6458 // Compute the reciprocal 1.0 / c2.
6459 APFloat N1APF = N1CFP->getValueAPF();
6460 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6461 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6462 // Only do the transform if the reciprocal is a legal fp immediate that
6463 // isn't too nasty (eg NaN, denormal, ...).
6464 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6465 (!LegalOperations ||
6466 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6467 // backend)... we should handle this gracefully after Legalize.
6468 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6469 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6470 TLI.isFPImmLegal(Recip, VT)))
6471 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6472 DAG.getConstantFP(Recip, VT));
6475 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6476 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6477 &DAG.getTarget().Options)) {
6478 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6479 &DAG.getTarget().Options)) {
6480 // Both can be negated for free, check to see if at least one is cheaper
6482 if (LHSNeg == 2 || RHSNeg == 2)
6483 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6484 GetNegatedExpression(N0, DAG, LegalOperations),
6485 GetNegatedExpression(N1, DAG, LegalOperations));
6492 SDValue DAGCombiner::visitFREM(SDNode *N) {
6493 SDValue N0 = N->getOperand(0);
6494 SDValue N1 = N->getOperand(1);
6495 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6496 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6497 EVT VT = N->getValueType(0);
6499 // fold (frem c1, c2) -> fmod(c1,c2)
6501 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6506 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6507 SDValue N0 = N->getOperand(0);
6508 SDValue N1 = N->getOperand(1);
6509 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6510 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6511 EVT VT = N->getValueType(0);
6513 if (N0CFP && N1CFP) // Constant fold
6514 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6517 const APFloat& V = N1CFP->getValueAPF();
6518 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6519 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6520 if (!V.isNegative()) {
6521 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6522 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6524 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6525 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6526 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6530 // copysign(fabs(x), y) -> copysign(x, y)
6531 // copysign(fneg(x), y) -> copysign(x, y)
6532 // copysign(copysign(x,z), y) -> copysign(x, y)
6533 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6534 N0.getOpcode() == ISD::FCOPYSIGN)
6535 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6536 N0.getOperand(0), N1);
6538 // copysign(x, abs(y)) -> abs(x)
6539 if (N1.getOpcode() == ISD::FABS)
6540 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6542 // copysign(x, copysign(y,z)) -> copysign(x, z)
6543 if (N1.getOpcode() == ISD::FCOPYSIGN)
6544 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6545 N0, N1.getOperand(1));
6547 // copysign(x, fp_extend(y)) -> copysign(x, y)
6548 // copysign(x, fp_round(y)) -> copysign(x, y)
6549 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6550 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6551 N0, N1.getOperand(0));
6556 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6557 SDValue N0 = N->getOperand(0);
6558 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6559 EVT VT = N->getValueType(0);
6560 EVT OpVT = N0.getValueType();
6562 // fold (sint_to_fp c1) -> c1fp
6564 // ...but only if the target supports immediate floating-point values
6565 (!LegalOperations ||
6566 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6567 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6569 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6570 // but UINT_TO_FP is legal on this target, try to convert.
6571 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6572 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6573 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6574 if (DAG.SignBitIsZero(N0))
6575 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6578 // The next optimizations are desireable only if SELECT_CC can be lowered.
6579 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6580 // having to say they don't support SELECT_CC on every type the DAG knows
6581 // about, since there is no way to mark an opcode illegal at all value types
6582 // (See also visitSELECT)
6583 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6584 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6585 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6587 (!LegalOperations ||
6588 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6590 { N0.getOperand(0), N0.getOperand(1),
6591 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6593 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6596 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6597 // (select_cc x, y, 1.0, 0.0,, cc)
6598 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6599 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6600 (!LegalOperations ||
6601 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6603 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6604 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6605 N0.getOperand(0).getOperand(2) };
6606 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6613 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6614 SDValue N0 = N->getOperand(0);
6615 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6616 EVT VT = N->getValueType(0);
6617 EVT OpVT = N0.getValueType();
6619 // fold (uint_to_fp c1) -> c1fp
6621 // ...but only if the target supports immediate floating-point values
6622 (!LegalOperations ||
6623 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6624 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6626 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6627 // but SINT_TO_FP is legal on this target, try to convert.
6628 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6629 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6630 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6631 if (DAG.SignBitIsZero(N0))
6632 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6635 // The next optimizations are desireable only if SELECT_CC can be lowered.
6636 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6637 // having to say they don't support SELECT_CC on every type the DAG knows
6638 // about, since there is no way to mark an opcode illegal at all value types
6639 // (See also visitSELECT)
6640 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6641 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6643 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6644 (!LegalOperations ||
6645 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6647 { N0.getOperand(0), N0.getOperand(1),
6648 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6650 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6657 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6658 SDValue N0 = N->getOperand(0);
6659 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6660 EVT VT = N->getValueType(0);
6662 // fold (fp_to_sint c1fp) -> c1
6664 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6669 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6670 SDValue N0 = N->getOperand(0);
6671 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6672 EVT VT = N->getValueType(0);
6674 // fold (fp_to_uint c1fp) -> c1
6676 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6681 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6682 SDValue N0 = N->getOperand(0);
6683 SDValue N1 = N->getOperand(1);
6684 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6685 EVT VT = N->getValueType(0);
6687 // fold (fp_round c1fp) -> c1fp
6689 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6691 // fold (fp_round (fp_extend x)) -> x
6692 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6693 return N0.getOperand(0);
6695 // fold (fp_round (fp_round x)) -> (fp_round x)
6696 if (N0.getOpcode() == ISD::FP_ROUND) {
6697 // This is a value preserving truncation if both round's are.
6698 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6699 N0.getNode()->getConstantOperandVal(1) == 1;
6700 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6701 DAG.getIntPtrConstant(IsTrunc));
6704 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6705 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6706 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6707 N0.getOperand(0), N1);
6708 AddToWorkList(Tmp.getNode());
6709 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6710 Tmp, N0.getOperand(1));
6716 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6717 SDValue N0 = N->getOperand(0);
6718 EVT VT = N->getValueType(0);
6719 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6720 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6722 // fold (fp_round_inreg c1fp) -> c1fp
6723 if (N0CFP && isTypeLegal(EVT)) {
6724 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6725 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6731 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6732 SDValue N0 = N->getOperand(0);
6733 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6734 EVT VT = N->getValueType(0);
6736 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6737 if (N->hasOneUse() &&
6738 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6741 // fold (fp_extend c1fp) -> c1fp
6743 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6745 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6747 if (N0.getOpcode() == ISD::FP_ROUND
6748 && N0.getNode()->getConstantOperandVal(1) == 1) {
6749 SDValue In = N0.getOperand(0);
6750 if (In.getValueType() == VT) return In;
6751 if (VT.bitsLT(In.getValueType()))
6752 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6753 In, N0.getOperand(1));
6754 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6757 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6758 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6759 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6760 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6761 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6762 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6764 LN0->getBasePtr(), LN0->getPointerInfo(),
6766 LN0->isVolatile(), LN0->isNonTemporal(),
6767 LN0->getAlignment());
6768 CombineTo(N, ExtLoad);
6769 CombineTo(N0.getNode(),
6770 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6771 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6772 ExtLoad.getValue(1));
6773 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6779 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6780 SDValue N0 = N->getOperand(0);
6781 EVT VT = N->getValueType(0);
6783 if (VT.isVector()) {
6784 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6785 if (FoldedVOp.getNode()) return FoldedVOp;
6788 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6789 &DAG.getTarget().Options))
6790 return GetNegatedExpression(N0, DAG, LegalOperations);
6792 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6793 // constant pool values.
6794 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6796 N0.getNode()->hasOneUse() &&
6797 N0.getOperand(0).getValueType().isInteger()) {
6798 SDValue Int = N0.getOperand(0);
6799 EVT IntVT = Int.getValueType();
6800 if (IntVT.isInteger() && !IntVT.isVector()) {
6801 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6802 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6803 AddToWorkList(Int.getNode());
6804 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6809 // (fneg (fmul c, x)) -> (fmul -c, x)
6810 if (N0.getOpcode() == ISD::FMUL) {
6811 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6813 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6815 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6822 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6823 SDValue N0 = N->getOperand(0);
6824 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6825 EVT VT = N->getValueType(0);
6827 // fold (fceil c1) -> fceil(c1)
6829 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6834 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6835 SDValue N0 = N->getOperand(0);
6836 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6837 EVT VT = N->getValueType(0);
6839 // fold (ftrunc c1) -> ftrunc(c1)
6841 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6846 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6847 SDValue N0 = N->getOperand(0);
6848 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6849 EVT VT = N->getValueType(0);
6851 // fold (ffloor c1) -> ffloor(c1)
6853 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6858 SDValue DAGCombiner::visitFABS(SDNode *N) {
6859 SDValue N0 = N->getOperand(0);
6860 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6861 EVT VT = N->getValueType(0);
6863 if (VT.isVector()) {
6864 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6865 if (FoldedVOp.getNode()) return FoldedVOp;
6868 // fold (fabs c1) -> fabs(c1)
6870 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6871 // fold (fabs (fabs x)) -> (fabs x)
6872 if (N0.getOpcode() == ISD::FABS)
6873 return N->getOperand(0);
6874 // fold (fabs (fneg x)) -> (fabs x)
6875 // fold (fabs (fcopysign x, y)) -> (fabs x)
6876 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6877 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6879 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6880 // constant pool values.
6881 if (!TLI.isFAbsFree(VT) &&
6882 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6883 N0.getOperand(0).getValueType().isInteger() &&
6884 !N0.getOperand(0).getValueType().isVector()) {
6885 SDValue Int = N0.getOperand(0);
6886 EVT IntVT = Int.getValueType();
6887 if (IntVT.isInteger() && !IntVT.isVector()) {
6888 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6889 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6890 AddToWorkList(Int.getNode());
6891 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6892 N->getValueType(0), Int);
6899 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6900 SDValue Chain = N->getOperand(0);
6901 SDValue N1 = N->getOperand(1);
6902 SDValue N2 = N->getOperand(2);
6904 // If N is a constant we could fold this into a fallthrough or unconditional
6905 // branch. However that doesn't happen very often in normal code, because
6906 // Instcombine/SimplifyCFG should have handled the available opportunities.
6907 // If we did this folding here, it would be necessary to update the
6908 // MachineBasicBlock CFG, which is awkward.
6910 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6912 if (N1.getOpcode() == ISD::SETCC &&
6913 TLI.isOperationLegalOrCustom(ISD::BR_CC,
6914 N1.getOperand(0).getValueType())) {
6915 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6916 Chain, N1.getOperand(2),
6917 N1.getOperand(0), N1.getOperand(1), N2);
6920 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6921 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6922 (N1.getOperand(0).hasOneUse() &&
6923 N1.getOperand(0).getOpcode() == ISD::SRL))) {
6925 if (N1.getOpcode() == ISD::TRUNCATE) {
6926 // Look pass the truncate.
6927 Trunc = N1.getNode();
6928 N1 = N1.getOperand(0);
6931 // Match this pattern so that we can generate simpler code:
6934 // %b = and i32 %a, 2
6935 // %c = srl i32 %b, 1
6936 // brcond i32 %c ...
6941 // %b = and i32 %a, 2
6942 // %c = setcc eq %b, 0
6945 // This applies only when the AND constant value has one bit set and the
6946 // SRL constant is equal to the log2 of the AND constant. The back-end is
6947 // smart enough to convert the result into a TEST/JMP sequence.
6948 SDValue Op0 = N1.getOperand(0);
6949 SDValue Op1 = N1.getOperand(1);
6951 if (Op0.getOpcode() == ISD::AND &&
6952 Op1.getOpcode() == ISD::Constant) {
6953 SDValue AndOp1 = Op0.getOperand(1);
6955 if (AndOp1.getOpcode() == ISD::Constant) {
6956 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6958 if (AndConst.isPowerOf2() &&
6959 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6961 DAG.getSetCC(SDLoc(N),
6962 getSetCCResultType(Op0.getValueType()),
6963 Op0, DAG.getConstant(0, Op0.getValueType()),
6966 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6967 MVT::Other, Chain, SetCC, N2);
6968 // Don't add the new BRCond into the worklist or else SimplifySelectCC
6969 // will convert it back to (X & C1) >> C2.
6970 CombineTo(N, NewBRCond, false);
6971 // Truncate is dead.
6973 removeFromWorkList(Trunc);
6974 DAG.DeleteNode(Trunc);
6976 // Replace the uses of SRL with SETCC
6977 WorkListRemover DeadNodes(*this);
6978 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6979 removeFromWorkList(N1.getNode());
6980 DAG.DeleteNode(N1.getNode());
6981 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6987 // Restore N1 if the above transformation doesn't match.
6988 N1 = N->getOperand(1);
6991 // Transform br(xor(x, y)) -> br(x != y)
6992 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6993 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6994 SDNode *TheXor = N1.getNode();
6995 SDValue Op0 = TheXor->getOperand(0);
6996 SDValue Op1 = TheXor->getOperand(1);
6997 if (Op0.getOpcode() == Op1.getOpcode()) {
6998 // Avoid missing important xor optimizations.
6999 SDValue Tmp = visitXOR(TheXor);
7000 if (Tmp.getNode()) {
7001 if (Tmp.getNode() != TheXor) {
7002 DEBUG(dbgs() << "\nReplacing.8 ";
7004 dbgs() << "\nWith: ";
7005 Tmp.getNode()->dump(&DAG);
7007 WorkListRemover DeadNodes(*this);
7008 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7009 removeFromWorkList(TheXor);
7010 DAG.DeleteNode(TheXor);
7011 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7012 MVT::Other, Chain, Tmp, N2);
7015 // visitXOR has changed XOR's operands or replaced the XOR completely,
7017 return SDValue(N, 0);
7021 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7023 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7024 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7025 Op0.getOpcode() == ISD::XOR) {
7026 TheXor = Op0.getNode();
7030 EVT SetCCVT = N1.getValueType();
7032 SetCCVT = getSetCCResultType(SetCCVT);
7033 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7036 Equal ? ISD::SETEQ : ISD::SETNE);
7037 // Replace the uses of XOR with SETCC
7038 WorkListRemover DeadNodes(*this);
7039 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7040 removeFromWorkList(N1.getNode());
7041 DAG.DeleteNode(N1.getNode());
7042 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7043 MVT::Other, Chain, SetCC, N2);
7050 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7052 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7053 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7054 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7056 // If N is a constant we could fold this into a fallthrough or unconditional
7057 // branch. However that doesn't happen very often in normal code, because
7058 // Instcombine/SimplifyCFG should have handled the available opportunities.
7059 // If we did this folding here, it would be necessary to update the
7060 // MachineBasicBlock CFG, which is awkward.
7062 // Use SimplifySetCC to simplify SETCC's.
7063 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7064 CondLHS, CondRHS, CC->get(), SDLoc(N),
7066 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7068 // fold to a simpler setcc
7069 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7070 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7071 N->getOperand(0), Simp.getOperand(2),
7072 Simp.getOperand(0), Simp.getOperand(1),
7078 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7079 /// uses N as its base pointer and that N may be folded in the load / store
7080 /// addressing mode.
7081 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7083 const TargetLowering &TLI) {
7085 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7086 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7088 VT = Use->getValueType(0);
7089 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7090 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7092 VT = ST->getValue().getValueType();
7096 TargetLowering::AddrMode AM;
7097 if (N->getOpcode() == ISD::ADD) {
7098 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7101 AM.BaseOffs = Offset->getSExtValue();
7105 } else if (N->getOpcode() == ISD::SUB) {
7106 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7109 AM.BaseOffs = -Offset->getSExtValue();
7116 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7119 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7120 /// pre-indexed load / store when the base pointer is an add or subtract
7121 /// and it has other uses besides the load / store. After the
7122 /// transformation, the new indexed load / store has effectively folded
7123 /// the add / subtract in and all of its other uses are redirected to the
7124 /// new load / store.
7125 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7126 if (Level < AfterLegalizeDAG)
7132 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7133 if (LD->isIndexed())
7135 VT = LD->getMemoryVT();
7136 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7137 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7139 Ptr = LD->getBasePtr();
7140 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7141 if (ST->isIndexed())
7143 VT = ST->getMemoryVT();
7144 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7145 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7147 Ptr = ST->getBasePtr();
7153 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7154 // out. There is no reason to make this a preinc/predec.
7155 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7156 Ptr.getNode()->hasOneUse())
7159 // Ask the target to do addressing mode selection.
7162 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7163 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7166 // Backends without true r+i pre-indexed forms may need to pass a
7167 // constant base with a variable offset so that constant coercion
7168 // will work with the patterns in canonical form.
7169 bool Swapped = false;
7170 if (isa<ConstantSDNode>(BasePtr)) {
7171 std::swap(BasePtr, Offset);
7175 // Don't create a indexed load / store with zero offset.
7176 if (isa<ConstantSDNode>(Offset) &&
7177 cast<ConstantSDNode>(Offset)->isNullValue())
7180 // Try turning it into a pre-indexed load / store except when:
7181 // 1) The new base ptr is a frame index.
7182 // 2) If N is a store and the new base ptr is either the same as or is a
7183 // predecessor of the value being stored.
7184 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7185 // that would create a cycle.
7186 // 4) All uses are load / store ops that use it as old base ptr.
7188 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7189 // (plus the implicit offset) to a register to preinc anyway.
7190 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7195 SDValue Val = cast<StoreSDNode>(N)->getValue();
7196 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7200 // If the offset is a constant, there may be other adds of constants that
7201 // can be folded with this one. We should do this to avoid having to keep
7202 // a copy of the original base pointer.
7203 SmallVector<SDNode *, 16> OtherUses;
7204 if (isa<ConstantSDNode>(Offset))
7205 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7206 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7208 if (Use == Ptr.getNode())
7211 if (Use->isPredecessorOf(N))
7214 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7219 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7220 if (Op1.getNode() == BasePtr.getNode())
7221 std::swap(Op0, Op1);
7222 assert(Op0.getNode() == BasePtr.getNode() &&
7223 "Use of ADD/SUB but not an operand");
7225 if (!isa<ConstantSDNode>(Op1)) {
7230 // FIXME: In some cases, we can be smarter about this.
7231 if (Op1.getValueType() != Offset.getValueType()) {
7236 OtherUses.push_back(Use);
7240 std::swap(BasePtr, Offset);
7242 // Now check for #3 and #4.
7243 bool RealUse = false;
7245 // Caches for hasPredecessorHelper
7246 SmallPtrSet<const SDNode *, 32> Visited;
7247 SmallVector<const SDNode *, 16> Worklist;
7249 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7250 E = Ptr.getNode()->use_end(); I != E; ++I) {
7254 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7257 // If Ptr may be folded in addressing mode of other use, then it's
7258 // not profitable to do this transformation.
7259 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7268 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7269 BasePtr, Offset, AM);
7271 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7272 BasePtr, Offset, AM);
7275 DEBUG(dbgs() << "\nReplacing.4 ";
7277 dbgs() << "\nWith: ";
7278 Result.getNode()->dump(&DAG);
7280 WorkListRemover DeadNodes(*this);
7282 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7283 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7285 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7288 // Finally, since the node is now dead, remove it from the graph.
7292 std::swap(BasePtr, Offset);
7294 // Replace other uses of BasePtr that can be updated to use Ptr
7295 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7296 unsigned OffsetIdx = 1;
7297 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7299 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7300 BasePtr.getNode() && "Expected BasePtr operand");
7302 // We need to replace ptr0 in the following expression:
7303 // x0 * offset0 + y0 * ptr0 = t0
7305 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7307 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7308 // indexed load/store and the expresion that needs to be re-written.
7310 // Therefore, we have:
7311 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7313 ConstantSDNode *CN =
7314 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7316 APInt Offset0 = CN->getAPIntValue();
7317 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7319 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7320 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7321 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7322 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7324 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7326 APInt CNV = Offset0;
7327 if (X0 < 0) CNV = -CNV;
7328 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7329 else CNV = CNV - Offset1;
7331 // We can now generate the new expression.
7332 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7333 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7335 SDValue NewUse = DAG.getNode(Opcode,
7336 SDLoc(OtherUses[i]),
7337 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7338 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7339 removeFromWorkList(OtherUses[i]);
7340 DAG.DeleteNode(OtherUses[i]);
7343 // Replace the uses of Ptr with uses of the updated base value.
7344 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7345 removeFromWorkList(Ptr.getNode());
7346 DAG.DeleteNode(Ptr.getNode());
7351 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7352 /// add / sub of the base pointer node into a post-indexed load / store.
7353 /// The transformation folded the add / subtract into the new indexed
7354 /// load / store effectively and all of its uses are redirected to the
7355 /// new load / store.
7356 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7357 if (Level < AfterLegalizeDAG)
7363 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7364 if (LD->isIndexed())
7366 VT = LD->getMemoryVT();
7367 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7368 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7370 Ptr = LD->getBasePtr();
7371 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7372 if (ST->isIndexed())
7374 VT = ST->getMemoryVT();
7375 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7376 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7378 Ptr = ST->getBasePtr();
7384 if (Ptr.getNode()->hasOneUse())
7387 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7388 E = Ptr.getNode()->use_end(); I != E; ++I) {
7391 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7396 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7397 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7398 // Don't create a indexed load / store with zero offset.
7399 if (isa<ConstantSDNode>(Offset) &&
7400 cast<ConstantSDNode>(Offset)->isNullValue())
7403 // Try turning it into a post-indexed load / store except when
7404 // 1) All uses are load / store ops that use it as base ptr (and
7405 // it may be folded as addressing mmode).
7406 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7407 // nor a successor of N. Otherwise, if Op is folded that would
7410 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7414 bool TryNext = false;
7415 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7416 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7418 if (Use == Ptr.getNode())
7421 // If all the uses are load / store addresses, then don't do the
7423 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7424 bool RealUse = false;
7425 for (SDNode::use_iterator III = Use->use_begin(),
7426 EEE = Use->use_end(); III != EEE; ++III) {
7427 SDNode *UseUse = *III;
7428 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7443 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7444 SDValue Result = isLoad
7445 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7446 BasePtr, Offset, AM)
7447 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7448 BasePtr, Offset, AM);
7451 DEBUG(dbgs() << "\nReplacing.5 ";
7453 dbgs() << "\nWith: ";
7454 Result.getNode()->dump(&DAG);
7456 WorkListRemover DeadNodes(*this);
7458 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7459 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7461 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7464 // Finally, since the node is now dead, remove it from the graph.
7467 // Replace the uses of Use with uses of the updated base value.
7468 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7469 Result.getValue(isLoad ? 1 : 0));
7470 removeFromWorkList(Op);
7480 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7481 LoadSDNode *LD = cast<LoadSDNode>(N);
7482 SDValue Chain = LD->getChain();
7483 SDValue Ptr = LD->getBasePtr();
7485 // If load is not volatile and there are no uses of the loaded value (and
7486 // the updated indexed value in case of indexed loads), change uses of the
7487 // chain value into uses of the chain input (i.e. delete the dead load).
7488 if (!LD->isVolatile()) {
7489 if (N->getValueType(1) == MVT::Other) {
7491 if (!N->hasAnyUseOfValue(0)) {
7492 // It's not safe to use the two value CombineTo variant here. e.g.
7493 // v1, chain2 = load chain1, loc
7494 // v2, chain3 = load chain2, loc
7496 // Now we replace use of chain2 with chain1. This makes the second load
7497 // isomorphic to the one we are deleting, and thus makes this load live.
7498 DEBUG(dbgs() << "\nReplacing.6 ";
7500 dbgs() << "\nWith chain: ";
7501 Chain.getNode()->dump(&DAG);
7503 WorkListRemover DeadNodes(*this);
7504 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7506 if (N->use_empty()) {
7507 removeFromWorkList(N);
7511 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7515 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7516 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7517 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7518 DEBUG(dbgs() << "\nReplacing.7 ";
7520 dbgs() << "\nWith: ";
7521 Undef.getNode()->dump(&DAG);
7522 dbgs() << " and 2 other values\n");
7523 WorkListRemover DeadNodes(*this);
7524 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7525 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7526 DAG.getUNDEF(N->getValueType(1)));
7527 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7528 removeFromWorkList(N);
7530 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7535 // If this load is directly stored, replace the load value with the stored
7537 // TODO: Handle store large -> read small portion.
7538 // TODO: Handle TRUNCSTORE/LOADEXT
7539 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7540 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7541 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7542 if (PrevST->getBasePtr() == Ptr &&
7543 PrevST->getValue().getValueType() == N->getValueType(0))
7544 return CombineTo(N, Chain.getOperand(1), Chain);
7548 // Try to infer better alignment information than the load already has.
7549 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7550 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7551 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7553 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7554 LD->getValueType(0),
7555 Chain, Ptr, LD->getPointerInfo(),
7557 LD->isVolatile(), LD->isNonTemporal(), Align);
7558 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7563 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7564 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7566 // Walk up chain skipping non-aliasing memory nodes.
7567 SDValue BetterChain = FindBetterChain(N, Chain);
7569 // If there is a better chain.
7570 if (Chain != BetterChain) {
7573 // Replace the chain to void dependency.
7574 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7575 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7576 BetterChain, Ptr, LD->getPointerInfo(),
7577 LD->isVolatile(), LD->isNonTemporal(),
7578 LD->isInvariant(), LD->getAlignment());
7580 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7581 LD->getValueType(0),
7582 BetterChain, Ptr, LD->getPointerInfo(),
7585 LD->isNonTemporal(),
7586 LD->getAlignment());
7589 // Create token factor to keep old chain connected.
7590 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7591 MVT::Other, Chain, ReplLoad.getValue(1));
7593 // Make sure the new and old chains are cleaned up.
7594 AddToWorkList(Token.getNode());
7596 // Replace uses with load result and token factor. Don't add users
7598 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7602 // Try transforming N to an indexed load.
7603 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7604 return SDValue(N, 0);
7606 // Try to slice up N to more direct loads if the slices are mapped to
7607 // different register banks or pairing can take place.
7609 return SDValue(N, 0);
7615 /// \brief Helper structure used to slice a load in smaller loads.
7616 /// Basically a slice is obtained from the following sequence:
7617 /// Origin = load Ty1, Base
7618 /// Shift = srl Ty1 Origin, CstTy Amount
7619 /// Inst = trunc Shift to Ty2
7621 /// Then, it will be rewriten into:
7622 /// Slice = load SliceTy, Base + SliceOffset
7623 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7625 /// SliceTy is deduced from the number of bits that are actually used to
7627 struct LoadedSlice {
7628 /// \brief Helper structure used to compute the cost of a slice.
7630 /// Are we optimizing for code size.
7635 unsigned CrossRegisterBanksCopies;
7639 Cost(bool ForCodeSize = false)
7640 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7641 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7643 /// \brief Get the cost of one isolated slice.
7644 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7645 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7646 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7647 EVT TruncType = LS.Inst->getValueType(0);
7648 EVT LoadedType = LS.getLoadedType();
7649 if (TruncType != LoadedType &&
7650 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7654 /// \brief Account for slicing gain in the current cost.
7655 /// Slicing provide a few gains like removing a shift or a
7656 /// truncate. This method allows to grow the cost of the original
7657 /// load with the gain from this slice.
7658 void addSliceGain(const LoadedSlice &LS) {
7659 // Each slice saves a truncate.
7660 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7661 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7662 LS.Inst->getOperand(0).getValueType()))
7664 // If there is a shift amount, this slice gets rid of it.
7667 // If this slice can merge a cross register bank copy, account for it.
7668 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7669 ++CrossRegisterBanksCopies;
7672 Cost &operator+=(const Cost &RHS) {
7674 Truncates += RHS.Truncates;
7675 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7681 bool operator==(const Cost &RHS) const {
7682 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7683 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7684 ZExts == RHS.ZExts && Shift == RHS.Shift;
7687 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7689 bool operator<(const Cost &RHS) const {
7690 // Assume cross register banks copies are as expensive as loads.
7691 // FIXME: Do we want some more target hooks?
7692 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7693 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7694 // Unless we are optimizing for code size, consider the
7695 // expensive operation first.
7696 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7697 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7698 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7699 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7702 bool operator>(const Cost &RHS) const { return RHS < *this; }
7704 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7706 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7708 // The last instruction that represent the slice. This should be a
7709 // truncate instruction.
7711 // The original load instruction.
7713 // The right shift amount in bits from the original load.
7715 // The DAG from which Origin came from.
7716 // This is used to get some contextual information about legal types, etc.
7719 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7720 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7721 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7723 LoadedSlice(const LoadedSlice &LS)
7724 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7726 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7727 /// \return Result is \p BitWidth and has used bits set to 1 and
7728 /// not used bits set to 0.
7729 APInt getUsedBits() const {
7730 // Reproduce the trunc(lshr) sequence:
7731 // - Start from the truncated value.
7732 // - Zero extend to the desired bit width.
7734 assert(Origin && "No original load to compare against.");
7735 unsigned BitWidth = Origin->getValueSizeInBits(0);
7736 assert(Inst && "This slice is not bound to an instruction");
7737 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7738 "Extracted slice is bigger than the whole type!");
7739 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7740 UsedBits.setAllBits();
7741 UsedBits = UsedBits.zext(BitWidth);
7746 /// \brief Get the size of the slice to be loaded in bytes.
7747 unsigned getLoadedSize() const {
7748 unsigned SliceSize = getUsedBits().countPopulation();
7749 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7750 return SliceSize / 8;
7753 /// \brief Get the type that will be loaded for this slice.
7754 /// Note: This may not be the final type for the slice.
7755 EVT getLoadedType() const {
7756 assert(DAG && "Missing context");
7757 LLVMContext &Ctxt = *DAG->getContext();
7758 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7761 /// \brief Get the alignment of the load used for this slice.
7762 unsigned getAlignment() const {
7763 unsigned Alignment = Origin->getAlignment();
7764 unsigned Offset = getOffsetFromBase();
7766 Alignment = MinAlign(Alignment, Alignment + Offset);
7770 /// \brief Check if this slice can be rewritten with legal operations.
7771 bool isLegal() const {
7772 // An invalid slice is not legal.
7773 if (!Origin || !Inst || !DAG)
7776 // Offsets are for indexed load only, we do not handle that.
7777 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7780 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7782 // Check that the type is legal.
7783 EVT SliceType = getLoadedType();
7784 if (!TLI.isTypeLegal(SliceType))
7787 // Check that the load is legal for this type.
7788 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7791 // Check that the offset can be computed.
7792 // 1. Check its type.
7793 EVT PtrType = Origin->getBasePtr().getValueType();
7794 if (PtrType == MVT::Untyped || PtrType.isExtended())
7797 // 2. Check that it fits in the immediate.
7798 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7801 // 3. Check that the computation is legal.
7802 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7805 // Check that the zext is legal if it needs one.
7806 EVT TruncateType = Inst->getValueType(0);
7807 if (TruncateType != SliceType &&
7808 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7814 /// \brief Get the offset in bytes of this slice in the original chunk of
7816 /// \pre DAG != NULL.
7817 uint64_t getOffsetFromBase() const {
7818 assert(DAG && "Missing context.");
7820 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7821 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7822 uint64_t Offset = Shift / 8;
7823 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7824 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7825 "The size of the original loaded type is not a multiple of a"
7827 // If Offset is bigger than TySizeInBytes, it means we are loading all
7828 // zeros. This should have been optimized before in the process.
7829 assert(TySizeInBytes > Offset &&
7830 "Invalid shift amount for given loaded size");
7832 Offset = TySizeInBytes - Offset - getLoadedSize();
7836 /// \brief Generate the sequence of instructions to load the slice
7837 /// represented by this object and redirect the uses of this slice to
7838 /// this new sequence of instructions.
7839 /// \pre this->Inst && this->Origin are valid Instructions and this
7840 /// object passed the legal check: LoadedSlice::isLegal returned true.
7841 /// \return The last instruction of the sequence used to load the slice.
7842 SDValue loadSlice() const {
7843 assert(Inst && Origin && "Unable to replace a non-existing slice.");
7844 const SDValue &OldBaseAddr = Origin->getBasePtr();
7845 SDValue BaseAddr = OldBaseAddr;
7846 // Get the offset in that chunk of bytes w.r.t. the endianess.
7847 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
7848 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
7850 // BaseAddr = BaseAddr + Offset.
7851 EVT ArithType = BaseAddr.getValueType();
7852 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
7853 DAG->getConstant(Offset, ArithType));
7856 // Create the type of the loaded slice according to its size.
7857 EVT SliceType = getLoadedType();
7859 // Create the load for the slice.
7860 SDValue LastInst = DAG->getLoad(
7861 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
7862 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
7863 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
7864 // If the final type is not the same as the loaded type, this means that
7865 // we have to pad with zero. Create a zero extend for that.
7866 EVT FinalType = Inst->getValueType(0);
7867 if (SliceType != FinalType)
7869 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
7873 /// \brief Check if this slice can be merged with an expensive cross register
7874 /// bank copy. E.g.,
7876 /// f = bitcast i32 i to float
7877 bool canMergeExpensiveCrossRegisterBankCopy() const {
7878 if (!Inst || !Inst->hasOneUse())
7880 SDNode *Use = *Inst->use_begin();
7881 if (Use->getOpcode() != ISD::BITCAST)
7883 assert(DAG && "Missing context");
7884 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7885 EVT ResVT = Use->getValueType(0);
7886 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
7887 const TargetRegisterClass *ArgRC =
7888 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
7889 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
7892 // At this point, we know that we perform a cross-register-bank copy.
7893 // Check if it is expensive.
7894 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
7895 // Assume bitcasts are cheap, unless both register classes do not
7896 // explicitly share a common sub class.
7897 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
7900 // Check if it will be merged with the load.
7901 // 1. Check the alignment constraint.
7902 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
7903 ResVT.getTypeForEVT(*DAG->getContext()));
7905 if (RequiredAlignment > getAlignment())
7908 // 2. Check that the load is a legal operation for that type.
7909 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
7912 // 3. Check that we do not have a zext in the way.
7913 if (Inst->getValueType(0) != getLoadedType())
7921 /// \brief Sorts LoadedSlice according to their offset.
7922 struct LoadedSliceSorter {
7923 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
7924 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
7925 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
7929 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
7930 /// \p UsedBits looks like 0..0 1..1 0..0.
7931 static bool areUsedBitsDense(const APInt &UsedBits) {
7932 // If all the bits are one, this is dense!
7933 if (UsedBits.isAllOnesValue())
7936 // Get rid of the unused bits on the right.
7937 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
7938 // Get rid of the unused bits on the left.
7939 if (NarrowedUsedBits.countLeadingZeros())
7940 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
7941 // Check that the chunk of bits is completely used.
7942 return NarrowedUsedBits.isAllOnesValue();
7945 /// \brief Check whether or not \p First and \p Second are next to each other
7946 /// in memory. This means that there is no hole between the bits loaded
7947 /// by \p First and the bits loaded by \p Second.
7948 static bool areSlicesNextToEachOther(const LoadedSlice &First,
7949 const LoadedSlice &Second) {
7950 assert(First.Origin == Second.Origin && First.Origin &&
7951 "Unable to match different memory origins.");
7952 APInt UsedBits = First.getUsedBits();
7953 assert((UsedBits & Second.getUsedBits()) == 0 &&
7954 "Slices are not supposed to overlap.");
7955 UsedBits |= Second.getUsedBits();
7956 return areUsedBitsDense(UsedBits);
7959 /// \brief Adjust the \p GlobalLSCost according to the target
7960 /// paring capabilities and the layout of the slices.
7961 /// \pre \p GlobalLSCost should account for at least as many loads as
7962 /// there is in the slices in \p LoadedSlices.
7963 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
7964 LoadedSlice::Cost &GlobalLSCost) {
7965 unsigned NumberOfSlices = LoadedSlices.size();
7966 // If there is less than 2 elements, no pairing is possible.
7967 if (NumberOfSlices < 2)
7970 // Sort the slices so that elements that are likely to be next to each
7971 // other in memory are next to each other in the list.
7972 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
7973 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
7974 // First (resp. Second) is the first (resp. Second) potentially candidate
7975 // to be placed in a paired load.
7976 const LoadedSlice *First = NULL;
7977 const LoadedSlice *Second = NULL;
7978 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
7979 // Set the beginning of the pair.
7982 Second = &LoadedSlices[CurrSlice];
7984 // If First is NULL, it means we start a new pair.
7985 // Get to the next slice.
7989 EVT LoadedType = First->getLoadedType();
7991 // If the types of the slices are different, we cannot pair them.
7992 if (LoadedType != Second->getLoadedType())
7995 // Check if the target supplies paired loads for this type.
7996 unsigned RequiredAlignment = 0;
7997 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
7998 // move to the next pair, this type is hopeless.
8002 // Check if we meet the alignment requirement.
8003 if (RequiredAlignment > First->getAlignment())
8006 // Check that both loads are next to each other in memory.
8007 if (!areSlicesNextToEachOther(*First, *Second))
8010 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8011 --GlobalLSCost.Loads;
8012 // Move to the next pair.
8017 /// \brief Check the profitability of all involved LoadedSlice.
8018 /// Currently, it is considered profitable if there is exactly two
8019 /// involved slices (1) which are (2) next to each other in memory, and
8020 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8022 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8023 /// the elements themselves.
8025 /// FIXME: When the cost model will be mature enough, we can relax
8026 /// constraints (1) and (2).
8027 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8028 const APInt &UsedBits, bool ForCodeSize) {
8029 unsigned NumberOfSlices = LoadedSlices.size();
8030 if (StressLoadSlicing)
8031 return NumberOfSlices > 1;
8034 if (NumberOfSlices != 2)
8038 if (!areUsedBitsDense(UsedBits))
8042 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8043 // The original code has one big load.
8045 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8046 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8047 // Accumulate the cost of all the slices.
8048 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8049 GlobalSlicingCost += SliceCost;
8051 // Account as cost in the original configuration the gain obtained
8052 // with the current slices.
8053 OrigCost.addSliceGain(LS);
8056 // If the target supports paired load, adjust the cost accordingly.
8057 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8058 return OrigCost > GlobalSlicingCost;
8061 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8062 /// operations, split it in the various pieces being extracted.
8064 /// This sort of thing is introduced by SROA.
8065 /// This slicing takes care not to insert overlapping loads.
8066 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8067 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8068 if (Level < AfterLegalizeDAG)
8071 LoadSDNode *LD = cast<LoadSDNode>(N);
8072 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8073 !LD->getValueType(0).isInteger())
8076 // Keep track of already used bits to detect overlapping values.
8077 // In that case, we will just abort the transformation.
8078 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8080 SmallVector<LoadedSlice, 4> LoadedSlices;
8082 // Check if this load is used as several smaller chunks of bits.
8083 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8084 // of computation for each trunc.
8085 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8086 UI != UIEnd; ++UI) {
8087 // Skip the uses of the chain.
8088 if (UI.getUse().getResNo() != 0)
8094 // Check if this is a trunc(lshr).
8095 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8096 isa<ConstantSDNode>(User->getOperand(1))) {
8097 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8098 User = *User->use_begin();
8101 // At this point, User is a Truncate, iff we encountered, trunc or
8103 if (User->getOpcode() != ISD::TRUNCATE)
8106 // The width of the type must be a power of 2 and greater than 8-bits.
8107 // Otherwise the load cannot be represented in LLVM IR.
8108 // Moreover, if we shifted with a non 8-bits multiple, the slice
8109 // will be accross several bytes. We do not support that.
8110 unsigned Width = User->getValueSizeInBits(0);
8111 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8114 // Build the slice for this chain of computations.
8115 LoadedSlice LS(User, LD, Shift, &DAG);
8116 APInt CurrentUsedBits = LS.getUsedBits();
8118 // Check if this slice overlaps with another.
8119 if ((CurrentUsedBits & UsedBits) != 0)
8121 // Update the bits used globally.
8122 UsedBits |= CurrentUsedBits;
8124 // Check if the new slice would be legal.
8128 // Record the slice.
8129 LoadedSlices.push_back(LS);
8132 // Abort slicing if it does not seem to be profitable.
8133 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8138 // Rewrite each chain to use an independent load.
8139 // By construction, each chain can be represented by a unique load.
8141 // Prepare the argument for the new token factor for all the slices.
8142 SmallVector<SDValue, 8> ArgChains;
8143 for (SmallVectorImpl<LoadedSlice>::const_iterator
8144 LSIt = LoadedSlices.begin(),
8145 LSItEnd = LoadedSlices.end();
8146 LSIt != LSItEnd; ++LSIt) {
8147 SDValue SliceInst = LSIt->loadSlice();
8148 CombineTo(LSIt->Inst, SliceInst, true);
8149 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8150 SliceInst = SliceInst.getOperand(0);
8151 assert(SliceInst->getOpcode() == ISD::LOAD &&
8152 "It takes more than a zext to get to the loaded slice!!");
8153 ArgChains.push_back(SliceInst.getValue(1));
8156 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8157 &ArgChains[0], ArgChains.size());
8158 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8162 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8163 /// load is having specific bytes cleared out. If so, return the byte size
8164 /// being masked out and the shift amount.
8165 static std::pair<unsigned, unsigned>
8166 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8167 std::pair<unsigned, unsigned> Result(0, 0);
8169 // Check for the structure we're looking for.
8170 if (V->getOpcode() != ISD::AND ||
8171 !isa<ConstantSDNode>(V->getOperand(1)) ||
8172 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8175 // Check the chain and pointer.
8176 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8177 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8179 // The store should be chained directly to the load or be an operand of a
8181 if (LD == Chain.getNode())
8183 else if (Chain->getOpcode() != ISD::TokenFactor)
8184 return Result; // Fail.
8187 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8188 if (Chain->getOperand(i).getNode() == LD) {
8192 if (!isOk) return Result;
8195 // This only handles simple types.
8196 if (V.getValueType() != MVT::i16 &&
8197 V.getValueType() != MVT::i32 &&
8198 V.getValueType() != MVT::i64)
8201 // Check the constant mask. Invert it so that the bits being masked out are
8202 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8203 // follow the sign bit for uniformity.
8204 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8205 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8206 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8207 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8208 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8209 if (NotMaskLZ == 64) return Result; // All zero mask.
8211 // See if we have a continuous run of bits. If so, we have 0*1+0*
8212 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8215 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8216 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8217 NotMaskLZ -= 64-V.getValueSizeInBits();
8219 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8220 switch (MaskedBytes) {
8224 default: return Result; // All one mask, or 5-byte mask.
8227 // Verify that the first bit starts at a multiple of mask so that the access
8228 // is aligned the same as the access width.
8229 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8231 Result.first = MaskedBytes;
8232 Result.second = NotMaskTZ/8;
8237 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8238 /// provides a value as specified by MaskInfo. If so, replace the specified
8239 /// store with a narrower store of truncated IVal.
8241 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8242 SDValue IVal, StoreSDNode *St,
8244 unsigned NumBytes = MaskInfo.first;
8245 unsigned ByteShift = MaskInfo.second;
8246 SelectionDAG &DAG = DC->getDAG();
8248 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8249 // that uses this. If not, this is not a replacement.
8250 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8251 ByteShift*8, (ByteShift+NumBytes)*8);
8252 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8254 // Check that it is legal on the target to do this. It is legal if the new
8255 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8257 MVT VT = MVT::getIntegerVT(NumBytes*8);
8258 if (!DC->isTypeLegal(VT))
8261 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8262 // shifted by ByteShift and truncated down to NumBytes.
8264 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8265 DAG.getConstant(ByteShift*8,
8266 DC->getShiftAmountTy(IVal.getValueType())));
8268 // Figure out the offset for the store and the alignment of the access.
8270 unsigned NewAlign = St->getAlignment();
8272 if (DAG.getTargetLoweringInfo().isLittleEndian())
8273 StOffset = ByteShift;
8275 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8277 SDValue Ptr = St->getBasePtr();
8279 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8280 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8281 NewAlign = MinAlign(NewAlign, StOffset);
8284 // Truncate down to the new size.
8285 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8288 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8289 St->getPointerInfo().getWithOffset(StOffset),
8290 false, false, NewAlign).getNode();
8294 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8295 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8296 /// of the loaded bits, try narrowing the load and store if it would end up
8297 /// being a win for performance or code size.
8298 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8299 StoreSDNode *ST = cast<StoreSDNode>(N);
8300 if (ST->isVolatile())
8303 SDValue Chain = ST->getChain();
8304 SDValue Value = ST->getValue();
8305 SDValue Ptr = ST->getBasePtr();
8306 EVT VT = Value.getValueType();
8308 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8311 unsigned Opc = Value.getOpcode();
8313 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8314 // is a byte mask indicating a consecutive number of bytes, check to see if
8315 // Y is known to provide just those bytes. If so, we try to replace the
8316 // load + replace + store sequence with a single (narrower) store, which makes
8318 if (Opc == ISD::OR) {
8319 std::pair<unsigned, unsigned> MaskedLoad;
8320 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8321 if (MaskedLoad.first)
8322 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8323 Value.getOperand(1), ST,this))
8324 return SDValue(NewST, 0);
8326 // Or is commutative, so try swapping X and Y.
8327 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8328 if (MaskedLoad.first)
8329 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8330 Value.getOperand(0), ST,this))
8331 return SDValue(NewST, 0);
8334 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8335 Value.getOperand(1).getOpcode() != ISD::Constant)
8338 SDValue N0 = Value.getOperand(0);
8339 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8340 Chain == SDValue(N0.getNode(), 1)) {
8341 LoadSDNode *LD = cast<LoadSDNode>(N0);
8342 if (LD->getBasePtr() != Ptr ||
8343 LD->getPointerInfo().getAddrSpace() !=
8344 ST->getPointerInfo().getAddrSpace())
8347 // Find the type to narrow it the load / op / store to.
8348 SDValue N1 = Value.getOperand(1);
8349 unsigned BitWidth = N1.getValueSizeInBits();
8350 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8351 if (Opc == ISD::AND)
8352 Imm ^= APInt::getAllOnesValue(BitWidth);
8353 if (Imm == 0 || Imm.isAllOnesValue())
8355 unsigned ShAmt = Imm.countTrailingZeros();
8356 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8357 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8358 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8359 while (NewBW < BitWidth &&
8360 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8361 TLI.isNarrowingProfitable(VT, NewVT))) {
8362 NewBW = NextPowerOf2(NewBW);
8363 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8365 if (NewBW >= BitWidth)
8368 // If the lsb changed does not start at the type bitwidth boundary,
8369 // start at the previous one.
8371 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8372 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8373 std::min(BitWidth, ShAmt + NewBW));
8374 if ((Imm & Mask) == Imm) {
8375 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8376 if (Opc == ISD::AND)
8377 NewImm ^= APInt::getAllOnesValue(NewBW);
8378 uint64_t PtrOff = ShAmt / 8;
8379 // For big endian targets, we need to adjust the offset to the pointer to
8380 // load the correct bytes.
8381 if (TLI.isBigEndian())
8382 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8384 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8385 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8386 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8389 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8390 Ptr.getValueType(), Ptr,
8391 DAG.getConstant(PtrOff, Ptr.getValueType()));
8392 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8393 LD->getChain(), NewPtr,
8394 LD->getPointerInfo().getWithOffset(PtrOff),
8395 LD->isVolatile(), LD->isNonTemporal(),
8396 LD->isInvariant(), NewAlign);
8397 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8398 DAG.getConstant(NewImm, NewVT));
8399 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8401 ST->getPointerInfo().getWithOffset(PtrOff),
8402 false, false, NewAlign);
8404 AddToWorkList(NewPtr.getNode());
8405 AddToWorkList(NewLD.getNode());
8406 AddToWorkList(NewVal.getNode());
8407 WorkListRemover DeadNodes(*this);
8408 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8417 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8418 /// if the load value isn't used by any other operations, then consider
8419 /// transforming the pair to integer load / store operations if the target
8420 /// deems the transformation profitable.
8421 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8422 StoreSDNode *ST = cast<StoreSDNode>(N);
8423 SDValue Chain = ST->getChain();
8424 SDValue Value = ST->getValue();
8425 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8426 Value.hasOneUse() &&
8427 Chain == SDValue(Value.getNode(), 1)) {
8428 LoadSDNode *LD = cast<LoadSDNode>(Value);
8429 EVT VT = LD->getMemoryVT();
8430 if (!VT.isFloatingPoint() ||
8431 VT != ST->getMemoryVT() ||
8432 LD->isNonTemporal() ||
8433 ST->isNonTemporal() ||
8434 LD->getPointerInfo().getAddrSpace() != 0 ||
8435 ST->getPointerInfo().getAddrSpace() != 0)
8438 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8439 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8440 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8441 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8442 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8445 unsigned LDAlign = LD->getAlignment();
8446 unsigned STAlign = ST->getAlignment();
8447 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8448 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8449 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8452 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8453 LD->getChain(), LD->getBasePtr(),
8454 LD->getPointerInfo(),
8455 false, false, false, LDAlign);
8457 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8458 NewLD, ST->getBasePtr(),
8459 ST->getPointerInfo(),
8460 false, false, STAlign);
8462 AddToWorkList(NewLD.getNode());
8463 AddToWorkList(NewST.getNode());
8464 WorkListRemover DeadNodes(*this);
8465 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8473 /// Helper struct to parse and store a memory address as base + index + offset.
8474 /// We ignore sign extensions when it is safe to do so.
8475 /// The following two expressions are not equivalent. To differentiate we need
8476 /// to store whether there was a sign extension involved in the index
8478 /// (load (i64 add (i64 copyfromreg %c)
8479 /// (i64 signextend (add (i8 load %index)
8483 /// (load (i64 add (i64 copyfromreg %c)
8484 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8486 struct BaseIndexOffset {
8490 bool IsIndexSignExt;
8492 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8494 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8495 bool IsIndexSignExt) :
8496 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8498 bool equalBaseIndex(const BaseIndexOffset &Other) {
8499 return Other.Base == Base && Other.Index == Index &&
8500 Other.IsIndexSignExt == IsIndexSignExt;
8503 /// Parses tree in Ptr for base, index, offset addresses.
8504 static BaseIndexOffset match(SDValue Ptr) {
8505 bool IsIndexSignExt = false;
8507 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8508 // instruction, then it could be just the BASE or everything else we don't
8509 // know how to handle. Just use Ptr as BASE and give up.
8510 if (Ptr->getOpcode() != ISD::ADD)
8511 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8513 // We know that we have at least an ADD instruction. Try to pattern match
8514 // the simple case of BASE + OFFSET.
8515 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8516 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8517 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8521 // Inside a loop the current BASE pointer is calculated using an ADD and a
8522 // MUL instruction. In this case Ptr is the actual BASE pointer.
8523 // (i64 add (i64 %array_ptr)
8524 // (i64 mul (i64 %induction_var)
8525 // (i64 %element_size)))
8526 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8527 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8529 // Look at Base + Index + Offset cases.
8530 SDValue Base = Ptr->getOperand(0);
8531 SDValue IndexOffset = Ptr->getOperand(1);
8533 // Skip signextends.
8534 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8535 IndexOffset = IndexOffset->getOperand(0);
8536 IsIndexSignExt = true;
8539 // Either the case of Base + Index (no offset) or something else.
8540 if (IndexOffset->getOpcode() != ISD::ADD)
8541 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8543 // Now we have the case of Base + Index + offset.
8544 SDValue Index = IndexOffset->getOperand(0);
8545 SDValue Offset = IndexOffset->getOperand(1);
8547 if (!isa<ConstantSDNode>(Offset))
8548 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8550 // Ignore signextends.
8551 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8552 Index = Index->getOperand(0);
8553 IsIndexSignExt = true;
8554 } else IsIndexSignExt = false;
8556 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8557 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8561 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8562 /// is located in a sequence of memory operations connected by a chain.
8564 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8565 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8566 // Ptr to the mem node.
8567 LSBaseSDNode *MemNode;
8568 // Offset from the base ptr.
8569 int64_t OffsetFromBase;
8570 // What is the sequence number of this mem node.
8571 // Lowest mem operand in the DAG starts at zero.
8572 unsigned SequenceNum;
8575 /// Sorts store nodes in a link according to their offset from a shared
8577 struct ConsecutiveMemoryChainSorter {
8578 bool operator()(MemOpLink LHS, MemOpLink RHS) {
8579 return LHS.OffsetFromBase < RHS.OffsetFromBase;
8583 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8584 EVT MemVT = St->getMemoryVT();
8585 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8586 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8587 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8589 // Don't merge vectors into wider inputs.
8590 if (MemVT.isVector() || !MemVT.isSimple())
8593 // Perform an early exit check. Do not bother looking at stored values that
8594 // are not constants or loads.
8595 SDValue StoredVal = St->getValue();
8596 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8597 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8601 // Only look at ends of store sequences.
8602 SDValue Chain = SDValue(St, 1);
8603 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8606 // This holds the base pointer, index, and the offset in bytes from the base
8608 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8610 // We must have a base and an offset.
8611 if (!BasePtr.Base.getNode())
8614 // Do not handle stores to undef base pointers.
8615 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8618 // Save the LoadSDNodes that we find in the chain.
8619 // We need to make sure that these nodes do not interfere with
8620 // any of the store nodes.
8621 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8623 // Save the StoreSDNodes that we find in the chain.
8624 SmallVector<MemOpLink, 8> StoreNodes;
8626 // Walk up the chain and look for nodes with offsets from the same
8627 // base pointer. Stop when reaching an instruction with a different kind
8628 // or instruction which has a different base pointer.
8630 StoreSDNode *Index = St;
8632 // If the chain has more than one use, then we can't reorder the mem ops.
8633 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8636 // Find the base pointer and offset for this memory node.
8637 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8639 // Check that the base pointer is the same as the original one.
8640 if (!Ptr.equalBaseIndex(BasePtr))
8643 // Check that the alignment is the same.
8644 if (Index->getAlignment() != St->getAlignment())
8647 // The memory operands must not be volatile.
8648 if (Index->isVolatile() || Index->isIndexed())
8652 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8653 if (St->isTruncatingStore())
8656 // The stored memory type must be the same.
8657 if (Index->getMemoryVT() != MemVT)
8660 // We do not allow unaligned stores because we want to prevent overriding
8662 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8665 // We found a potential memory operand to merge.
8666 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8668 // Find the next memory operand in the chain. If the next operand in the
8669 // chain is a store then move up and continue the scan with the next
8670 // memory operand. If the next operand is a load save it and use alias
8671 // information to check if it interferes with anything.
8672 SDNode *NextInChain = Index->getChain().getNode();
8674 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8675 // We found a store node. Use it for the next iteration.
8678 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8679 // Save the load node for later. Continue the scan.
8680 AliasLoadNodes.push_back(Ldn);
8681 NextInChain = Ldn->getChain().getNode();
8690 // Check if there is anything to merge.
8691 if (StoreNodes.size() < 2)
8694 // Sort the memory operands according to their distance from the base pointer.
8695 std::sort(StoreNodes.begin(), StoreNodes.end(),
8696 ConsecutiveMemoryChainSorter());
8698 // Scan the memory operations on the chain and find the first non-consecutive
8699 // store memory address.
8700 unsigned LastConsecutiveStore = 0;
8701 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8702 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8704 // Check that the addresses are consecutive starting from the second
8705 // element in the list of stores.
8707 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8708 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8713 // Check if this store interferes with any of the loads that we found.
8714 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8715 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8719 // We found a load that alias with this store. Stop the sequence.
8723 // Mark this node as useful.
8724 LastConsecutiveStore = i;
8727 // The node with the lowest store address.
8728 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8730 // Store the constants into memory as one consecutive store.
8732 unsigned LastLegalType = 0;
8733 unsigned LastLegalVectorType = 0;
8734 bool NonZero = false;
8735 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8736 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8737 SDValue StoredVal = St->getValue();
8739 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8740 NonZero |= !C->isNullValue();
8741 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8742 NonZero |= !C->getConstantFPValue()->isNullValue();
8748 // Find a legal type for the constant store.
8749 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8750 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8751 if (TLI.isTypeLegal(StoreTy))
8752 LastLegalType = i+1;
8753 // Or check whether a truncstore is legal.
8754 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8755 TargetLowering::TypePromoteInteger) {
8756 EVT LegalizedStoredValueTy =
8757 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8758 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8759 LastLegalType = i+1;
8762 // Find a legal type for the vector store.
8763 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8764 if (TLI.isTypeLegal(Ty))
8765 LastLegalVectorType = i + 1;
8768 // We only use vectors if the constant is known to be zero and the
8769 // function is not marked with the noimplicitfloat attribute.
8770 if (NonZero || NoVectors)
8771 LastLegalVectorType = 0;
8773 // Check if we found a legal integer type to store.
8774 if (LastLegalType == 0 && LastLegalVectorType == 0)
8777 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8778 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8780 // Make sure we have something to merge.
8784 unsigned EarliestNodeUsed = 0;
8785 for (unsigned i=0; i < NumElem; ++i) {
8786 // Find a chain for the new wide-store operand. Notice that some
8787 // of the store nodes that we found may not be selected for inclusion
8788 // in the wide store. The chain we use needs to be the chain of the
8789 // earliest store node which is *used* and replaced by the wide store.
8790 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8791 EarliestNodeUsed = i;
8794 // The earliest Node in the DAG.
8795 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8796 SDLoc DL(StoreNodes[0].MemNode);
8800 // Find a legal type for the vector store.
8801 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8802 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8803 StoredVal = DAG.getConstant(0, Ty);
8805 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8806 APInt StoreInt(StoreBW, 0);
8808 // Construct a single integer constant which is made of the smaller
8810 bool IsLE = TLI.isLittleEndian();
8811 for (unsigned i = 0; i < NumElem ; ++i) {
8812 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8813 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8814 SDValue Val = St->getValue();
8815 StoreInt<<=ElementSizeBytes*8;
8816 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8817 StoreInt|=C->getAPIntValue().zext(StoreBW);
8818 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8819 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8821 assert(false && "Invalid constant element type");
8825 // Create the new Load and Store operations.
8826 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8827 StoredVal = DAG.getConstant(StoreInt, StoreTy);
8830 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8831 FirstInChain->getBasePtr(),
8832 FirstInChain->getPointerInfo(),
8834 FirstInChain->getAlignment());
8836 // Replace the first store with the new store
8837 CombineTo(EarliestOp, NewStore);
8838 // Erase all other stores.
8839 for (unsigned i = 0; i < NumElem ; ++i) {
8840 if (StoreNodes[i].MemNode == EarliestOp)
8842 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8843 // ReplaceAllUsesWith will replace all uses that existed when it was
8844 // called, but graph optimizations may cause new ones to appear. For
8845 // example, the case in pr14333 looks like
8847 // St's chain -> St -> another store -> X
8849 // And the only difference from St to the other store is the chain.
8850 // When we change it's chain to be St's chain they become identical,
8851 // get CSEed and the net result is that X is now a use of St.
8852 // Since we know that St is redundant, just iterate.
8853 while (!St->use_empty())
8854 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8855 removeFromWorkList(St);
8862 // Below we handle the case of multiple consecutive stores that
8863 // come from multiple consecutive loads. We merge them into a single
8864 // wide load and a single wide store.
8866 // Look for load nodes which are used by the stored values.
8867 SmallVector<MemOpLink, 8> LoadNodes;
8869 // Find acceptable loads. Loads need to have the same chain (token factor),
8870 // must not be zext, volatile, indexed, and they must be consecutive.
8871 BaseIndexOffset LdBasePtr;
8872 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8873 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8874 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8877 // Loads must only have one use.
8878 if (!Ld->hasNUsesOfValue(1, 0))
8881 // Check that the alignment is the same as the stores.
8882 if (Ld->getAlignment() != St->getAlignment())
8885 // The memory operands must not be volatile.
8886 if (Ld->isVolatile() || Ld->isIndexed())
8889 // We do not accept ext loads.
8890 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8893 // The stored memory type must be the same.
8894 if (Ld->getMemoryVT() != MemVT)
8897 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8898 // If this is not the first ptr that we check.
8899 if (LdBasePtr.Base.getNode()) {
8900 // The base ptr must be the same.
8901 if (!LdPtr.equalBaseIndex(LdBasePtr))
8904 // Check that all other base pointers are the same as this one.
8908 // We found a potential memory operand to merge.
8909 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8912 if (LoadNodes.size() < 2)
8915 // Scan the memory operations on the chain and find the first non-consecutive
8916 // load memory address. These variables hold the index in the store node
8918 unsigned LastConsecutiveLoad = 0;
8919 // This variable refers to the size and not index in the array.
8920 unsigned LastLegalVectorType = 0;
8921 unsigned LastLegalIntegerType = 0;
8922 StartAddress = LoadNodes[0].OffsetFromBase;
8923 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8924 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8925 // All loads much share the same chain.
8926 if (LoadNodes[i].MemNode->getChain() != FirstChain)
8929 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8930 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8932 LastConsecutiveLoad = i;
8934 // Find a legal type for the vector store.
8935 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8936 if (TLI.isTypeLegal(StoreTy))
8937 LastLegalVectorType = i + 1;
8939 // Find a legal type for the integer store.
8940 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8941 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8942 if (TLI.isTypeLegal(StoreTy))
8943 LastLegalIntegerType = i + 1;
8944 // Or check whether a truncstore and extload is legal.
8945 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8946 TargetLowering::TypePromoteInteger) {
8947 EVT LegalizedStoredValueTy =
8948 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8949 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8950 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8951 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8952 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8953 LastLegalIntegerType = i+1;
8957 // Only use vector types if the vector type is larger than the integer type.
8958 // If they are the same, use integers.
8959 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8960 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8962 // We add +1 here because the LastXXX variables refer to location while
8963 // the NumElem refers to array/index size.
8964 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8965 NumElem = std::min(LastLegalType, NumElem);
8970 // The earliest Node in the DAG.
8971 unsigned EarliestNodeUsed = 0;
8972 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8973 for (unsigned i=1; i<NumElem; ++i) {
8974 // Find a chain for the new wide-store operand. Notice that some
8975 // of the store nodes that we found may not be selected for inclusion
8976 // in the wide store. The chain we use needs to be the chain of the
8977 // earliest store node which is *used* and replaced by the wide store.
8978 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8979 EarliestNodeUsed = i;
8982 // Find if it is better to use vectors or integers to load and store
8986 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8988 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8989 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8992 SDLoc LoadDL(LoadNodes[0].MemNode);
8993 SDLoc StoreDL(StoreNodes[0].MemNode);
8995 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8996 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8997 FirstLoad->getChain(),
8998 FirstLoad->getBasePtr(),
8999 FirstLoad->getPointerInfo(),
9000 false, false, false,
9001 FirstLoad->getAlignment());
9003 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9004 FirstInChain->getBasePtr(),
9005 FirstInChain->getPointerInfo(), false, false,
9006 FirstInChain->getAlignment());
9008 // Replace one of the loads with the new load.
9009 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9010 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9011 SDValue(NewLoad.getNode(), 1));
9013 // Remove the rest of the load chains.
9014 for (unsigned i = 1; i < NumElem ; ++i) {
9015 // Replace all chain users of the old load nodes with the chain of the new
9017 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9018 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9021 // Replace the first store with the new store.
9022 CombineTo(EarliestOp, NewStore);
9023 // Erase all other stores.
9024 for (unsigned i = 0; i < NumElem ; ++i) {
9025 // Remove all Store nodes.
9026 if (StoreNodes[i].MemNode == EarliestOp)
9028 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9029 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9030 removeFromWorkList(St);
9037 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9038 StoreSDNode *ST = cast<StoreSDNode>(N);
9039 SDValue Chain = ST->getChain();
9040 SDValue Value = ST->getValue();
9041 SDValue Ptr = ST->getBasePtr();
9043 // If this is a store of a bit convert, store the input value if the
9044 // resultant store does not need a higher alignment than the original.
9045 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9046 ST->isUnindexed()) {
9047 unsigned OrigAlign = ST->getAlignment();
9048 EVT SVT = Value.getOperand(0).getValueType();
9049 unsigned Align = TLI.getDataLayout()->
9050 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9051 if (Align <= OrigAlign &&
9052 ((!LegalOperations && !ST->isVolatile()) ||
9053 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9054 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9055 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9056 ST->isNonTemporal(), OrigAlign);
9059 // Turn 'store undef, Ptr' -> nothing.
9060 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9063 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9064 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9065 // NOTE: If the original store is volatile, this transform must not increase
9066 // the number of stores. For example, on x86-32 an f64 can be stored in one
9067 // processor operation but an i64 (which is not legal) requires two. So the
9068 // transform should not be done in this case.
9069 if (Value.getOpcode() != ISD::TargetConstantFP) {
9071 switch (CFP->getSimpleValueType(0).SimpleTy) {
9072 default: llvm_unreachable("Unknown FP type");
9073 case MVT::f16: // We don't do this for these yet.
9079 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9080 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9081 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9082 bitcastToAPInt().getZExtValue(), MVT::i32);
9083 return DAG.getStore(Chain, SDLoc(N), Tmp,
9084 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9085 ST->isNonTemporal(), ST->getAlignment());
9089 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9090 !ST->isVolatile()) ||
9091 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9092 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9093 getZExtValue(), MVT::i64);
9094 return DAG.getStore(Chain, SDLoc(N), Tmp,
9095 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9096 ST->isNonTemporal(), ST->getAlignment());
9099 if (!ST->isVolatile() &&
9100 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9101 // Many FP stores are not made apparent until after legalize, e.g. for
9102 // argument passing. Since this is so common, custom legalize the
9103 // 64-bit integer store into two 32-bit stores.
9104 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9105 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9106 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9107 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9109 unsigned Alignment = ST->getAlignment();
9110 bool isVolatile = ST->isVolatile();
9111 bool isNonTemporal = ST->isNonTemporal();
9113 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9114 Ptr, ST->getPointerInfo(),
9115 isVolatile, isNonTemporal,
9116 ST->getAlignment());
9117 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9118 DAG.getConstant(4, Ptr.getValueType()));
9119 Alignment = MinAlign(Alignment, 4U);
9120 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9121 Ptr, ST->getPointerInfo().getWithOffset(4),
9122 isVolatile, isNonTemporal,
9124 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9133 // Try to infer better alignment information than the store already has.
9134 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9135 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9136 if (Align > ST->getAlignment())
9137 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9138 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9139 ST->isVolatile(), ST->isNonTemporal(), Align);
9143 // Try transforming a pair floating point load / store ops to integer
9144 // load / store ops.
9145 SDValue NewST = TransformFPLoadStorePair(N);
9146 if (NewST.getNode())
9149 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9150 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9152 // Walk up chain skipping non-aliasing memory nodes.
9153 SDValue BetterChain = FindBetterChain(N, Chain);
9155 // If there is a better chain.
9156 if (Chain != BetterChain) {
9159 // Replace the chain to avoid dependency.
9160 if (ST->isTruncatingStore()) {
9161 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9162 ST->getPointerInfo(),
9163 ST->getMemoryVT(), ST->isVolatile(),
9164 ST->isNonTemporal(), ST->getAlignment());
9166 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9167 ST->getPointerInfo(),
9168 ST->isVolatile(), ST->isNonTemporal(),
9169 ST->getAlignment());
9172 // Create token to keep both nodes around.
9173 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9174 MVT::Other, Chain, ReplStore);
9176 // Make sure the new and old chains are cleaned up.
9177 AddToWorkList(Token.getNode());
9179 // Don't add users to work list.
9180 return CombineTo(N, Token, false);
9184 // Try transforming N to an indexed store.
9185 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9186 return SDValue(N, 0);
9188 // FIXME: is there such a thing as a truncating indexed store?
9189 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9190 Value.getValueType().isInteger()) {
9191 // See if we can simplify the input to this truncstore with knowledge that
9192 // only the low bits are being used. For example:
9193 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9195 GetDemandedBits(Value,
9196 APInt::getLowBitsSet(
9197 Value.getValueType().getScalarType().getSizeInBits(),
9198 ST->getMemoryVT().getScalarType().getSizeInBits()));
9199 AddToWorkList(Value.getNode());
9200 if (Shorter.getNode())
9201 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9202 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9203 ST->isVolatile(), ST->isNonTemporal(),
9204 ST->getAlignment());
9206 // Otherwise, see if we can simplify the operation with
9207 // SimplifyDemandedBits, which only works if the value has a single use.
9208 if (SimplifyDemandedBits(Value,
9209 APInt::getLowBitsSet(
9210 Value.getValueType().getScalarType().getSizeInBits(),
9211 ST->getMemoryVT().getScalarType().getSizeInBits())))
9212 return SDValue(N, 0);
9215 // If this is a load followed by a store to the same location, then the store
9217 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9218 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9219 ST->isUnindexed() && !ST->isVolatile() &&
9220 // There can't be any side effects between the load and store, such as
9222 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9223 // The store is dead, remove it.
9228 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9229 // truncating store. We can do this even if this is already a truncstore.
9230 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9231 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9232 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9233 ST->getMemoryVT())) {
9234 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9235 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9236 ST->isVolatile(), ST->isNonTemporal(),
9237 ST->getAlignment());
9240 // Only perform this optimization before the types are legal, because we
9241 // don't want to perform this optimization on every DAGCombine invocation.
9243 bool EverChanged = false;
9246 // There can be multiple store sequences on the same chain.
9247 // Keep trying to merge store sequences until we are unable to do so
9248 // or until we merge the last store on the chain.
9249 bool Changed = MergeConsecutiveStores(ST);
9250 EverChanged |= Changed;
9251 if (!Changed) break;
9252 } while (ST->getOpcode() != ISD::DELETED_NODE);
9255 return SDValue(N, 0);
9258 return ReduceLoadOpStoreWidth(N);
9261 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9262 SDValue InVec = N->getOperand(0);
9263 SDValue InVal = N->getOperand(1);
9264 SDValue EltNo = N->getOperand(2);
9267 // If the inserted element is an UNDEF, just use the input vector.
9268 if (InVal.getOpcode() == ISD::UNDEF)
9271 EVT VT = InVec.getValueType();
9273 // If we can't generate a legal BUILD_VECTOR, exit
9274 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9277 // Check that we know which element is being inserted
9278 if (!isa<ConstantSDNode>(EltNo))
9280 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9282 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9283 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9285 SmallVector<SDValue, 8> Ops;
9286 // Do not combine these two vectors if the output vector will not replace
9287 // the input vector.
9288 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9289 Ops.append(InVec.getNode()->op_begin(),
9290 InVec.getNode()->op_end());
9291 } else if (InVec.getOpcode() == ISD::UNDEF) {
9292 unsigned NElts = VT.getVectorNumElements();
9293 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9298 // Insert the element
9299 if (Elt < Ops.size()) {
9300 // All the operands of BUILD_VECTOR must have the same type;
9301 // we enforce that here.
9302 EVT OpVT = Ops[0].getValueType();
9303 if (InVal.getValueType() != OpVT)
9304 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9305 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9306 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9310 // Return the new vector
9311 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9312 VT, &Ops[0], Ops.size());
9315 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9316 // (vextract (scalar_to_vector val, 0) -> val
9317 SDValue InVec = N->getOperand(0);
9318 EVT VT = InVec.getValueType();
9319 EVT NVT = N->getValueType(0);
9321 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9322 // Check if the result type doesn't match the inserted element type. A
9323 // SCALAR_TO_VECTOR may truncate the inserted element and the
9324 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9325 SDValue InOp = InVec.getOperand(0);
9326 if (InOp.getValueType() != NVT) {
9327 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9328 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9333 SDValue EltNo = N->getOperand(1);
9334 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9336 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9337 // We only perform this optimization before the op legalization phase because
9338 // we may introduce new vector instructions which are not backed by TD
9339 // patterns. For example on AVX, extracting elements from a wide vector
9340 // without using extract_subvector.
9341 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9342 && ConstEltNo && !LegalOperations) {
9343 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9344 int NumElem = VT.getVectorNumElements();
9345 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9346 // Find the new index to extract from.
9347 int OrigElt = SVOp->getMaskElt(Elt);
9349 // Extracting an undef index is undef.
9351 return DAG.getUNDEF(NVT);
9353 // Select the right vector half to extract from.
9354 if (OrigElt < NumElem) {
9355 InVec = InVec->getOperand(0);
9357 InVec = InVec->getOperand(1);
9361 EVT IndexTy = TLI.getVectorIdxTy();
9362 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9363 InVec, DAG.getConstant(OrigElt, IndexTy));
9366 // Perform only after legalization to ensure build_vector / vector_shuffle
9367 // optimizations have already been done.
9368 if (!LegalOperations) return SDValue();
9370 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9371 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9372 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9375 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9376 bool NewLoad = false;
9377 bool BCNumEltsChanged = false;
9378 EVT ExtVT = VT.getVectorElementType();
9381 // If the result of load has to be truncated, then it's not necessarily
9383 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9386 if (InVec.getOpcode() == ISD::BITCAST) {
9387 // Don't duplicate a load with other uses.
9388 if (!InVec.hasOneUse())
9391 EVT BCVT = InVec.getOperand(0).getValueType();
9392 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9394 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9395 BCNumEltsChanged = true;
9396 InVec = InVec.getOperand(0);
9397 ExtVT = BCVT.getVectorElementType();
9401 LoadSDNode *LN0 = NULL;
9402 const ShuffleVectorSDNode *SVN = NULL;
9403 if (ISD::isNormalLoad(InVec.getNode())) {
9404 LN0 = cast<LoadSDNode>(InVec);
9405 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9406 InVec.getOperand(0).getValueType() == ExtVT &&
9407 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9408 // Don't duplicate a load with other uses.
9409 if (!InVec.hasOneUse())
9412 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9413 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9414 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9416 // (load $addr+1*size)
9418 // Don't duplicate a load with other uses.
9419 if (!InVec.hasOneUse())
9422 // If the bit convert changed the number of elements, it is unsafe
9423 // to examine the mask.
9424 if (BCNumEltsChanged)
9427 // Select the input vector, guarding against out of range extract vector.
9428 unsigned NumElems = VT.getVectorNumElements();
9429 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9430 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9432 if (InVec.getOpcode() == ISD::BITCAST) {
9433 // Don't duplicate a load with other uses.
9434 if (!InVec.hasOneUse())
9437 InVec = InVec.getOperand(0);
9439 if (ISD::isNormalLoad(InVec.getNode())) {
9440 LN0 = cast<LoadSDNode>(InVec);
9441 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9445 // Make sure we found a non-volatile load and the extractelement is
9447 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9450 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9452 return DAG.getUNDEF(LVT);
9454 unsigned Align = LN0->getAlignment();
9456 // Check the resultant load doesn't need a higher alignment than the
9460 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9462 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9468 SDValue NewPtr = LN0->getBasePtr();
9469 unsigned PtrOff = 0;
9472 PtrOff = LVT.getSizeInBits() * Elt / 8;
9473 EVT PtrType = NewPtr.getValueType();
9474 if (TLI.isBigEndian())
9475 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9476 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9477 DAG.getConstant(PtrOff, PtrType));
9480 // The replacement we need to do here is a little tricky: we need to
9481 // replace an extractelement of a load with a load.
9482 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9483 // Note that this replacement assumes that the extractvalue is the only
9484 // use of the load; that's okay because we don't want to perform this
9485 // transformation in other cases anyway.
9488 if (NVT.bitsGT(LVT)) {
9489 // If the result type of vextract is wider than the load, then issue an
9490 // extending load instead.
9491 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9492 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9493 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9494 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9495 LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
9496 Chain = Load.getValue(1);
9498 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9499 LN0->getPointerInfo().getWithOffset(PtrOff),
9500 LN0->isVolatile(), LN0->isNonTemporal(),
9501 LN0->isInvariant(), Align);
9502 Chain = Load.getValue(1);
9503 if (NVT.bitsLT(LVT))
9504 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9506 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9508 WorkListRemover DeadNodes(*this);
9509 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9510 SDValue To[] = { Load, Chain };
9511 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9512 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9513 // worklist explicitly as well.
9514 AddToWorkList(Load.getNode());
9515 AddUsersToWorkList(Load.getNode()); // Add users too
9516 // Make sure to revisit this node to clean it up; it will usually be dead.
9518 return SDValue(N, 0);
9524 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9525 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9526 // We perform this optimization post type-legalization because
9527 // the type-legalizer often scalarizes integer-promoted vectors.
9528 // Performing this optimization before may create bit-casts which
9529 // will be type-legalized to complex code sequences.
9530 // We perform this optimization only before the operation legalizer because we
9531 // may introduce illegal operations.
9532 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9535 unsigned NumInScalars = N->getNumOperands();
9537 EVT VT = N->getValueType(0);
9539 // Check to see if this is a BUILD_VECTOR of a bunch of values
9540 // which come from any_extend or zero_extend nodes. If so, we can create
9541 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9542 // optimizations. We do not handle sign-extend because we can't fill the sign
9544 EVT SourceType = MVT::Other;
9545 bool AllAnyExt = true;
9547 for (unsigned i = 0; i != NumInScalars; ++i) {
9548 SDValue In = N->getOperand(i);
9549 // Ignore undef inputs.
9550 if (In.getOpcode() == ISD::UNDEF) continue;
9552 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9553 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9555 // Abort if the element is not an extension.
9556 if (!ZeroExt && !AnyExt) {
9557 SourceType = MVT::Other;
9561 // The input is a ZeroExt or AnyExt. Check the original type.
9562 EVT InTy = In.getOperand(0).getValueType();
9564 // Check that all of the widened source types are the same.
9565 if (SourceType == MVT::Other)
9568 else if (InTy != SourceType) {
9569 // Multiple income types. Abort.
9570 SourceType = MVT::Other;
9574 // Check if all of the extends are ANY_EXTENDs.
9575 AllAnyExt &= AnyExt;
9578 // In order to have valid types, all of the inputs must be extended from the
9579 // same source type and all of the inputs must be any or zero extend.
9580 // Scalar sizes must be a power of two.
9581 EVT OutScalarTy = VT.getScalarType();
9582 bool ValidTypes = SourceType != MVT::Other &&
9583 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9584 isPowerOf2_32(SourceType.getSizeInBits());
9586 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9587 // turn into a single shuffle instruction.
9591 bool isLE = TLI.isLittleEndian();
9592 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9593 assert(ElemRatio > 1 && "Invalid element size ratio");
9594 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9595 DAG.getConstant(0, SourceType);
9597 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9598 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9600 // Populate the new build_vector
9601 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9602 SDValue Cast = N->getOperand(i);
9603 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9604 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9605 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9607 if (Cast.getOpcode() == ISD::UNDEF)
9608 In = DAG.getUNDEF(SourceType);
9610 In = Cast->getOperand(0);
9611 unsigned Index = isLE ? (i * ElemRatio) :
9612 (i * ElemRatio + (ElemRatio - 1));
9614 assert(Index < Ops.size() && "Invalid index");
9618 // The type of the new BUILD_VECTOR node.
9619 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9620 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9621 "Invalid vector size");
9622 // Check if the new vector type is legal.
9623 if (!isTypeLegal(VecVT)) return SDValue();
9625 // Make the new BUILD_VECTOR.
9626 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9628 // The new BUILD_VECTOR node has the potential to be further optimized.
9629 AddToWorkList(BV.getNode());
9630 // Bitcast to the desired type.
9631 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9634 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9635 EVT VT = N->getValueType(0);
9637 unsigned NumInScalars = N->getNumOperands();
9640 EVT SrcVT = MVT::Other;
9641 unsigned Opcode = ISD::DELETED_NODE;
9642 unsigned NumDefs = 0;
9644 for (unsigned i = 0; i != NumInScalars; ++i) {
9645 SDValue In = N->getOperand(i);
9646 unsigned Opc = In.getOpcode();
9648 if (Opc == ISD::UNDEF)
9651 // If all scalar values are floats and converted from integers.
9652 if (Opcode == ISD::DELETED_NODE &&
9653 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9660 EVT InVT = In.getOperand(0).getValueType();
9662 // If all scalar values are typed differently, bail out. It's chosen to
9663 // simplify BUILD_VECTOR of integer types.
9664 if (SrcVT == MVT::Other)
9671 // If the vector has just one element defined, it's not worth to fold it into
9672 // a vectorized one.
9676 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9677 && "Should only handle conversion from integer to float.");
9678 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9680 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9682 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9685 SmallVector<SDValue, 8> Opnds;
9686 for (unsigned i = 0; i != NumInScalars; ++i) {
9687 SDValue In = N->getOperand(i);
9689 if (In.getOpcode() == ISD::UNDEF)
9690 Opnds.push_back(DAG.getUNDEF(SrcVT));
9692 Opnds.push_back(In.getOperand(0));
9694 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9695 &Opnds[0], Opnds.size());
9696 AddToWorkList(BV.getNode());
9698 return DAG.getNode(Opcode, dl, VT, BV);
9701 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9702 unsigned NumInScalars = N->getNumOperands();
9704 EVT VT = N->getValueType(0);
9706 // A vector built entirely of undefs is undef.
9707 if (ISD::allOperandsUndef(N))
9708 return DAG.getUNDEF(VT);
9710 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9714 V = reduceBuildVecConvertToConvertBuildVec(N);
9718 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9719 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9720 // at most two distinct vectors, turn this into a shuffle node.
9722 // May only combine to shuffle after legalize if shuffle is legal.
9723 if (LegalOperations &&
9724 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9727 SDValue VecIn1, VecIn2;
9728 for (unsigned i = 0; i != NumInScalars; ++i) {
9729 // Ignore undef inputs.
9730 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9732 // If this input is something other than a EXTRACT_VECTOR_ELT with a
9733 // constant index, bail out.
9734 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9735 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9736 VecIn1 = VecIn2 = SDValue(0, 0);
9740 // We allow up to two distinct input vectors.
9741 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9742 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9745 if (VecIn1.getNode() == 0) {
9746 VecIn1 = ExtractedFromVec;
9747 } else if (VecIn2.getNode() == 0) {
9748 VecIn2 = ExtractedFromVec;
9751 VecIn1 = VecIn2 = SDValue(0, 0);
9756 // If everything is good, we can make a shuffle operation.
9757 if (VecIn1.getNode()) {
9758 SmallVector<int, 8> Mask;
9759 for (unsigned i = 0; i != NumInScalars; ++i) {
9760 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9765 // If extracting from the first vector, just use the index directly.
9766 SDValue Extract = N->getOperand(i);
9767 SDValue ExtVal = Extract.getOperand(1);
9768 if (Extract.getOperand(0) == VecIn1) {
9769 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9770 if (ExtIndex > VT.getVectorNumElements())
9773 Mask.push_back(ExtIndex);
9777 // Otherwise, use InIdx + VecSize
9778 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9779 Mask.push_back(Idx+NumInScalars);
9782 // We can't generate a shuffle node with mismatched input and output types.
9783 // Attempt to transform a single input vector to the correct type.
9784 if ((VT != VecIn1.getValueType())) {
9785 // We don't support shuffeling between TWO values of different types.
9786 if (VecIn2.getNode() != 0)
9789 // We only support widening of vectors which are half the size of the
9790 // output registers. For example XMM->YMM widening on X86 with AVX.
9791 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9794 // If the input vector type has a different base type to the output
9795 // vector type, bail out.
9796 if (VecIn1.getValueType().getVectorElementType() !=
9797 VT.getVectorElementType())
9800 // Widen the input vector by adding undef values.
9801 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9802 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9805 // If VecIn2 is unused then change it to undef.
9806 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9808 // Check that we were able to transform all incoming values to the same
9810 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9811 VecIn1.getValueType() != VT)
9814 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9815 if (!isTypeLegal(VT))
9818 // Return the new VECTOR_SHUFFLE node.
9822 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9828 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9829 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9830 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9831 // inputs come from at most two distinct vectors, turn this into a shuffle
9834 // If we only have one input vector, we don't need to do any concatenation.
9835 if (N->getNumOperands() == 1)
9836 return N->getOperand(0);
9838 // Check if all of the operands are undefs.
9839 if (ISD::allOperandsUndef(N))
9840 return DAG.getUNDEF(N->getValueType(0));
9842 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9843 // nodes often generate nop CONCAT_VECTOR nodes.
9844 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9845 // place the incoming vectors at the exact same location.
9846 SDValue SingleSource = SDValue();
9847 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9849 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9850 SDValue Op = N->getOperand(i);
9852 if (Op.getOpcode() == ISD::UNDEF)
9855 // Check if this is the identity extract:
9856 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9859 // Find the single incoming vector for the extract_subvector.
9860 if (SingleSource.getNode()) {
9861 if (Op.getOperand(0) != SingleSource)
9864 SingleSource = Op.getOperand(0);
9866 // Check the source type is the same as the type of the result.
9867 // If not, this concat may extend the vector, so we can not
9868 // optimize it away.
9869 if (SingleSource.getValueType() != N->getValueType(0))
9873 unsigned IdentityIndex = i * PartNumElem;
9874 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9875 // The extract index must be constant.
9879 // Check that we are reading from the identity index.
9880 if (CS->getZExtValue() != IdentityIndex)
9884 if (SingleSource.getNode())
9885 return SingleSource;
9890 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9891 EVT NVT = N->getValueType(0);
9892 SDValue V = N->getOperand(0);
9894 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9896 // (extract_subvec (concat V1, V2, ...), i)
9899 // Only operand 0 is checked as 'concat' assumes all inputs of the same
9901 if (V->getOperand(0).getValueType() != NVT)
9903 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9904 unsigned NumElems = NVT.getVectorNumElements();
9905 assert((Idx % NumElems) == 0 &&
9906 "IDX in concat is not a multiple of the result vector length.");
9907 return V->getOperand(Idx / NumElems);
9911 if (V->getOpcode() == ISD::BITCAST)
9912 V = V.getOperand(0);
9914 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9916 // Handle only simple case where vector being inserted and vector
9917 // being extracted are of same type, and are half size of larger vectors.
9918 EVT BigVT = V->getOperand(0).getValueType();
9919 EVT SmallVT = V->getOperand(1).getValueType();
9920 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9923 // Only handle cases where both indexes are constants with the same type.
9924 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9925 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9927 if (InsIdx && ExtIdx &&
9928 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9929 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9931 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9933 // indices are equal or bit offsets are equal => V1
9934 // otherwise => (extract_subvec V1, ExtIdx)
9935 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9936 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9937 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9938 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9939 DAG.getNode(ISD::BITCAST, dl,
9940 N->getOperand(0).getValueType(),
9941 V->getOperand(0)), N->getOperand(1));
9948 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9949 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9950 EVT VT = N->getValueType(0);
9951 unsigned NumElts = VT.getVectorNumElements();
9953 SDValue N0 = N->getOperand(0);
9954 SDValue N1 = N->getOperand(1);
9955 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9957 SmallVector<SDValue, 4> Ops;
9958 EVT ConcatVT = N0.getOperand(0).getValueType();
9959 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9960 unsigned NumConcats = NumElts / NumElemsPerConcat;
9962 // Look at every vector that's inserted. We're looking for exact
9963 // subvector-sized copies from a concatenated vector
9964 for (unsigned I = 0; I != NumConcats; ++I) {
9965 // Make sure we're dealing with a copy.
9966 unsigned Begin = I * NumElemsPerConcat;
9967 bool AllUndef = true, NoUndef = true;
9968 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9969 if (SVN->getMaskElt(J) >= 0)
9976 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9979 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9980 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9983 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9984 if (FirstElt < N0.getNumOperands())
9985 Ops.push_back(N0.getOperand(FirstElt));
9987 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9989 } else if (AllUndef) {
9990 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9991 } else { // Mixed with general masks and undefs, can't do optimization.
9996 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10000 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10001 EVT VT = N->getValueType(0);
10002 unsigned NumElts = VT.getVectorNumElements();
10004 SDValue N0 = N->getOperand(0);
10005 SDValue N1 = N->getOperand(1);
10007 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10009 // Canonicalize shuffle undef, undef -> undef
10010 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10011 return DAG.getUNDEF(VT);
10013 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10015 // Canonicalize shuffle v, v -> v, undef
10017 SmallVector<int, 8> NewMask;
10018 for (unsigned i = 0; i != NumElts; ++i) {
10019 int Idx = SVN->getMaskElt(i);
10020 if (Idx >= (int)NumElts) Idx -= NumElts;
10021 NewMask.push_back(Idx);
10023 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10027 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10028 if (N0.getOpcode() == ISD::UNDEF) {
10029 SmallVector<int, 8> NewMask;
10030 for (unsigned i = 0; i != NumElts; ++i) {
10031 int Idx = SVN->getMaskElt(i);
10033 if (Idx >= (int)NumElts)
10036 Idx = -1; // remove reference to lhs
10038 NewMask.push_back(Idx);
10040 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10044 // Remove references to rhs if it is undef
10045 if (N1.getOpcode() == ISD::UNDEF) {
10046 bool Changed = false;
10047 SmallVector<int, 8> NewMask;
10048 for (unsigned i = 0; i != NumElts; ++i) {
10049 int Idx = SVN->getMaskElt(i);
10050 if (Idx >= (int)NumElts) {
10054 NewMask.push_back(Idx);
10057 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10060 // If it is a splat, check if the argument vector is another splat or a
10061 // build_vector with all scalar elements the same.
10062 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10063 SDNode *V = N0.getNode();
10065 // If this is a bit convert that changes the element type of the vector but
10066 // not the number of vector elements, look through it. Be careful not to
10067 // look though conversions that change things like v4f32 to v2f64.
10068 if (V->getOpcode() == ISD::BITCAST) {
10069 SDValue ConvInput = V->getOperand(0);
10070 if (ConvInput.getValueType().isVector() &&
10071 ConvInput.getValueType().getVectorNumElements() == NumElts)
10072 V = ConvInput.getNode();
10075 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10076 assert(V->getNumOperands() == NumElts &&
10077 "BUILD_VECTOR has wrong number of operands");
10079 bool AllSame = true;
10080 for (unsigned i = 0; i != NumElts; ++i) {
10081 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10082 Base = V->getOperand(i);
10086 // Splat of <u, u, u, u>, return <u, u, u, u>
10087 if (!Base.getNode())
10089 for (unsigned i = 0; i != NumElts; ++i) {
10090 if (V->getOperand(i) != Base) {
10095 // Splat of <x, x, x, x>, return <x, x, x, x>
10101 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10102 Level < AfterLegalizeVectorOps &&
10103 (N1.getOpcode() == ISD::UNDEF ||
10104 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10105 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10106 SDValue V = partitionShuffleOfConcats(N, DAG);
10112 // If this shuffle node is simply a swizzle of another shuffle node,
10113 // and it reverses the swizzle of the previous shuffle then we can
10114 // optimize shuffle(shuffle(x, undef), undef) -> x.
10115 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10116 N1.getOpcode() == ISD::UNDEF) {
10118 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10120 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10121 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10124 // The incoming shuffle must be of the same type as the result of the
10125 // current shuffle.
10126 assert(OtherSV->getOperand(0).getValueType() == VT &&
10127 "Shuffle types don't match");
10129 for (unsigned i = 0; i != NumElts; ++i) {
10130 int Idx = SVN->getMaskElt(i);
10131 assert(Idx < (int)NumElts && "Index references undef operand");
10132 // Next, this index comes from the first value, which is the incoming
10133 // shuffle. Adopt the incoming index.
10135 Idx = OtherSV->getMaskElt(Idx);
10137 // The combined shuffle must map each index to itself.
10138 if (Idx >= 0 && (unsigned)Idx != i)
10142 return OtherSV->getOperand(0);
10148 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10149 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10150 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10151 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10152 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10153 EVT VT = N->getValueType(0);
10155 SDValue LHS = N->getOperand(0);
10156 SDValue RHS = N->getOperand(1);
10157 if (N->getOpcode() == ISD::AND) {
10158 if (RHS.getOpcode() == ISD::BITCAST)
10159 RHS = RHS.getOperand(0);
10160 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10161 SmallVector<int, 8> Indices;
10162 unsigned NumElts = RHS.getNumOperands();
10163 for (unsigned i = 0; i != NumElts; ++i) {
10164 SDValue Elt = RHS.getOperand(i);
10165 if (!isa<ConstantSDNode>(Elt))
10168 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10169 Indices.push_back(i);
10170 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10171 Indices.push_back(NumElts);
10176 // Let's see if the target supports this vector_shuffle.
10177 EVT RVT = RHS.getValueType();
10178 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10181 // Return the new VECTOR_SHUFFLE node.
10182 EVT EltVT = RVT.getVectorElementType();
10183 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10184 DAG.getConstant(0, EltVT));
10185 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10186 RVT, &ZeroOps[0], ZeroOps.size());
10187 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10188 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10189 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10196 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10197 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10198 assert(N->getValueType(0).isVector() &&
10199 "SimplifyVBinOp only works on vectors!");
10201 SDValue LHS = N->getOperand(0);
10202 SDValue RHS = N->getOperand(1);
10203 SDValue Shuffle = XformToShuffleWithZero(N);
10204 if (Shuffle.getNode()) return Shuffle;
10206 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10208 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10209 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10210 SmallVector<SDValue, 8> Ops;
10211 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10212 SDValue LHSOp = LHS.getOperand(i);
10213 SDValue RHSOp = RHS.getOperand(i);
10214 // If these two elements can't be folded, bail out.
10215 if ((LHSOp.getOpcode() != ISD::UNDEF &&
10216 LHSOp.getOpcode() != ISD::Constant &&
10217 LHSOp.getOpcode() != ISD::ConstantFP) ||
10218 (RHSOp.getOpcode() != ISD::UNDEF &&
10219 RHSOp.getOpcode() != ISD::Constant &&
10220 RHSOp.getOpcode() != ISD::ConstantFP))
10223 // Can't fold divide by zero.
10224 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10225 N->getOpcode() == ISD::FDIV) {
10226 if ((RHSOp.getOpcode() == ISD::Constant &&
10227 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10228 (RHSOp.getOpcode() == ISD::ConstantFP &&
10229 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10233 EVT VT = LHSOp.getValueType();
10234 EVT RVT = RHSOp.getValueType();
10236 // Integer BUILD_VECTOR operands may have types larger than the element
10237 // size (e.g., when the element type is not legal). Prior to type
10238 // legalization, the types may not match between the two BUILD_VECTORS.
10239 // Truncate one of the operands to make them match.
10240 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10241 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10243 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10247 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10249 if (FoldOp.getOpcode() != ISD::UNDEF &&
10250 FoldOp.getOpcode() != ISD::Constant &&
10251 FoldOp.getOpcode() != ISD::ConstantFP)
10253 Ops.push_back(FoldOp);
10254 AddToWorkList(FoldOp.getNode());
10257 if (Ops.size() == LHS.getNumOperands())
10258 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10259 LHS.getValueType(), &Ops[0], Ops.size());
10265 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10266 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10267 assert(N->getValueType(0).isVector() &&
10268 "SimplifyVUnaryOp only works on vectors!");
10270 SDValue N0 = N->getOperand(0);
10272 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10275 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10276 SmallVector<SDValue, 8> Ops;
10277 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10278 SDValue Op = N0.getOperand(i);
10279 if (Op.getOpcode() != ISD::UNDEF &&
10280 Op.getOpcode() != ISD::ConstantFP)
10282 EVT EltVT = Op.getValueType();
10283 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10284 if (FoldOp.getOpcode() != ISD::UNDEF &&
10285 FoldOp.getOpcode() != ISD::ConstantFP)
10287 Ops.push_back(FoldOp);
10288 AddToWorkList(FoldOp.getNode());
10291 if (Ops.size() != N0.getNumOperands())
10294 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10295 N0.getValueType(), &Ops[0], Ops.size());
10298 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10299 SDValue N1, SDValue N2){
10300 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10302 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10303 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10305 // If we got a simplified select_cc node back from SimplifySelectCC, then
10306 // break it down into a new SETCC node, and a new SELECT node, and then return
10307 // the SELECT node, since we were called with a SELECT node.
10308 if (SCC.getNode()) {
10309 // Check to see if we got a select_cc back (to turn into setcc/select).
10310 // Otherwise, just return whatever node we got back, like fabs.
10311 if (SCC.getOpcode() == ISD::SELECT_CC) {
10312 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10314 SCC.getOperand(0), SCC.getOperand(1),
10315 SCC.getOperand(4));
10316 AddToWorkList(SETCC.getNode());
10317 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10318 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10326 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10327 /// are the two values being selected between, see if we can simplify the
10328 /// select. Callers of this should assume that TheSelect is deleted if this
10329 /// returns true. As such, they should return the appropriate thing (e.g. the
10330 /// node) back to the top-level of the DAG combiner loop to avoid it being
10332 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10335 // Cannot simplify select with vector condition
10336 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10338 // If this is a select from two identical things, try to pull the operation
10339 // through the select.
10340 if (LHS.getOpcode() != RHS.getOpcode() ||
10341 !LHS.hasOneUse() || !RHS.hasOneUse())
10344 // If this is a load and the token chain is identical, replace the select
10345 // of two loads with a load through a select of the address to load from.
10346 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10347 // constants have been dropped into the constant pool.
10348 if (LHS.getOpcode() == ISD::LOAD) {
10349 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10350 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10352 // Token chains must be identical.
10353 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10354 // Do not let this transformation reduce the number of volatile loads.
10355 LLD->isVolatile() || RLD->isVolatile() ||
10356 // If this is an EXTLOAD, the VT's must match.
10357 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10358 // If this is an EXTLOAD, the kind of extension must match.
10359 (LLD->getExtensionType() != RLD->getExtensionType() &&
10360 // The only exception is if one of the extensions is anyext.
10361 LLD->getExtensionType() != ISD::EXTLOAD &&
10362 RLD->getExtensionType() != ISD::EXTLOAD) ||
10363 // FIXME: this discards src value information. This is
10364 // over-conservative. It would be beneficial to be able to remember
10365 // both potential memory locations. Since we are discarding
10366 // src value info, don't do the transformation if the memory
10367 // locations are not in the default address space.
10368 LLD->getPointerInfo().getAddrSpace() != 0 ||
10369 RLD->getPointerInfo().getAddrSpace() != 0 ||
10370 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10371 LLD->getBasePtr().getValueType()))
10374 // Check that the select condition doesn't reach either load. If so,
10375 // folding this will induce a cycle into the DAG. If not, this is safe to
10376 // xform, so create a select of the addresses.
10378 if (TheSelect->getOpcode() == ISD::SELECT) {
10379 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10380 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10381 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10383 // The loads must not depend on one another.
10384 if (LLD->isPredecessorOf(RLD) ||
10385 RLD->isPredecessorOf(LLD))
10387 Addr = DAG.getSelect(SDLoc(TheSelect),
10388 LLD->getBasePtr().getValueType(),
10389 TheSelect->getOperand(0), LLD->getBasePtr(),
10390 RLD->getBasePtr());
10391 } else { // Otherwise SELECT_CC
10392 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10393 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10395 if ((LLD->hasAnyUseOfValue(1) &&
10396 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10397 (RLD->hasAnyUseOfValue(1) &&
10398 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10401 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10402 LLD->getBasePtr().getValueType(),
10403 TheSelect->getOperand(0),
10404 TheSelect->getOperand(1),
10405 LLD->getBasePtr(), RLD->getBasePtr(),
10406 TheSelect->getOperand(4));
10410 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10411 Load = DAG.getLoad(TheSelect->getValueType(0),
10413 // FIXME: Discards pointer info.
10414 LLD->getChain(), Addr, MachinePointerInfo(),
10415 LLD->isVolatile(), LLD->isNonTemporal(),
10416 LLD->isInvariant(), LLD->getAlignment());
10418 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10419 RLD->getExtensionType() : LLD->getExtensionType(),
10421 TheSelect->getValueType(0),
10422 // FIXME: Discards pointer info.
10423 LLD->getChain(), Addr, MachinePointerInfo(),
10424 LLD->getMemoryVT(), LLD->isVolatile(),
10425 LLD->isNonTemporal(), LLD->getAlignment());
10428 // Users of the select now use the result of the load.
10429 CombineTo(TheSelect, Load);
10431 // Users of the old loads now use the new load's chain. We know the
10432 // old-load value is dead now.
10433 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10434 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10441 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10442 /// where 'cond' is the comparison specified by CC.
10443 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10444 SDValue N2, SDValue N3,
10445 ISD::CondCode CC, bool NotExtCompare) {
10446 // (x ? y : y) -> y.
10447 if (N2 == N3) return N2;
10449 EVT VT = N2.getValueType();
10450 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10451 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10452 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10454 // Determine if the condition we're dealing with is constant
10455 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10456 N0, N1, CC, DL, false);
10457 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10458 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10460 // fold select_cc true, x, y -> x
10461 if (SCCC && !SCCC->isNullValue())
10463 // fold select_cc false, x, y -> y
10464 if (SCCC && SCCC->isNullValue())
10467 // Check to see if we can simplify the select into an fabs node
10468 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10469 // Allow either -0.0 or 0.0
10470 if (CFP->getValueAPF().isZero()) {
10471 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10472 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10473 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10474 N2 == N3.getOperand(0))
10475 return DAG.getNode(ISD::FABS, DL, VT, N0);
10477 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10478 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10479 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10480 N2.getOperand(0) == N3)
10481 return DAG.getNode(ISD::FABS, DL, VT, N3);
10485 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10486 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10487 // in it. This is a win when the constant is not otherwise available because
10488 // it replaces two constant pool loads with one. We only do this if the FP
10489 // type is known to be legal, because if it isn't, then we are before legalize
10490 // types an we want the other legalization to happen first (e.g. to avoid
10491 // messing with soft float) and if the ConstantFP is not legal, because if
10492 // it is legal, we may not need to store the FP constant in a constant pool.
10493 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10494 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10495 if (TLI.isTypeLegal(N2.getValueType()) &&
10496 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10497 TargetLowering::Legal) &&
10498 // If both constants have multiple uses, then we won't need to do an
10499 // extra load, they are likely around in registers for other users.
10500 (TV->hasOneUse() || FV->hasOneUse())) {
10501 Constant *Elts[] = {
10502 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10503 const_cast<ConstantFP*>(TV->getConstantFPValue())
10505 Type *FPTy = Elts[0]->getType();
10506 const DataLayout &TD = *TLI.getDataLayout();
10508 // Create a ConstantArray of the two constants.
10509 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10510 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10511 TD.getPrefTypeAlignment(FPTy));
10512 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10514 // Get the offsets to the 0 and 1 element of the array so that we can
10515 // select between them.
10516 SDValue Zero = DAG.getIntPtrConstant(0);
10517 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10518 SDValue One = DAG.getIntPtrConstant(EltSize);
10520 SDValue Cond = DAG.getSetCC(DL,
10521 getSetCCResultType(N0.getValueType()),
10523 AddToWorkList(Cond.getNode());
10524 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10526 AddToWorkList(CstOffset.getNode());
10527 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10529 AddToWorkList(CPIdx.getNode());
10530 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10531 MachinePointerInfo::getConstantPool(), false,
10532 false, false, Alignment);
10537 // Check to see if we can perform the "gzip trick", transforming
10538 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10539 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10540 (N1C->isNullValue() || // (a < 0) ? b : 0
10541 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10542 EVT XType = N0.getValueType();
10543 EVT AType = N2.getValueType();
10544 if (XType.bitsGE(AType)) {
10545 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10546 // single-bit constant.
10547 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10548 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10549 ShCtV = XType.getSizeInBits()-ShCtV-1;
10550 SDValue ShCt = DAG.getConstant(ShCtV,
10551 getShiftAmountTy(N0.getValueType()));
10552 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10554 AddToWorkList(Shift.getNode());
10556 if (XType.bitsGT(AType)) {
10557 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10558 AddToWorkList(Shift.getNode());
10561 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10564 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10566 DAG.getConstant(XType.getSizeInBits()-1,
10567 getShiftAmountTy(N0.getValueType())));
10568 AddToWorkList(Shift.getNode());
10570 if (XType.bitsGT(AType)) {
10571 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10572 AddToWorkList(Shift.getNode());
10575 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10579 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10580 // where y is has a single bit set.
10581 // A plaintext description would be, we can turn the SELECT_CC into an AND
10582 // when the condition can be materialized as an all-ones register. Any
10583 // single bit-test can be materialized as an all-ones register with
10584 // shift-left and shift-right-arith.
10585 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10586 N0->getValueType(0) == VT &&
10587 N1C && N1C->isNullValue() &&
10588 N2C && N2C->isNullValue()) {
10589 SDValue AndLHS = N0->getOperand(0);
10590 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10591 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10592 // Shift the tested bit over the sign bit.
10593 APInt AndMask = ConstAndRHS->getAPIntValue();
10595 DAG.getConstant(AndMask.countLeadingZeros(),
10596 getShiftAmountTy(AndLHS.getValueType()));
10597 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10599 // Now arithmetic right shift it all the way over, so the result is either
10600 // all-ones, or zero.
10602 DAG.getConstant(AndMask.getBitWidth()-1,
10603 getShiftAmountTy(Shl.getValueType()));
10604 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10606 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10610 // fold select C, 16, 0 -> shl C, 4
10611 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10612 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10613 TargetLowering::ZeroOrOneBooleanContent) {
10615 // If the caller doesn't want us to simplify this into a zext of a compare,
10617 if (NotExtCompare && N2C->getAPIntValue() == 1)
10620 // Get a SetCC of the condition
10621 // NOTE: Don't create a SETCC if it's not legal on this target.
10622 if (!LegalOperations ||
10623 TLI.isOperationLegal(ISD::SETCC,
10624 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10626 // cast from setcc result type to select result type
10628 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10630 if (N2.getValueType().bitsLT(SCC.getValueType()))
10631 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10632 N2.getValueType());
10634 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10635 N2.getValueType(), SCC);
10637 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10638 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10639 N2.getValueType(), SCC);
10642 AddToWorkList(SCC.getNode());
10643 AddToWorkList(Temp.getNode());
10645 if (N2C->getAPIntValue() == 1)
10648 // shl setcc result by log2 n2c
10649 return DAG.getNode(
10650 ISD::SHL, DL, N2.getValueType(), Temp,
10651 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10652 getShiftAmountTy(Temp.getValueType())));
10656 // Check to see if this is the equivalent of setcc
10657 // FIXME: Turn all of these into setcc if setcc if setcc is legal
10658 // otherwise, go ahead with the folds.
10659 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10660 EVT XType = N0.getValueType();
10661 if (!LegalOperations ||
10662 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10663 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10664 if (Res.getValueType() != VT)
10665 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10669 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10670 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10671 (!LegalOperations ||
10672 TLI.isOperationLegal(ISD::CTLZ, XType))) {
10673 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10674 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10675 DAG.getConstant(Log2_32(XType.getSizeInBits()),
10676 getShiftAmountTy(Ctlz.getValueType())));
10678 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10679 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10680 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10681 XType, DAG.getConstant(0, XType), N0);
10682 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10683 return DAG.getNode(ISD::SRL, DL, XType,
10684 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10685 DAG.getConstant(XType.getSizeInBits()-1,
10686 getShiftAmountTy(XType)));
10688 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10689 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10690 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10691 DAG.getConstant(XType.getSizeInBits()-1,
10692 getShiftAmountTy(N0.getValueType())));
10693 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10697 // Check to see if this is an integer abs.
10698 // select_cc setg[te] X, 0, X, -X ->
10699 // select_cc setgt X, -1, X, -X ->
10700 // select_cc setl[te] X, 0, -X, X ->
10701 // select_cc setlt X, 1, -X, X ->
10702 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10704 ConstantSDNode *SubC = NULL;
10705 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10706 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10707 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10708 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10709 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10710 (N1C->isOne() && CC == ISD::SETLT)) &&
10711 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10712 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10714 EVT XType = N0.getValueType();
10715 if (SubC && SubC->isNullValue() && XType.isInteger()) {
10716 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10718 DAG.getConstant(XType.getSizeInBits()-1,
10719 getShiftAmountTy(N0.getValueType())));
10720 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10722 AddToWorkList(Shift.getNode());
10723 AddToWorkList(Add.getNode());
10724 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10731 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10732 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10733 SDValue N1, ISD::CondCode Cond,
10734 SDLoc DL, bool foldBooleans) {
10735 TargetLowering::DAGCombinerInfo
10736 DagCombineInfo(DAG, Level, false, this);
10737 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10740 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10741 /// return a DAG expression to select that will generate the same value by
10742 /// multiplying by a magic number. See:
10743 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10744 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10745 std::vector<SDNode*> Built;
10746 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10748 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10750 AddToWorkList(*ii);
10754 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10755 /// return a DAG expression to select that will generate the same value by
10756 /// multiplying by a magic number. See:
10757 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10758 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10759 std::vector<SDNode*> Built;
10760 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10762 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10764 AddToWorkList(*ii);
10768 /// FindBaseOffset - Return true if base is a frame index, which is known not
10769 // to alias with anything but itself. Provides base object and offset as
10771 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10772 const GlobalValue *&GV, const void *&CV) {
10773 // Assume it is a primitive operation.
10774 Base = Ptr; Offset = 0; GV = 0; CV = 0;
10776 // If it's an adding a simple constant then integrate the offset.
10777 if (Base.getOpcode() == ISD::ADD) {
10778 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10779 Base = Base.getOperand(0);
10780 Offset += C->getZExtValue();
10784 // Return the underlying GlobalValue, and update the Offset. Return false
10785 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10786 // by multiple nodes with different offsets.
10787 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10788 GV = G->getGlobal();
10789 Offset += G->getOffset();
10793 // Return the underlying Constant value, and update the Offset. Return false
10794 // for ConstantSDNodes since the same constant pool entry may be represented
10795 // by multiple nodes with different offsets.
10796 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10797 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10798 : (const void *)C->getConstVal();
10799 Offset += C->getOffset();
10802 // If it's any of the following then it can't alias with anything but itself.
10803 return isa<FrameIndexSDNode>(Base);
10806 /// isAlias - Return true if there is any possibility that the two addresses
10808 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10809 const Value *SrcValue1, int SrcValueOffset1,
10810 unsigned SrcValueAlign1,
10811 const MDNode *TBAAInfo1,
10812 SDValue Ptr2, int64_t Size2,
10813 const Value *SrcValue2, int SrcValueOffset2,
10814 unsigned SrcValueAlign2,
10815 const MDNode *TBAAInfo2) const {
10816 // If they are the same then they must be aliases.
10817 if (Ptr1 == Ptr2) return true;
10819 // Gather base node and offset information.
10820 SDValue Base1, Base2;
10821 int64_t Offset1, Offset2;
10822 const GlobalValue *GV1, *GV2;
10823 const void *CV1, *CV2;
10824 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10825 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10827 // If they have a same base address then check to see if they overlap.
10828 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10829 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10831 // It is possible for different frame indices to alias each other, mostly
10832 // when tail call optimization reuses return address slots for arguments.
10833 // To catch this case, look up the actual index of frame indices to compute
10834 // the real alias relationship.
10835 if (isFrameIndex1 && isFrameIndex2) {
10836 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10837 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10838 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10839 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10842 // Otherwise, if we know what the bases are, and they aren't identical, then
10843 // we know they cannot alias.
10844 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10847 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10848 // compared to the size and offset of the access, we may be able to prove they
10849 // do not alias. This check is conservative for now to catch cases created by
10850 // splitting vector types.
10851 if ((SrcValueAlign1 == SrcValueAlign2) &&
10852 (SrcValueOffset1 != SrcValueOffset2) &&
10853 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10854 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10855 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10857 // There is no overlap between these relatively aligned accesses of similar
10858 // size, return no alias.
10859 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10863 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10864 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10865 if (UseAA && SrcValue1 && SrcValue2) {
10866 // Use alias analysis information.
10867 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10868 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10869 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10870 AliasAnalysis::AliasResult AAResult =
10871 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10872 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10873 if (AAResult == AliasAnalysis::NoAlias)
10877 // Otherwise we have to assume they alias.
10881 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10882 SDValue Ptr0, Ptr1;
10883 int64_t Size0, Size1;
10884 const Value *SrcValue0, *SrcValue1;
10885 int SrcValueOffset0, SrcValueOffset1;
10886 unsigned SrcValueAlign0, SrcValueAlign1;
10887 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10888 FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10889 SrcValueAlign0, SrcTBAAInfo0);
10890 FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10891 SrcValueAlign1, SrcTBAAInfo1);
10892 return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10893 SrcValueAlign0, SrcTBAAInfo0,
10894 Ptr1, Size1, SrcValue1, SrcValueOffset1,
10895 SrcValueAlign1, SrcTBAAInfo1);
10898 /// FindAliasInfo - Extracts the relevant alias information from the memory
10899 /// node. Returns true if the operand was a load.
10900 bool DAGCombiner::FindAliasInfo(SDNode *N,
10901 SDValue &Ptr, int64_t &Size,
10902 const Value *&SrcValue,
10903 int &SrcValueOffset,
10904 unsigned &SrcValueAlign,
10905 const MDNode *&TBAAInfo) const {
10906 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10908 Ptr = LS->getBasePtr();
10909 Size = LS->getMemoryVT().getSizeInBits() >> 3;
10910 SrcValue = LS->getSrcValue();
10911 SrcValueOffset = LS->getSrcValueOffset();
10912 SrcValueAlign = LS->getOriginalAlignment();
10913 TBAAInfo = LS->getTBAAInfo();
10914 return isa<LoadSDNode>(LS);
10917 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10918 /// looking for aliasing nodes and adding them to the Aliases vector.
10919 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10920 SmallVectorImpl<SDValue> &Aliases) {
10921 SmallVector<SDValue, 8> Chains; // List of chains to visit.
10922 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
10924 // Get alias information for node.
10927 const Value *SrcValue;
10928 int SrcValueOffset;
10929 unsigned SrcValueAlign;
10930 const MDNode *SrcTBAAInfo;
10931 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10932 SrcValueAlign, SrcTBAAInfo);
10935 Chains.push_back(OriginalChain);
10936 unsigned Depth = 0;
10938 // Look at each chain and determine if it is an alias. If so, add it to the
10939 // aliases list. If not, then continue up the chain looking for the next
10941 while (!Chains.empty()) {
10942 SDValue Chain = Chains.back();
10945 // For TokenFactor nodes, look at each operand and only continue up the
10946 // chain until we find two aliases. If we've seen two aliases, assume we'll
10947 // find more and revert to original chain since the xform is unlikely to be
10950 // FIXME: The depth check could be made to return the last non-aliasing
10951 // chain we found before we hit a tokenfactor rather than the original
10953 if (Depth > 6 || Aliases.size() == 2) {
10955 Aliases.push_back(OriginalChain);
10959 // Don't bother if we've been before.
10960 if (!Visited.insert(Chain.getNode()))
10963 switch (Chain.getOpcode()) {
10964 case ISD::EntryToken:
10965 // Entry token is ideal chain operand, but handled in FindBetterChain.
10970 // Get alias information for Chain.
10973 const Value *OpSrcValue;
10974 int OpSrcValueOffset;
10975 unsigned OpSrcValueAlign;
10976 const MDNode *OpSrcTBAAInfo;
10977 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10978 OpSrcValue, OpSrcValueOffset,
10982 // If chain is alias then stop here.
10983 if (!(IsLoad && IsOpLoad) &&
10984 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10986 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10987 OpSrcValueAlign, OpSrcTBAAInfo)) {
10988 Aliases.push_back(Chain);
10990 // Look further up the chain.
10991 Chains.push_back(Chain.getOperand(0));
10997 case ISD::TokenFactor:
10998 // We have to check each of the operands of the token factor for "small"
10999 // token factors, so we queue them up. Adding the operands to the queue
11000 // (stack) in reverse order maintains the original order and increases the
11001 // likelihood that getNode will find a matching token factor (CSE.)
11002 if (Chain.getNumOperands() > 16) {
11003 Aliases.push_back(Chain);
11006 for (unsigned n = Chain.getNumOperands(); n;)
11007 Chains.push_back(Chain.getOperand(--n));
11012 // For all other instructions we will just have to take what we can get.
11013 Aliases.push_back(Chain);
11019 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11020 /// for a better chain (aliasing node.)
11021 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11022 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11024 // Accumulate all the aliases to this node.
11025 GatherAllAliases(N, OldChain, Aliases);
11027 // If no operands then chain to entry token.
11028 if (Aliases.size() == 0)
11029 return DAG.getEntryNode();
11031 // If a single operand then chain to it. We don't need to revisit it.
11032 if (Aliases.size() == 1)
11035 // Construct a custom tailored token factor.
11036 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11037 &Aliases[0], Aliases.size());
11040 // SelectionDAG::Combine - This is the entry point for the file.
11042 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11043 CodeGenOpt::Level OptLevel) {
11044 /// run - This is the main entry point to this class.
11046 DAGCombiner(*this, AA, OptLevel).Run(Level);