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 *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
284 SDValue InnerPos, SDValue InnerNeg,
285 unsigned PosOpcode, unsigned NegOpcode,
287 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
288 SDValue ReduceLoadWidth(SDNode *N);
289 SDValue ReduceLoadOpStoreWidth(SDNode *N);
290 SDValue TransformFPLoadStorePair(SDNode *N);
291 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
292 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
294 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
296 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
297 /// looking for aliasing nodes and adding them to the Aliases vector.
298 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
299 SmallVectorImpl<SDValue> &Aliases);
301 /// isAlias - Return true if there is any possibility that the two addresses
303 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
304 const Value *SrcValue1, int SrcValueOffset1,
305 unsigned SrcValueAlign1,
306 const MDNode *TBAAInfo1,
307 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
308 const Value *SrcValue2, int SrcValueOffset2,
309 unsigned SrcValueAlign2,
310 const MDNode *TBAAInfo2) const;
312 /// isAlias - Return true if there is any possibility that the two addresses
314 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
316 /// FindAliasInfo - Extracts the relevant alias information from the memory
317 /// node. Returns true if the operand was a load.
318 bool FindAliasInfo(SDNode *N,
319 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
320 const Value *&SrcValue, int &SrcValueOffset,
321 unsigned &SrcValueAlignment,
322 const MDNode *&TBAAInfo) const;
324 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
325 /// looking for a better chain (aliasing node.)
326 SDValue FindBetterChain(SDNode *N, SDValue Chain);
328 /// Merge consecutive store operations into a wide store.
329 /// This optimization uses wide integers or vectors when possible.
330 /// \return True if some memory operations were changed.
331 bool MergeConsecutiveStores(StoreSDNode *N);
334 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
335 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
336 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
337 AttributeSet FnAttrs =
338 DAG.getMachineFunction().getFunction()->getAttributes();
340 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
341 Attribute::OptimizeForSize) ||
342 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
345 /// Run - runs the dag combiner on all nodes in the work list
346 void Run(CombineLevel AtLevel);
348 SelectionDAG &getDAG() const { return DAG; }
350 /// getShiftAmountTy - Returns a type large enough to hold any valid
351 /// shift amount - before type legalization these can be huge.
352 EVT getShiftAmountTy(EVT LHSTy) {
353 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
354 if (LHSTy.isVector())
356 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
357 : TLI.getPointerTy();
360 /// isTypeLegal - This method returns true if we are running before type
361 /// legalization or if the specified VT is legal.
362 bool isTypeLegal(const EVT &VT) {
363 if (!LegalTypes) return true;
364 return TLI.isTypeLegal(VT);
367 /// getSetCCResultType - Convenience wrapper around
368 /// TargetLowering::getSetCCResultType
369 EVT getSetCCResultType(EVT VT) const {
370 return TLI.getSetCCResultType(*DAG.getContext(), VT);
377 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
378 /// nodes from the worklist.
379 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
382 explicit WorkListRemover(DAGCombiner &dc)
383 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
385 virtual void NodeDeleted(SDNode *N, SDNode *E) {
386 DC.removeFromWorkList(N);
391 //===----------------------------------------------------------------------===//
392 // TargetLowering::DAGCombinerInfo implementation
393 //===----------------------------------------------------------------------===//
395 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
396 ((DAGCombiner*)DC)->AddToWorkList(N);
399 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
400 ((DAGCombiner*)DC)->removeFromWorkList(N);
403 SDValue TargetLowering::DAGCombinerInfo::
404 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
405 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
408 SDValue TargetLowering::DAGCombinerInfo::
409 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
410 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
414 SDValue TargetLowering::DAGCombinerInfo::
415 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
416 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
419 void TargetLowering::DAGCombinerInfo::
420 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
421 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
424 //===----------------------------------------------------------------------===//
426 //===----------------------------------------------------------------------===//
428 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
429 /// specified expression for the same cost as the expression itself, or 2 if we
430 /// can compute the negated form more cheaply than the expression itself.
431 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
432 const TargetLowering &TLI,
433 const TargetOptions *Options,
434 unsigned Depth = 0) {
435 // fneg is removable even if it has multiple uses.
436 if (Op.getOpcode() == ISD::FNEG) return 2;
438 // Don't allow anything with multiple uses.
439 if (!Op.hasOneUse()) return 0;
441 // Don't recurse exponentially.
442 if (Depth > 6) return 0;
444 switch (Op.getOpcode()) {
445 default: return false;
446 case ISD::ConstantFP:
447 // Don't invert constant FP values after legalize. The negated constant
448 // isn't necessarily legal.
449 return LegalOperations ? 0 : 1;
451 // FIXME: determine better conditions for this xform.
452 if (!Options->UnsafeFPMath) return 0;
454 // After operation legalization, it might not be legal to create new FSUBs.
455 if (LegalOperations &&
456 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
459 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
460 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
463 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
464 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
467 // We can't turn -(A-B) into B-A when we honor signed zeros.
468 if (!Options->UnsafeFPMath) return 0;
470 // fold (fneg (fsub A, B)) -> (fsub B, A)
475 if (Options->HonorSignDependentRoundingFPMath()) return 0;
477 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
478 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
482 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
488 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
493 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
494 /// returns the newly negated expression.
495 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
496 bool LegalOperations, unsigned Depth = 0) {
497 // fneg is removable even if it has multiple uses.
498 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
500 // Don't allow anything with multiple uses.
501 assert(Op.hasOneUse() && "Unknown reuse!");
503 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
504 switch (Op.getOpcode()) {
505 default: llvm_unreachable("Unknown code");
506 case ISD::ConstantFP: {
507 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
509 return DAG.getConstantFP(V, Op.getValueType());
512 // FIXME: determine better conditions for this xform.
513 assert(DAG.getTarget().Options.UnsafeFPMath);
515 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
516 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
517 DAG.getTargetLoweringInfo(),
518 &DAG.getTarget().Options, Depth+1))
519 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
520 GetNegatedExpression(Op.getOperand(0), DAG,
521 LegalOperations, Depth+1),
523 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
524 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
525 GetNegatedExpression(Op.getOperand(1), DAG,
526 LegalOperations, Depth+1),
529 // We can't turn -(A-B) into B-A when we honor signed zeros.
530 assert(DAG.getTarget().Options.UnsafeFPMath);
532 // fold (fneg (fsub 0, B)) -> B
533 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
534 if (N0CFP->getValueAPF().isZero())
535 return Op.getOperand(1);
537 // fold (fneg (fsub A, B)) -> (fsub B, A)
538 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
539 Op.getOperand(1), Op.getOperand(0));
543 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
545 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
546 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
547 DAG.getTargetLoweringInfo(),
548 &DAG.getTarget().Options, Depth+1))
549 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
550 GetNegatedExpression(Op.getOperand(0), DAG,
551 LegalOperations, Depth+1),
554 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
555 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
557 GetNegatedExpression(Op.getOperand(1), DAG,
558 LegalOperations, Depth+1));
562 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
563 GetNegatedExpression(Op.getOperand(0), DAG,
564 LegalOperations, Depth+1));
566 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
567 GetNegatedExpression(Op.getOperand(0), DAG,
568 LegalOperations, Depth+1),
574 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
575 // that selects between the values 1 and 0, making it equivalent to a setcc.
576 // Also, set the incoming LHS, RHS, and CC references to the appropriate
577 // nodes based on the type of node we are checking. This simplifies life a
578 // bit for the callers.
579 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
581 if (N.getOpcode() == ISD::SETCC) {
582 LHS = N.getOperand(0);
583 RHS = N.getOperand(1);
584 CC = N.getOperand(2);
587 if (N.getOpcode() == ISD::SELECT_CC &&
588 N.getOperand(2).getOpcode() == ISD::Constant &&
589 N.getOperand(3).getOpcode() == ISD::Constant &&
590 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
591 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
592 LHS = N.getOperand(0);
593 RHS = N.getOperand(1);
594 CC = N.getOperand(4);
600 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
601 // one use. If this is true, it allows the users to invert the operation for
602 // free when it is profitable to do so.
603 static bool isOneUseSetCC(SDValue N) {
605 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
610 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
611 SDValue N0, SDValue N1) {
612 EVT VT = N0.getValueType();
613 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
614 if (isa<ConstantSDNode>(N1)) {
615 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
617 DAG.FoldConstantArithmetic(Opc, VT,
618 cast<ConstantSDNode>(N0.getOperand(1)),
619 cast<ConstantSDNode>(N1));
620 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
622 if (N0.hasOneUse()) {
623 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
624 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
625 N0.getOperand(0), N1);
626 AddToWorkList(OpNode.getNode());
627 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
631 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
632 if (isa<ConstantSDNode>(N0)) {
633 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
635 DAG.FoldConstantArithmetic(Opc, VT,
636 cast<ConstantSDNode>(N1.getOperand(1)),
637 cast<ConstantSDNode>(N0));
638 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
640 if (N1.hasOneUse()) {
641 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
642 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
643 N1.getOperand(0), N0);
644 AddToWorkList(OpNode.getNode());
645 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
652 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
654 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
656 DEBUG(dbgs() << "\nReplacing.1 ";
658 dbgs() << "\nWith: ";
659 To[0].getNode()->dump(&DAG);
660 dbgs() << " and " << NumTo-1 << " other values\n";
661 for (unsigned i = 0, e = NumTo; i != e; ++i)
662 assert((!To[i].getNode() ||
663 N->getValueType(i) == To[i].getValueType()) &&
664 "Cannot combine value to value of different type!"));
665 WorkListRemover DeadNodes(*this);
666 DAG.ReplaceAllUsesWith(N, To);
668 // Push the new nodes and any users onto the worklist
669 for (unsigned i = 0, e = NumTo; i != e; ++i) {
670 if (To[i].getNode()) {
671 AddToWorkList(To[i].getNode());
672 AddUsersToWorkList(To[i].getNode());
677 // Finally, if the node is now dead, remove it from the graph. The node
678 // may not be dead if the replacement process recursively simplified to
679 // something else needing this node.
680 if (N->use_empty()) {
681 // Nodes can be reintroduced into the worklist. Make sure we do not
682 // process a node that has been replaced.
683 removeFromWorkList(N);
685 // Finally, since the node is now dead, remove it from the graph.
688 return SDValue(N, 0);
692 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
693 // Replace all uses. If any nodes become isomorphic to other nodes and
694 // are deleted, make sure to remove them from our worklist.
695 WorkListRemover DeadNodes(*this);
696 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
698 // Push the new node and any (possibly new) users onto the worklist.
699 AddToWorkList(TLO.New.getNode());
700 AddUsersToWorkList(TLO.New.getNode());
702 // Finally, if the node is now dead, remove it from the graph. The node
703 // may not be dead if the replacement process recursively simplified to
704 // something else needing this node.
705 if (TLO.Old.getNode()->use_empty()) {
706 removeFromWorkList(TLO.Old.getNode());
708 // If the operands of this node are only used by the node, they will now
709 // be dead. Make sure to visit them first to delete dead nodes early.
710 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
711 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
712 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
714 DAG.DeleteNode(TLO.Old.getNode());
718 /// SimplifyDemandedBits - Check the specified integer node value to see if
719 /// it can be simplified or if things it uses can be simplified by bit
720 /// propagation. If so, return true.
721 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
722 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
723 APInt KnownZero, KnownOne;
724 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
728 AddToWorkList(Op.getNode());
730 // Replace the old value with the new one.
732 DEBUG(dbgs() << "\nReplacing.2 ";
733 TLO.Old.getNode()->dump(&DAG);
734 dbgs() << "\nWith: ";
735 TLO.New.getNode()->dump(&DAG);
738 CommitTargetLoweringOpt(TLO);
742 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
744 EVT VT = Load->getValueType(0);
745 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
747 DEBUG(dbgs() << "\nReplacing.9 ";
749 dbgs() << "\nWith: ";
750 Trunc.getNode()->dump(&DAG);
752 WorkListRemover DeadNodes(*this);
753 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
754 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
755 removeFromWorkList(Load);
756 DAG.DeleteNode(Load);
757 AddToWorkList(Trunc.getNode());
760 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
763 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
764 EVT MemVT = LD->getMemoryVT();
765 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
766 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
768 : LD->getExtensionType();
770 return DAG.getExtLoad(ExtType, dl, PVT,
771 LD->getChain(), LD->getBasePtr(),
772 MemVT, LD->getMemOperand());
775 unsigned Opc = Op.getOpcode();
778 case ISD::AssertSext:
779 return DAG.getNode(ISD::AssertSext, dl, PVT,
780 SExtPromoteOperand(Op.getOperand(0), PVT),
782 case ISD::AssertZext:
783 return DAG.getNode(ISD::AssertZext, dl, PVT,
784 ZExtPromoteOperand(Op.getOperand(0), PVT),
786 case ISD::Constant: {
788 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
789 return DAG.getNode(ExtOpc, dl, PVT, Op);
793 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
795 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
798 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
799 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
801 EVT OldVT = Op.getValueType();
803 bool Replace = false;
804 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
805 if (NewOp.getNode() == 0)
807 AddToWorkList(NewOp.getNode());
810 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
811 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
812 DAG.getValueType(OldVT));
815 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
816 EVT OldVT = Op.getValueType();
818 bool Replace = false;
819 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
820 if (NewOp.getNode() == 0)
822 AddToWorkList(NewOp.getNode());
825 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
826 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
829 /// PromoteIntBinOp - Promote the specified integer binary operation if the
830 /// target indicates it is beneficial. e.g. On x86, it's usually better to
831 /// promote i16 operations to i32 since i16 instructions are longer.
832 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
833 if (!LegalOperations)
836 EVT VT = Op.getValueType();
837 if (VT.isVector() || !VT.isInteger())
840 // If operation type is 'undesirable', e.g. i16 on x86, consider
842 unsigned Opc = Op.getOpcode();
843 if (TLI.isTypeDesirableForOp(Opc, VT))
847 // Consult target whether it is a good idea to promote this operation and
848 // what's the right type to promote it to.
849 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
850 assert(PVT != VT && "Don't know what type to promote to!");
852 bool Replace0 = false;
853 SDValue N0 = Op.getOperand(0);
854 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
855 if (NN0.getNode() == 0)
858 bool Replace1 = false;
859 SDValue N1 = Op.getOperand(1);
864 NN1 = PromoteOperand(N1, PVT, Replace1);
865 if (NN1.getNode() == 0)
869 AddToWorkList(NN0.getNode());
871 AddToWorkList(NN1.getNode());
874 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
876 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
878 DEBUG(dbgs() << "\nPromoting ";
879 Op.getNode()->dump(&DAG));
881 return DAG.getNode(ISD::TRUNCATE, dl, VT,
882 DAG.getNode(Opc, dl, PVT, NN0, NN1));
887 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
888 /// target indicates it is beneficial. e.g. On x86, it's usually better to
889 /// promote i16 operations to i32 since i16 instructions are longer.
890 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
891 if (!LegalOperations)
894 EVT VT = Op.getValueType();
895 if (VT.isVector() || !VT.isInteger())
898 // If operation type is 'undesirable', e.g. i16 on x86, consider
900 unsigned Opc = Op.getOpcode();
901 if (TLI.isTypeDesirableForOp(Opc, VT))
905 // Consult target whether it is a good idea to promote this operation and
906 // what's the right type to promote it to.
907 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
908 assert(PVT != VT && "Don't know what type to promote to!");
910 bool Replace = false;
911 SDValue N0 = Op.getOperand(0);
913 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
914 else if (Opc == ISD::SRL)
915 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
917 N0 = PromoteOperand(N0, PVT, Replace);
918 if (N0.getNode() == 0)
921 AddToWorkList(N0.getNode());
923 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
925 DEBUG(dbgs() << "\nPromoting ";
926 Op.getNode()->dump(&DAG));
928 return DAG.getNode(ISD::TRUNCATE, dl, VT,
929 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
934 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
935 if (!LegalOperations)
938 EVT VT = Op.getValueType();
939 if (VT.isVector() || !VT.isInteger())
942 // If operation type is 'undesirable', e.g. i16 on x86, consider
944 unsigned Opc = Op.getOpcode();
945 if (TLI.isTypeDesirableForOp(Opc, VT))
949 // Consult target whether it is a good idea to promote this operation and
950 // what's the right type to promote it to.
951 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
952 assert(PVT != VT && "Don't know what type to promote to!");
953 // fold (aext (aext x)) -> (aext x)
954 // fold (aext (zext x)) -> (zext x)
955 // fold (aext (sext x)) -> (sext x)
956 DEBUG(dbgs() << "\nPromoting ";
957 Op.getNode()->dump(&DAG));
958 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
963 bool DAGCombiner::PromoteLoad(SDValue Op) {
964 if (!LegalOperations)
967 EVT VT = Op.getValueType();
968 if (VT.isVector() || !VT.isInteger())
971 // If operation type is 'undesirable', e.g. i16 on x86, consider
973 unsigned Opc = Op.getOpcode();
974 if (TLI.isTypeDesirableForOp(Opc, VT))
978 // Consult target whether it is a good idea to promote this operation and
979 // what's the right type to promote it to.
980 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
981 assert(PVT != VT && "Don't know what type to promote to!");
984 SDNode *N = Op.getNode();
985 LoadSDNode *LD = cast<LoadSDNode>(N);
986 EVT MemVT = LD->getMemoryVT();
987 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
988 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
990 : LD->getExtensionType();
991 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
992 LD->getChain(), LD->getBasePtr(),
993 MemVT, LD->getMemOperand());
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 return DAG.getConstant(0, VT);
1647 SDValue DAGCombiner::visitSUB(SDNode *N) {
1648 SDValue N0 = N->getOperand(0);
1649 SDValue N1 = N->getOperand(1);
1650 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1651 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1652 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1653 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1654 EVT VT = N0.getValueType();
1657 if (VT.isVector()) {
1658 SDValue FoldedVOp = SimplifyVBinOp(N);
1659 if (FoldedVOp.getNode()) return FoldedVOp;
1661 // fold (sub x, 0) -> x, vector edition
1662 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1666 // fold (sub x, x) -> 0
1667 // FIXME: Refactor this and xor and other similar operations together.
1669 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1670 // fold (sub c1, c2) -> c1-c2
1672 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1673 // fold (sub x, c) -> (add x, -c)
1675 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1676 DAG.getConstant(-N1C->getAPIntValue(), VT));
1677 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1678 if (N0C && N0C->isAllOnesValue())
1679 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1680 // fold A-(A-B) -> B
1681 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1682 return N1.getOperand(1);
1683 // fold (A+B)-A -> B
1684 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1685 return N0.getOperand(1);
1686 // fold (A+B)-B -> A
1687 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1688 return N0.getOperand(0);
1689 // fold C2-(A+C1) -> (C2-C1)-A
1690 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1691 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1693 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1696 // fold ((A+(B+or-C))-B) -> A+or-C
1697 if (N0.getOpcode() == ISD::ADD &&
1698 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1699 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1700 N0.getOperand(1).getOperand(0) == N1)
1701 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1702 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1703 // fold ((A+(C+B))-B) -> A+C
1704 if (N0.getOpcode() == ISD::ADD &&
1705 N0.getOperand(1).getOpcode() == ISD::ADD &&
1706 N0.getOperand(1).getOperand(1) == N1)
1707 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1708 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1709 // fold ((A-(B-C))-C) -> A-B
1710 if (N0.getOpcode() == ISD::SUB &&
1711 N0.getOperand(1).getOpcode() == ISD::SUB &&
1712 N0.getOperand(1).getOperand(1) == N1)
1713 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1714 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1716 // If either operand of a sub is undef, the result is undef
1717 if (N0.getOpcode() == ISD::UNDEF)
1719 if (N1.getOpcode() == ISD::UNDEF)
1722 // If the relocation model supports it, consider symbol offsets.
1723 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1724 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1725 // fold (sub Sym, c) -> Sym-c
1726 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1727 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1729 (uint64_t)N1C->getSExtValue());
1730 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1731 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1732 if (GA->getGlobal() == GB->getGlobal())
1733 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1740 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1741 SDValue N0 = N->getOperand(0);
1742 SDValue N1 = N->getOperand(1);
1743 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1744 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1745 EVT VT = N0.getValueType();
1747 // If the flag result is dead, turn this into an SUB.
1748 if (!N->hasAnyUseOfValue(1))
1749 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1750 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1753 // fold (subc x, x) -> 0 + no borrow
1755 return CombineTo(N, DAG.getConstant(0, VT),
1756 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1759 // fold (subc x, 0) -> x + no borrow
1760 if (N1C && N1C->isNullValue())
1761 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1764 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1765 if (N0C && N0C->isAllOnesValue())
1766 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1767 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1773 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1774 SDValue N0 = N->getOperand(0);
1775 SDValue N1 = N->getOperand(1);
1776 SDValue CarryIn = N->getOperand(2);
1778 // fold (sube x, y, false) -> (subc x, y)
1779 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1780 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1785 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1786 /// elements are all the same constant or undefined.
1787 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1788 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1793 unsigned SplatBitSize;
1795 EVT EltVT = N->getValueType(0).getVectorElementType();
1796 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1798 EltVT.getSizeInBits() >= SplatBitSize);
1801 SDValue DAGCombiner::visitMUL(SDNode *N) {
1802 SDValue N0 = N->getOperand(0);
1803 SDValue N1 = N->getOperand(1);
1804 EVT VT = N0.getValueType();
1806 // fold (mul x, undef) -> 0
1807 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1808 return DAG.getConstant(0, VT);
1810 bool N0IsConst = false;
1811 bool N1IsConst = false;
1812 APInt ConstValue0, ConstValue1;
1814 if (VT.isVector()) {
1815 SDValue FoldedVOp = SimplifyVBinOp(N);
1816 if (FoldedVOp.getNode()) return FoldedVOp;
1818 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1819 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1821 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1822 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1824 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1825 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1829 // fold (mul c1, c2) -> c1*c2
1830 if (N0IsConst && N1IsConst)
1831 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1833 // canonicalize constant to RHS
1834 if (N0IsConst && !N1IsConst)
1835 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1836 // fold (mul x, 0) -> 0
1837 if (N1IsConst && ConstValue1 == 0)
1839 // We require a splat of the entire scalar bit width for non-contiguous
1842 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1843 // fold (mul x, 1) -> x
1844 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1846 // fold (mul x, -1) -> 0-x
1847 if (N1IsConst && ConstValue1.isAllOnesValue())
1848 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849 DAG.getConstant(0, VT), N0);
1850 // fold (mul x, (1 << c)) -> x << c
1851 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1852 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1853 DAG.getConstant(ConstValue1.logBase2(),
1854 getShiftAmountTy(N0.getValueType())));
1855 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1856 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1857 unsigned Log2Val = (-ConstValue1).logBase2();
1858 // FIXME: If the input is something that is easily negated (e.g. a
1859 // single-use add), we should put the negate there.
1860 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1861 DAG.getConstant(0, VT),
1862 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1863 DAG.getConstant(Log2Val,
1864 getShiftAmountTy(N0.getValueType()))));
1868 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1869 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1870 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1871 isa<ConstantSDNode>(N0.getOperand(1)))) {
1872 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1873 N1, N0.getOperand(1));
1874 AddToWorkList(C3.getNode());
1875 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1876 N0.getOperand(0), C3);
1879 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1882 SDValue Sh(0,0), Y(0,0);
1883 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1884 if (N0.getOpcode() == ISD::SHL &&
1885 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1886 isa<ConstantSDNode>(N0.getOperand(1))) &&
1887 N0.getNode()->hasOneUse()) {
1889 } else if (N1.getOpcode() == ISD::SHL &&
1890 isa<ConstantSDNode>(N1.getOperand(1)) &&
1891 N1.getNode()->hasOneUse()) {
1896 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1897 Sh.getOperand(0), Y);
1898 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1899 Mul, Sh.getOperand(1));
1903 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1904 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1905 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1906 isa<ConstantSDNode>(N0.getOperand(1))))
1907 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1908 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1909 N0.getOperand(0), N1),
1910 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1911 N0.getOperand(1), N1));
1914 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1915 if (RMUL.getNode() != 0)
1921 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1922 SDValue N0 = N->getOperand(0);
1923 SDValue N1 = N->getOperand(1);
1924 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1925 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1926 EVT VT = N->getValueType(0);
1929 if (VT.isVector()) {
1930 SDValue FoldedVOp = SimplifyVBinOp(N);
1931 if (FoldedVOp.getNode()) return FoldedVOp;
1934 // fold (sdiv c1, c2) -> c1/c2
1935 if (N0C && N1C && !N1C->isNullValue())
1936 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1937 // fold (sdiv X, 1) -> X
1938 if (N1C && N1C->getAPIntValue() == 1LL)
1940 // fold (sdiv X, -1) -> 0-X
1941 if (N1C && N1C->isAllOnesValue())
1942 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1943 DAG.getConstant(0, VT), N0);
1944 // If we know the sign bits of both operands are zero, strength reduce to a
1945 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1946 if (!VT.isVector()) {
1947 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1948 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1951 // fold (sdiv X, pow2) -> simple ops after legalize
1952 if (N1C && !N1C->isNullValue() &&
1953 (N1C->getAPIntValue().isPowerOf2() ||
1954 (-N1C->getAPIntValue()).isPowerOf2())) {
1955 // If dividing by powers of two is cheap, then don't perform the following
1957 if (TLI.isPow2DivCheap())
1960 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1962 // Splat the sign bit into the register
1963 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1964 DAG.getConstant(VT.getSizeInBits()-1,
1965 getShiftAmountTy(N0.getValueType())));
1966 AddToWorkList(SGN.getNode());
1968 // Add (N0 < 0) ? abs2 - 1 : 0;
1969 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1970 DAG.getConstant(VT.getSizeInBits() - lg2,
1971 getShiftAmountTy(SGN.getValueType())));
1972 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1973 AddToWorkList(SRL.getNode());
1974 AddToWorkList(ADD.getNode()); // Divide by pow2
1975 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1976 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1978 // If we're dividing by a positive value, we're done. Otherwise, we must
1979 // negate the result.
1980 if (N1C->getAPIntValue().isNonNegative())
1983 AddToWorkList(SRA.getNode());
1984 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1985 DAG.getConstant(0, VT), SRA);
1988 // if integer divide is expensive and we satisfy the requirements, emit an
1989 // alternate sequence.
1990 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1991 SDValue Op = BuildSDIV(N);
1992 if (Op.getNode()) return Op;
1996 if (N0.getOpcode() == ISD::UNDEF)
1997 return DAG.getConstant(0, VT);
1998 // X / undef -> undef
1999 if (N1.getOpcode() == ISD::UNDEF)
2005 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2006 SDValue N0 = N->getOperand(0);
2007 SDValue N1 = N->getOperand(1);
2008 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2009 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2010 EVT VT = N->getValueType(0);
2013 if (VT.isVector()) {
2014 SDValue FoldedVOp = SimplifyVBinOp(N);
2015 if (FoldedVOp.getNode()) return FoldedVOp;
2018 // fold (udiv c1, c2) -> c1/c2
2019 if (N0C && N1C && !N1C->isNullValue())
2020 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2021 // fold (udiv x, (1 << c)) -> x >>u c
2022 if (N1C && N1C->getAPIntValue().isPowerOf2())
2023 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2024 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2025 getShiftAmountTy(N0.getValueType())));
2026 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2027 if (N1.getOpcode() == ISD::SHL) {
2028 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2029 if (SHC->getAPIntValue().isPowerOf2()) {
2030 EVT ADDVT = N1.getOperand(1).getValueType();
2031 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2033 DAG.getConstant(SHC->getAPIntValue()
2036 AddToWorkList(Add.getNode());
2037 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2041 // fold (udiv x, c) -> alternate
2042 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2043 SDValue Op = BuildUDIV(N);
2044 if (Op.getNode()) return Op;
2048 if (N0.getOpcode() == ISD::UNDEF)
2049 return DAG.getConstant(0, VT);
2050 // X / undef -> undef
2051 if (N1.getOpcode() == ISD::UNDEF)
2057 SDValue DAGCombiner::visitSREM(SDNode *N) {
2058 SDValue N0 = N->getOperand(0);
2059 SDValue N1 = N->getOperand(1);
2060 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2061 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2062 EVT VT = N->getValueType(0);
2064 // fold (srem c1, c2) -> c1%c2
2065 if (N0C && N1C && !N1C->isNullValue())
2066 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2067 // If we know the sign bits of both operands are zero, strength reduce to a
2068 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2069 if (!VT.isVector()) {
2070 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2071 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2074 // If X/C can be simplified by the division-by-constant logic, lower
2075 // X%C to the equivalent of X-X/C*C.
2076 if (N1C && !N1C->isNullValue()) {
2077 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2078 AddToWorkList(Div.getNode());
2079 SDValue OptimizedDiv = combine(Div.getNode());
2080 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2081 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2083 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2084 AddToWorkList(Mul.getNode());
2090 if (N0.getOpcode() == ISD::UNDEF)
2091 return DAG.getConstant(0, VT);
2092 // X % undef -> undef
2093 if (N1.getOpcode() == ISD::UNDEF)
2099 SDValue DAGCombiner::visitUREM(SDNode *N) {
2100 SDValue N0 = N->getOperand(0);
2101 SDValue N1 = N->getOperand(1);
2102 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2103 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2104 EVT VT = N->getValueType(0);
2106 // fold (urem c1, c2) -> c1%c2
2107 if (N0C && N1C && !N1C->isNullValue())
2108 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2109 // fold (urem x, pow2) -> (and x, pow2-1)
2110 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2111 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2112 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2113 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2114 if (N1.getOpcode() == ISD::SHL) {
2115 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2116 if (SHC->getAPIntValue().isPowerOf2()) {
2118 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2119 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2121 AddToWorkList(Add.getNode());
2122 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2127 // If X/C can be simplified by the division-by-constant logic, lower
2128 // X%C to the equivalent of X-X/C*C.
2129 if (N1C && !N1C->isNullValue()) {
2130 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2131 AddToWorkList(Div.getNode());
2132 SDValue OptimizedDiv = combine(Div.getNode());
2133 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2134 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2136 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2137 AddToWorkList(Mul.getNode());
2143 if (N0.getOpcode() == ISD::UNDEF)
2144 return DAG.getConstant(0, VT);
2145 // X % undef -> undef
2146 if (N1.getOpcode() == ISD::UNDEF)
2152 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2153 SDValue N0 = N->getOperand(0);
2154 SDValue N1 = N->getOperand(1);
2155 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2156 EVT VT = N->getValueType(0);
2159 // fold (mulhs x, 0) -> 0
2160 if (N1C && N1C->isNullValue())
2162 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2163 if (N1C && N1C->getAPIntValue() == 1)
2164 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2165 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2166 getShiftAmountTy(N0.getValueType())));
2167 // fold (mulhs x, undef) -> 0
2168 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2169 return DAG.getConstant(0, VT);
2171 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2173 if (VT.isSimple() && !VT.isVector()) {
2174 MVT Simple = VT.getSimpleVT();
2175 unsigned SimpleSize = Simple.getSizeInBits();
2176 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2177 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2178 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2179 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2180 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2181 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2182 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2183 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2190 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2191 SDValue N0 = N->getOperand(0);
2192 SDValue N1 = N->getOperand(1);
2193 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2194 EVT VT = N->getValueType(0);
2197 // fold (mulhu x, 0) -> 0
2198 if (N1C && N1C->isNullValue())
2200 // fold (mulhu x, 1) -> 0
2201 if (N1C && N1C->getAPIntValue() == 1)
2202 return DAG.getConstant(0, N0.getValueType());
2203 // fold (mulhu x, undef) -> 0
2204 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2205 return DAG.getConstant(0, VT);
2207 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2209 if (VT.isSimple() && !VT.isVector()) {
2210 MVT Simple = VT.getSimpleVT();
2211 unsigned SimpleSize = Simple.getSizeInBits();
2212 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2213 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2214 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2215 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2216 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2217 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2218 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2219 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2226 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2227 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2228 /// that are being performed. Return true if a simplification was made.
2230 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2232 // If the high half is not needed, just compute the low half.
2233 bool HiExists = N->hasAnyUseOfValue(1);
2235 (!LegalOperations ||
2236 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2237 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2238 N->op_begin(), N->getNumOperands());
2239 return CombineTo(N, Res, Res);
2242 // If the low half is not needed, just compute the high half.
2243 bool LoExists = N->hasAnyUseOfValue(0);
2245 (!LegalOperations ||
2246 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2247 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2248 N->op_begin(), N->getNumOperands());
2249 return CombineTo(N, Res, Res);
2252 // If both halves are used, return as it is.
2253 if (LoExists && HiExists)
2256 // If the two computed results can be simplified separately, separate them.
2258 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2259 N->op_begin(), N->getNumOperands());
2260 AddToWorkList(Lo.getNode());
2261 SDValue LoOpt = combine(Lo.getNode());
2262 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2263 (!LegalOperations ||
2264 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2265 return CombineTo(N, LoOpt, LoOpt);
2269 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2270 N->op_begin(), N->getNumOperands());
2271 AddToWorkList(Hi.getNode());
2272 SDValue HiOpt = combine(Hi.getNode());
2273 if (HiOpt.getNode() && HiOpt != Hi &&
2274 (!LegalOperations ||
2275 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2276 return CombineTo(N, HiOpt, HiOpt);
2282 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2283 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2284 if (Res.getNode()) return Res;
2286 EVT VT = N->getValueType(0);
2289 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2291 if (VT.isSimple() && !VT.isVector()) {
2292 MVT Simple = VT.getSimpleVT();
2293 unsigned SimpleSize = Simple.getSizeInBits();
2294 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2295 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2296 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2297 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2298 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2299 // Compute the high part as N1.
2300 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2301 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2302 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2303 // Compute the low part as N0.
2304 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2305 return CombineTo(N, Lo, Hi);
2312 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2313 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2314 if (Res.getNode()) return Res;
2316 EVT VT = N->getValueType(0);
2319 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2321 if (VT.isSimple() && !VT.isVector()) {
2322 MVT Simple = VT.getSimpleVT();
2323 unsigned SimpleSize = Simple.getSizeInBits();
2324 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2325 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2326 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2327 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2328 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2329 // Compute the high part as N1.
2330 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2331 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2332 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2333 // Compute the low part as N0.
2334 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2335 return CombineTo(N, Lo, Hi);
2342 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2343 // (smulo x, 2) -> (saddo x, x)
2344 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2345 if (C2->getAPIntValue() == 2)
2346 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2347 N->getOperand(0), N->getOperand(0));
2352 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2353 // (umulo x, 2) -> (uaddo x, x)
2354 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2355 if (C2->getAPIntValue() == 2)
2356 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2357 N->getOperand(0), N->getOperand(0));
2362 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2363 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2364 if (Res.getNode()) return Res;
2369 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2370 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2371 if (Res.getNode()) return Res;
2376 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2377 /// two operands of the same opcode, try to simplify it.
2378 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2379 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2380 EVT VT = N0.getValueType();
2381 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2383 // Bail early if none of these transforms apply.
2384 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2386 // For each of OP in AND/OR/XOR:
2387 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2388 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2389 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2390 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2392 // do not sink logical op inside of a vector extend, since it may combine
2394 EVT Op0VT = N0.getOperand(0).getValueType();
2395 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2396 N0.getOpcode() == ISD::SIGN_EXTEND ||
2397 // Avoid infinite looping with PromoteIntBinOp.
2398 (N0.getOpcode() == ISD::ANY_EXTEND &&
2399 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2400 (N0.getOpcode() == ISD::TRUNCATE &&
2401 (!TLI.isZExtFree(VT, Op0VT) ||
2402 !TLI.isTruncateFree(Op0VT, VT)) &&
2403 TLI.isTypeLegal(Op0VT))) &&
2405 Op0VT == N1.getOperand(0).getValueType() &&
2406 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2407 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2408 N0.getOperand(0).getValueType(),
2409 N0.getOperand(0), N1.getOperand(0));
2410 AddToWorkList(ORNode.getNode());
2411 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2414 // For each of OP in SHL/SRL/SRA/AND...
2415 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2416 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2417 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2418 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2419 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2420 N0.getOperand(1) == N1.getOperand(1)) {
2421 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2422 N0.getOperand(0).getValueType(),
2423 N0.getOperand(0), N1.getOperand(0));
2424 AddToWorkList(ORNode.getNode());
2425 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2426 ORNode, N0.getOperand(1));
2429 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2430 // Only perform this optimization after type legalization and before
2431 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2432 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2433 // we don't want to undo this promotion.
2434 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2436 if ((N0.getOpcode() == ISD::BITCAST ||
2437 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2438 Level == AfterLegalizeTypes) {
2439 SDValue In0 = N0.getOperand(0);
2440 SDValue In1 = N1.getOperand(0);
2441 EVT In0Ty = In0.getValueType();
2442 EVT In1Ty = In1.getValueType();
2444 // If both incoming values are integers, and the original types are the
2446 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2447 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2448 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2449 AddToWorkList(Op.getNode());
2454 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2455 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2456 // If both shuffles use the same mask, and both shuffle within a single
2457 // vector, then it is worthwhile to move the swizzle after the operation.
2458 // The type-legalizer generates this pattern when loading illegal
2459 // vector types from memory. In many cases this allows additional shuffle
2461 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2462 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2463 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2464 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2465 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2467 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2468 "Inputs to shuffles are not the same type");
2470 unsigned NumElts = VT.getVectorNumElements();
2472 // Check that both shuffles use the same mask. The masks are known to be of
2473 // the same length because the result vector type is the same.
2474 bool SameMask = true;
2475 for (unsigned i = 0; i != NumElts; ++i) {
2476 int Idx0 = SVN0->getMaskElt(i);
2477 int Idx1 = SVN1->getMaskElt(i);
2485 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2486 N0.getOperand(0), N1.getOperand(0));
2487 AddToWorkList(Op.getNode());
2488 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2489 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2496 SDValue DAGCombiner::visitAND(SDNode *N) {
2497 SDValue N0 = N->getOperand(0);
2498 SDValue N1 = N->getOperand(1);
2499 SDValue LL, LR, RL, RR, CC0, CC1;
2500 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2501 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2502 EVT VT = N1.getValueType();
2503 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2506 if (VT.isVector()) {
2507 SDValue FoldedVOp = SimplifyVBinOp(N);
2508 if (FoldedVOp.getNode()) return FoldedVOp;
2510 // fold (and x, 0) -> 0, vector edition
2511 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2513 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2516 // fold (and x, -1) -> x, vector edition
2517 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2519 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2523 // fold (and x, undef) -> 0
2524 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2525 return DAG.getConstant(0, VT);
2526 // fold (and c1, c2) -> c1&c2
2528 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2529 // canonicalize constant to RHS
2531 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2532 // fold (and x, -1) -> x
2533 if (N1C && N1C->isAllOnesValue())
2535 // if (and x, c) is known to be zero, return 0
2536 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2537 APInt::getAllOnesValue(BitWidth)))
2538 return DAG.getConstant(0, VT);
2540 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2541 if (RAND.getNode() != 0)
2543 // fold (and (or x, C), D) -> D if (C & D) == D
2544 if (N1C && N0.getOpcode() == ISD::OR)
2545 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2546 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2548 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2549 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2550 SDValue N0Op0 = N0.getOperand(0);
2551 APInt Mask = ~N1C->getAPIntValue();
2552 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2553 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2554 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2555 N0.getValueType(), N0Op0);
2557 // Replace uses of the AND with uses of the Zero extend node.
2560 // We actually want to replace all uses of the any_extend with the
2561 // zero_extend, to avoid duplicating things. This will later cause this
2562 // AND to be folded.
2563 CombineTo(N0.getNode(), Zext);
2564 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2567 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2568 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2569 // already be zero by virtue of the width of the base type of the load.
2571 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2573 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2574 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2575 N0.getOpcode() == ISD::LOAD) {
2576 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2577 N0 : N0.getOperand(0) );
2579 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2580 // This can be a pure constant or a vector splat, in which case we treat the
2581 // vector as a scalar and use the splat value.
2582 APInt Constant = APInt::getNullValue(1);
2583 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2584 Constant = C->getAPIntValue();
2585 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2586 APInt SplatValue, SplatUndef;
2587 unsigned SplatBitSize;
2589 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2590 SplatBitSize, HasAnyUndefs);
2592 // Undef bits can contribute to a possible optimisation if set, so
2594 SplatValue |= SplatUndef;
2596 // The splat value may be something like "0x00FFFFFF", which means 0 for
2597 // the first vector value and FF for the rest, repeating. We need a mask
2598 // that will apply equally to all members of the vector, so AND all the
2599 // lanes of the constant together.
2600 EVT VT = Vector->getValueType(0);
2601 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2603 // If the splat value has been compressed to a bitlength lower
2604 // than the size of the vector lane, we need to re-expand it to
2606 if (BitWidth > SplatBitSize)
2607 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2608 SplatBitSize < BitWidth;
2609 SplatBitSize = SplatBitSize * 2)
2610 SplatValue |= SplatValue.shl(SplatBitSize);
2612 Constant = APInt::getAllOnesValue(BitWidth);
2613 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2614 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2618 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2619 // actually legal and isn't going to get expanded, else this is a false
2621 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2622 Load->getMemoryVT());
2624 // Resize the constant to the same size as the original memory access before
2625 // extension. If it is still the AllOnesValue then this AND is completely
2628 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2631 switch (Load->getExtensionType()) {
2632 default: B = false; break;
2633 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2635 case ISD::NON_EXTLOAD: B = true; break;
2638 if (B && Constant.isAllOnesValue()) {
2639 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2640 // preserve semantics once we get rid of the AND.
2641 SDValue NewLoad(Load, 0);
2642 if (Load->getExtensionType() == ISD::EXTLOAD) {
2643 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2644 Load->getValueType(0), SDLoc(Load),
2645 Load->getChain(), Load->getBasePtr(),
2646 Load->getOffset(), Load->getMemoryVT(),
2647 Load->getMemOperand());
2648 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2649 if (Load->getNumValues() == 3) {
2650 // PRE/POST_INC loads have 3 values.
2651 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2652 NewLoad.getValue(2) };
2653 CombineTo(Load, To, 3, true);
2655 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2659 // Fold the AND away, taking care not to fold to the old load node if we
2661 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2663 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2666 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2667 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2668 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2669 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2671 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2672 LL.getValueType().isInteger()) {
2673 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2674 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2675 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2676 LR.getValueType(), LL, RL);
2677 AddToWorkList(ORNode.getNode());
2678 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2680 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2681 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2682 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2683 LR.getValueType(), LL, RL);
2684 AddToWorkList(ANDNode.getNode());
2685 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2687 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2688 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2689 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2690 LR.getValueType(), LL, RL);
2691 AddToWorkList(ORNode.getNode());
2692 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2695 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2696 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2697 Op0 == Op1 && LL.getValueType().isInteger() &&
2698 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2699 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2700 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2701 cast<ConstantSDNode>(RR)->isNullValue()))) {
2702 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2703 LL, DAG.getConstant(1, LL.getValueType()));
2704 AddToWorkList(ADDNode.getNode());
2705 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2706 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2708 // canonicalize equivalent to ll == rl
2709 if (LL == RR && LR == RL) {
2710 Op1 = ISD::getSetCCSwappedOperands(Op1);
2713 if (LL == RL && LR == RR) {
2714 bool isInteger = LL.getValueType().isInteger();
2715 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2716 if (Result != ISD::SETCC_INVALID &&
2717 (!LegalOperations ||
2718 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2719 TLI.isOperationLegal(ISD::SETCC,
2720 getSetCCResultType(N0.getSimpleValueType())))))
2721 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2726 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2727 if (N0.getOpcode() == N1.getOpcode()) {
2728 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2729 if (Tmp.getNode()) return Tmp;
2732 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2733 // fold (and (sra)) -> (and (srl)) when possible.
2734 if (!VT.isVector() &&
2735 SimplifyDemandedBits(SDValue(N, 0)))
2736 return SDValue(N, 0);
2738 // fold (zext_inreg (extload x)) -> (zextload x)
2739 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2740 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2741 EVT MemVT = LN0->getMemoryVT();
2742 // If we zero all the possible extended bits, then we can turn this into
2743 // a zextload if we are running before legalize or the operation is legal.
2744 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2745 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2746 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2747 ((!LegalOperations && !LN0->isVolatile()) ||
2748 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2749 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2750 LN0->getChain(), LN0->getBasePtr(),
2751 MemVT, LN0->getMemOperand());
2753 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2754 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2757 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2758 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2760 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2761 EVT MemVT = LN0->getMemoryVT();
2762 // If we zero all the possible extended bits, then we can turn this into
2763 // a zextload if we are running before legalize or the operation is legal.
2764 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2765 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2766 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2767 ((!LegalOperations && !LN0->isVolatile()) ||
2768 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2769 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2770 LN0->getChain(), LN0->getBasePtr(),
2771 MemVT, LN0->getMemOperand());
2773 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2774 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2778 // fold (and (load x), 255) -> (zextload x, i8)
2779 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2780 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2781 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2782 (N0.getOpcode() == ISD::ANY_EXTEND &&
2783 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2784 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2785 LoadSDNode *LN0 = HasAnyExt
2786 ? cast<LoadSDNode>(N0.getOperand(0))
2787 : cast<LoadSDNode>(N0);
2788 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2789 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2790 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2791 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2792 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2793 EVT LoadedVT = LN0->getMemoryVT();
2795 if (ExtVT == LoadedVT &&
2796 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2797 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2800 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2801 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2802 LN0->getMemOperand());
2804 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2805 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2808 // Do not change the width of a volatile load.
2809 // Do not generate loads of non-round integer types since these can
2810 // be expensive (and would be wrong if the type is not byte sized).
2811 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2812 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2813 EVT PtrType = LN0->getOperand(1).getValueType();
2815 unsigned Alignment = LN0->getAlignment();
2816 SDValue NewPtr = LN0->getBasePtr();
2818 // For big endian targets, we need to add an offset to the pointer
2819 // to load the correct bytes. For little endian systems, we merely
2820 // need to read fewer bytes from the same pointer.
2821 if (TLI.isBigEndian()) {
2822 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2823 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2824 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2825 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2826 NewPtr, DAG.getConstant(PtrOff, PtrType));
2827 Alignment = MinAlign(Alignment, PtrOff);
2830 AddToWorkList(NewPtr.getNode());
2832 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2834 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2835 LN0->getChain(), NewPtr,
2836 LN0->getPointerInfo(),
2837 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2838 Alignment, LN0->getTBAAInfo());
2840 CombineTo(LN0, Load, Load.getValue(1));
2841 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2847 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2848 VT.getSizeInBits() <= 64) {
2849 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2850 APInt ADDC = ADDI->getAPIntValue();
2851 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2852 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2853 // immediate for an add, but it is legal if its top c2 bits are set,
2854 // transform the ADD so the immediate doesn't need to be materialized
2856 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2857 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2858 SRLI->getZExtValue());
2859 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2861 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2863 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2864 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2865 CombineTo(N0.getNode(), NewAdd);
2866 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2874 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2875 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2876 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2877 N0.getOperand(1), false);
2878 if (BSwap.getNode())
2885 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2887 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2888 bool DemandHighBits) {
2889 if (!LegalOperations)
2892 EVT VT = N->getValueType(0);
2893 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2895 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2898 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2899 bool LookPassAnd0 = false;
2900 bool LookPassAnd1 = false;
2901 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2903 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2905 if (N0.getOpcode() == ISD::AND) {
2906 if (!N0.getNode()->hasOneUse())
2908 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2909 if (!N01C || N01C->getZExtValue() != 0xFF00)
2911 N0 = N0.getOperand(0);
2912 LookPassAnd0 = true;
2915 if (N1.getOpcode() == ISD::AND) {
2916 if (!N1.getNode()->hasOneUse())
2918 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2919 if (!N11C || N11C->getZExtValue() != 0xFF)
2921 N1 = N1.getOperand(0);
2922 LookPassAnd1 = true;
2925 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2927 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2929 if (!N0.getNode()->hasOneUse() ||
2930 !N1.getNode()->hasOneUse())
2933 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2934 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2937 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2940 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2941 SDValue N00 = N0->getOperand(0);
2942 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2943 if (!N00.getNode()->hasOneUse())
2945 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2946 if (!N001C || N001C->getZExtValue() != 0xFF)
2948 N00 = N00.getOperand(0);
2949 LookPassAnd0 = true;
2952 SDValue N10 = N1->getOperand(0);
2953 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2954 if (!N10.getNode()->hasOneUse())
2956 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2957 if (!N101C || N101C->getZExtValue() != 0xFF00)
2959 N10 = N10.getOperand(0);
2960 LookPassAnd1 = true;
2966 // Make sure everything beyond the low halfword gets set to zero since the SRL
2967 // 16 will clear the top bits.
2968 unsigned OpSizeInBits = VT.getSizeInBits();
2969 if (DemandHighBits && OpSizeInBits > 16) {
2970 // If the left-shift isn't masked out then the only way this is a bswap is
2971 // if all bits beyond the low 8 are 0. In that case the entire pattern
2972 // reduces to a left shift anyway: leave it for other parts of the combiner.
2976 // However, if the right shift isn't masked out then it might be because
2977 // it's not needed. See if we can spot that too.
2978 if (!LookPassAnd1 &&
2979 !DAG.MaskedValueIsZero(
2980 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2984 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2985 if (OpSizeInBits > 16)
2986 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2987 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2991 /// isBSwapHWordElement - Return true if the specified node is an element
2992 /// that makes up a 32-bit packed halfword byteswap. i.e.
2993 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2994 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
2995 if (!N.getNode()->hasOneUse())
2998 unsigned Opc = N.getOpcode();
2999 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3002 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3007 switch (N1C->getZExtValue()) {
3010 case 0xFF: Num = 0; break;
3011 case 0xFF00: Num = 1; break;
3012 case 0xFF0000: Num = 2; break;
3013 case 0xFF000000: Num = 3; break;
3016 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3017 SDValue N0 = N.getOperand(0);
3018 if (Opc == ISD::AND) {
3019 if (Num == 0 || Num == 2) {
3021 // (x >> 8) & 0xff0000
3022 if (N0.getOpcode() != ISD::SRL)
3024 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3025 if (!C || C->getZExtValue() != 8)
3028 // (x << 8) & 0xff00
3029 // (x << 8) & 0xff000000
3030 if (N0.getOpcode() != ISD::SHL)
3032 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3033 if (!C || C->getZExtValue() != 8)
3036 } else if (Opc == ISD::SHL) {
3038 // (x & 0xff0000) << 8
3039 if (Num != 0 && Num != 2)
3041 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3042 if (!C || C->getZExtValue() != 8)
3044 } else { // Opc == ISD::SRL
3045 // (x & 0xff00) >> 8
3046 // (x & 0xff000000) >> 8
3047 if (Num != 1 && Num != 3)
3049 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3050 if (!C || C->getZExtValue() != 8)
3057 Parts[Num] = N0.getOperand(0).getNode();
3061 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3062 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3063 /// => (rotl (bswap x), 16)
3064 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3065 if (!LegalOperations)
3068 EVT VT = N->getValueType(0);
3071 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3074 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3076 // (or (or (and), (and)), (or (and), (and)))
3077 // (or (or (or (and), (and)), (and)), (and))
3078 if (N0.getOpcode() != ISD::OR)
3080 SDValue N00 = N0.getOperand(0);
3081 SDValue N01 = N0.getOperand(1);
3083 if (N1.getOpcode() == ISD::OR &&
3084 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3085 // (or (or (and), (and)), (or (and), (and)))
3086 SDValue N000 = N00.getOperand(0);
3087 if (!isBSwapHWordElement(N000, Parts))
3090 SDValue N001 = N00.getOperand(1);
3091 if (!isBSwapHWordElement(N001, Parts))
3093 SDValue N010 = N01.getOperand(0);
3094 if (!isBSwapHWordElement(N010, Parts))
3096 SDValue N011 = N01.getOperand(1);
3097 if (!isBSwapHWordElement(N011, Parts))
3100 // (or (or (or (and), (and)), (and)), (and))
3101 if (!isBSwapHWordElement(N1, Parts))
3103 if (!isBSwapHWordElement(N01, Parts))
3105 if (N00.getOpcode() != ISD::OR)
3107 SDValue N000 = N00.getOperand(0);
3108 if (!isBSwapHWordElement(N000, Parts))
3110 SDValue N001 = N00.getOperand(1);
3111 if (!isBSwapHWordElement(N001, Parts))
3115 // Make sure the parts are all coming from the same node.
3116 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3119 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3120 SDValue(Parts[0],0));
3122 // Result of the bswap should be rotated by 16. If it's not legal, then
3123 // do (x << 16) | (x >> 16).
3124 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3125 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3126 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3127 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3128 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3129 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3130 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3131 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3134 SDValue DAGCombiner::visitOR(SDNode *N) {
3135 SDValue N0 = N->getOperand(0);
3136 SDValue N1 = N->getOperand(1);
3137 SDValue LL, LR, RL, RR, CC0, CC1;
3138 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3139 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3140 EVT VT = N1.getValueType();
3143 if (VT.isVector()) {
3144 SDValue FoldedVOp = SimplifyVBinOp(N);
3145 if (FoldedVOp.getNode()) return FoldedVOp;
3147 // fold (or x, 0) -> x, vector edition
3148 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3150 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3153 // fold (or x, -1) -> -1, vector edition
3154 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3156 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3160 // fold (or x, undef) -> -1
3161 if (!LegalOperations &&
3162 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3163 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3164 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3166 // fold (or c1, c2) -> c1|c2
3168 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3169 // canonicalize constant to RHS
3171 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3172 // fold (or x, 0) -> x
3173 if (N1C && N1C->isNullValue())
3175 // fold (or x, -1) -> -1
3176 if (N1C && N1C->isAllOnesValue())
3178 // fold (or x, c) -> c iff (x & ~c) == 0
3179 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3182 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3183 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3184 if (BSwap.getNode() != 0)
3186 BSwap = MatchBSwapHWordLow(N, N0, N1);
3187 if (BSwap.getNode() != 0)
3191 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3192 if (ROR.getNode() != 0)
3194 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3195 // iff (c1 & c2) == 0.
3196 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3197 isa<ConstantSDNode>(N0.getOperand(1))) {
3198 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3199 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3200 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3201 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3202 N0.getOperand(0), N1),
3203 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3205 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3206 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3207 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3208 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3210 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3211 LL.getValueType().isInteger()) {
3212 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3213 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3214 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3215 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3216 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3217 LR.getValueType(), LL, RL);
3218 AddToWorkList(ORNode.getNode());
3219 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3221 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3222 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3223 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3224 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3225 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3226 LR.getValueType(), LL, RL);
3227 AddToWorkList(ANDNode.getNode());
3228 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3231 // canonicalize equivalent to ll == rl
3232 if (LL == RR && LR == RL) {
3233 Op1 = ISD::getSetCCSwappedOperands(Op1);
3236 if (LL == RL && LR == RR) {
3237 bool isInteger = LL.getValueType().isInteger();
3238 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3239 if (Result != ISD::SETCC_INVALID &&
3240 (!LegalOperations ||
3241 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3242 TLI.isOperationLegal(ISD::SETCC,
3243 getSetCCResultType(N0.getValueType())))))
3244 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3249 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3250 if (N0.getOpcode() == N1.getOpcode()) {
3251 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3252 if (Tmp.getNode()) return Tmp;
3255 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3256 if (N0.getOpcode() == ISD::AND &&
3257 N1.getOpcode() == ISD::AND &&
3258 N0.getOperand(1).getOpcode() == ISD::Constant &&
3259 N1.getOperand(1).getOpcode() == ISD::Constant &&
3260 // Don't increase # computations.
3261 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3262 // We can only do this xform if we know that bits from X that are set in C2
3263 // but not in C1 are already zero. Likewise for Y.
3264 const APInt &LHSMask =
3265 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3266 const APInt &RHSMask =
3267 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3269 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3270 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3271 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3272 N0.getOperand(0), N1.getOperand(0));
3273 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3274 DAG.getConstant(LHSMask | RHSMask, VT));
3278 // See if this is some rotate idiom.
3279 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3280 return SDValue(Rot, 0);
3282 // Simplify the operands using demanded-bits information.
3283 if (!VT.isVector() &&
3284 SimplifyDemandedBits(SDValue(N, 0)))
3285 return SDValue(N, 0);
3290 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3291 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3292 if (Op.getOpcode() == ISD::AND) {
3293 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3294 Mask = Op.getOperand(1);
3295 Op = Op.getOperand(0);
3301 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3309 // A subroutine of MatchRotate used once we have found an OR of two opposite
3310 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3311 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3312 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3313 // Neg with outer conversions stripped away.
3314 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3315 SDValue Neg, SDValue InnerPos,
3316 SDValue InnerNeg, unsigned PosOpcode,
3317 unsigned NegOpcode, SDLoc DL) {
3318 // Check that Neg == SUBC - Pos.
3319 if (InnerNeg.getOpcode() != ISD::SUB)
3321 ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(InnerNeg.getOperand(0));
3324 if (InnerNeg.getOperand(1) != InnerPos)
3327 // fold (or (shl x, (*ext y)),
3328 // (srl x, (*ext (sub 32, y)))) ->
3329 // (rotl x, y) or (rotr x, (sub 32, y))
3331 // fold (or (shl x, (*ext (sub 32, y))),
3332 // (srl x, (*ext y))) ->
3333 // (rotr x, y) or (rotl x, (sub 32, y))
3334 EVT VT = Shifted.getValueType();
3335 unsigned OpSizeInBits = VT.getSizeInBits();
3336 if (SUBC->getAPIntValue() == OpSizeInBits) {
3337 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3338 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3339 HasPos ? Pos : Neg).getNode();
3342 // fold (or (shl (*ext x), (*ext y)),
3343 // (srl (*ext x), (*ext (sub 32, y)))) ->
3344 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3346 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3347 // (srl (*ext x), (*ext y))) ->
3348 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3349 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3350 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3351 SDValue InnerShifted = Shifted.getOperand(0);
3352 EVT InnerVT = InnerShifted.getValueType();
3353 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3354 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3355 if (InnerVT.getSizeInBits() == SUBC->getAPIntValue()) {
3356 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3357 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3358 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3366 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3367 // idioms for rotate, and if the target supports rotation instructions, generate
3369 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3370 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3371 EVT VT = LHS.getValueType();
3372 if (!TLI.isTypeLegal(VT)) return 0;
3374 // The target must have at least one rotate flavor.
3375 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3376 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3377 if (!HasROTL && !HasROTR) return 0;
3379 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3380 SDValue LHSShift; // The shift.
3381 SDValue LHSMask; // AND value if any.
3382 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3383 return 0; // Not part of a rotate.
3385 SDValue RHSShift; // The shift.
3386 SDValue RHSMask; // AND value if any.
3387 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3388 return 0; // Not part of a rotate.
3390 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3391 return 0; // Not shifting the same value.
3393 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3394 return 0; // Shifts must disagree.
3396 // Canonicalize shl to left side in a shl/srl pair.
3397 if (RHSShift.getOpcode() == ISD::SHL) {
3398 std::swap(LHS, RHS);
3399 std::swap(LHSShift, RHSShift);
3400 std::swap(LHSMask , RHSMask );
3403 unsigned OpSizeInBits = VT.getSizeInBits();
3404 SDValue LHSShiftArg = LHSShift.getOperand(0);
3405 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3406 SDValue RHSShiftArg = RHSShift.getOperand(0);
3407 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3409 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3410 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3411 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3412 RHSShiftAmt.getOpcode() == ISD::Constant) {
3413 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3414 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3415 if ((LShVal + RShVal) != OpSizeInBits)
3418 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3419 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3421 // If there is an AND of either shifted operand, apply it to the result.
3422 if (LHSMask.getNode() || RHSMask.getNode()) {
3423 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3425 if (LHSMask.getNode()) {
3426 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3427 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3429 if (RHSMask.getNode()) {
3430 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3431 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3434 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3437 return Rot.getNode();
3440 // If there is a mask here, and we have a variable shift, we can't be sure
3441 // that we're masking out the right stuff.
3442 if (LHSMask.getNode() || RHSMask.getNode())
3445 // If the shift amount is sign/zext/any-extended just peel it off.
3446 SDValue LExtOp0 = LHSShiftAmt;
3447 SDValue RExtOp0 = RHSShiftAmt;
3448 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3449 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3450 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3451 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3452 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3453 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3454 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3455 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3456 LExtOp0 = LHSShiftAmt.getOperand(0);
3457 RExtOp0 = RHSShiftAmt.getOperand(0);
3460 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3461 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3465 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3466 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3473 SDValue DAGCombiner::visitXOR(SDNode *N) {
3474 SDValue N0 = N->getOperand(0);
3475 SDValue N1 = N->getOperand(1);
3476 SDValue LHS, RHS, CC;
3477 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3478 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3479 EVT VT = N0.getValueType();
3482 if (VT.isVector()) {
3483 SDValue FoldedVOp = SimplifyVBinOp(N);
3484 if (FoldedVOp.getNode()) return FoldedVOp;
3486 // fold (xor x, 0) -> x, vector edition
3487 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3489 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3493 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3494 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3495 return DAG.getConstant(0, VT);
3496 // fold (xor x, undef) -> undef
3497 if (N0.getOpcode() == ISD::UNDEF)
3499 if (N1.getOpcode() == ISD::UNDEF)
3501 // fold (xor c1, c2) -> c1^c2
3503 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3504 // canonicalize constant to RHS
3506 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3507 // fold (xor x, 0) -> x
3508 if (N1C && N1C->isNullValue())
3511 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3512 if (RXOR.getNode() != 0)
3515 // fold !(x cc y) -> (x !cc y)
3516 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3517 bool isInt = LHS.getValueType().isInteger();
3518 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3521 if (!LegalOperations ||
3522 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3523 switch (N0.getOpcode()) {
3525 llvm_unreachable("Unhandled SetCC Equivalent!");
3527 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3528 case ISD::SELECT_CC:
3529 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3530 N0.getOperand(3), NotCC);
3535 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3536 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3537 N0.getNode()->hasOneUse() &&
3538 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3539 SDValue V = N0.getOperand(0);
3540 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3541 DAG.getConstant(1, V.getValueType()));
3542 AddToWorkList(V.getNode());
3543 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3546 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3547 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3548 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3549 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3550 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3551 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3552 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3553 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3554 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3555 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3558 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3559 if (N1C && N1C->isAllOnesValue() &&
3560 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3561 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3562 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3563 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3564 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3565 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3566 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3567 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3570 // fold (xor (and x, y), y) -> (and (not x), y)
3571 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3572 N0->getOperand(1) == N1) {
3573 SDValue X = N0->getOperand(0);
3574 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3575 AddToWorkList(NotX.getNode());
3576 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3578 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3579 if (N1C && N0.getOpcode() == ISD::XOR) {
3580 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3581 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3583 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3584 DAG.getConstant(N1C->getAPIntValue() ^
3585 N00C->getAPIntValue(), VT));
3587 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3588 DAG.getConstant(N1C->getAPIntValue() ^
3589 N01C->getAPIntValue(), VT));
3591 // fold (xor x, x) -> 0
3593 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3595 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3596 if (N0.getOpcode() == N1.getOpcode()) {
3597 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3598 if (Tmp.getNode()) return Tmp;
3601 // Simplify the expression using non-local knowledge.
3602 if (!VT.isVector() &&
3603 SimplifyDemandedBits(SDValue(N, 0)))
3604 return SDValue(N, 0);
3609 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3610 /// the shift amount is a constant.
3611 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3612 SDNode *LHS = N->getOperand(0).getNode();
3613 if (!LHS->hasOneUse()) return SDValue();
3615 // We want to pull some binops through shifts, so that we have (and (shift))
3616 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3617 // thing happens with address calculations, so it's important to canonicalize
3619 bool HighBitSet = false; // Can we transform this if the high bit is set?
3621 switch (LHS->getOpcode()) {
3622 default: return SDValue();
3625 HighBitSet = false; // We can only transform sra if the high bit is clear.
3628 HighBitSet = true; // We can only transform sra if the high bit is set.
3631 if (N->getOpcode() != ISD::SHL)
3632 return SDValue(); // only shl(add) not sr[al](add).
3633 HighBitSet = false; // We can only transform sra if the high bit is clear.
3637 // We require the RHS of the binop to be a constant as well.
3638 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3639 if (!BinOpCst) return SDValue();
3641 // FIXME: disable this unless the input to the binop is a shift by a constant.
3642 // If it is not a shift, it pessimizes some common cases like:
3644 // void foo(int *X, int i) { X[i & 1235] = 1; }
3645 // int bar(int *X, int i) { return X[i & 255]; }
3646 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3647 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3648 BinOpLHSVal->getOpcode() != ISD::SRA &&
3649 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3650 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3653 EVT VT = N->getValueType(0);
3655 // If this is a signed shift right, and the high bit is modified by the
3656 // logical operation, do not perform the transformation. The highBitSet
3657 // boolean indicates the value of the high bit of the constant which would
3658 // cause it to be modified for this operation.
3659 if (N->getOpcode() == ISD::SRA) {
3660 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3661 if (BinOpRHSSignSet != HighBitSet)
3665 // Fold the constants, shifting the binop RHS by the shift amount.
3666 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3668 LHS->getOperand(1), N->getOperand(1));
3670 // Create the new shift.
3671 SDValue NewShift = DAG.getNode(N->getOpcode(),
3672 SDLoc(LHS->getOperand(0)),
3673 VT, LHS->getOperand(0), N->getOperand(1));
3675 // Create the new binop.
3676 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3679 SDValue DAGCombiner::visitSHL(SDNode *N) {
3680 SDValue N0 = N->getOperand(0);
3681 SDValue N1 = N->getOperand(1);
3682 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3683 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3684 EVT VT = N0.getValueType();
3685 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3688 if (VT.isVector()) {
3689 SDValue FoldedVOp = SimplifyVBinOp(N);
3690 if (FoldedVOp.getNode()) return FoldedVOp;
3693 // fold (shl c1, c2) -> c1<<c2
3695 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3696 // fold (shl 0, x) -> 0
3697 if (N0C && N0C->isNullValue())
3699 // fold (shl x, c >= size(x)) -> undef
3700 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3701 return DAG.getUNDEF(VT);
3702 // fold (shl x, 0) -> x
3703 if (N1C && N1C->isNullValue())
3705 // fold (shl undef, x) -> 0
3706 if (N0.getOpcode() == ISD::UNDEF)
3707 return DAG.getConstant(0, VT);
3708 // if (shl x, c) is known to be zero, return 0
3709 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3710 APInt::getAllOnesValue(OpSizeInBits)))
3711 return DAG.getConstant(0, VT);
3712 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3713 if (N1.getOpcode() == ISD::TRUNCATE &&
3714 N1.getOperand(0).getOpcode() == ISD::AND &&
3715 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3716 SDValue N101 = N1.getOperand(0).getOperand(1);
3717 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3718 EVT TruncVT = N1.getValueType();
3719 SDValue N100 = N1.getOperand(0).getOperand(0);
3720 APInt TruncC = N101C->getAPIntValue();
3721 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3722 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3723 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3724 DAG.getNode(ISD::TRUNCATE,
3727 DAG.getConstant(TruncC, TruncVT)));
3731 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3732 return SDValue(N, 0);
3734 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3735 if (N1C && N0.getOpcode() == ISD::SHL &&
3736 N0.getOperand(1).getOpcode() == ISD::Constant) {
3737 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3738 uint64_t c2 = N1C->getZExtValue();
3739 if (c1 + c2 >= OpSizeInBits)
3740 return DAG.getConstant(0, VT);
3741 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3742 DAG.getConstant(c1 + c2, N1.getValueType()));
3745 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3746 // For this to be valid, the second form must not preserve any of the bits
3747 // that are shifted out by the inner shift in the first form. This means
3748 // the outer shift size must be >= the number of bits added by the ext.
3749 // As a corollary, we don't care what kind of ext it is.
3750 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3751 N0.getOpcode() == ISD::ANY_EXTEND ||
3752 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3753 N0.getOperand(0).getOpcode() == ISD::SHL &&
3754 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3756 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3757 uint64_t c2 = N1C->getZExtValue();
3758 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3759 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3760 if (c2 >= OpSizeInBits - InnerShiftSize) {
3761 if (c1 + c2 >= OpSizeInBits)
3762 return DAG.getConstant(0, VT);
3763 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3764 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3765 N0.getOperand(0)->getOperand(0)),
3766 DAG.getConstant(c1 + c2, N1.getValueType()));
3770 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3771 // Only fold this if the inner zext has no other uses to avoid increasing
3772 // the total number of instructions.
3773 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3774 N0.getOperand(0).getOpcode() == ISD::SRL &&
3775 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3777 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3778 if (c1 < VT.getSizeInBits()) {
3779 uint64_t c2 = N1C->getZExtValue();
3781 SDValue NewOp0 = N0.getOperand(0);
3782 EVT CountVT = NewOp0.getOperand(1).getValueType();
3783 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3784 NewOp0, DAG.getConstant(c2, CountVT));
3785 AddToWorkList(NewSHL.getNode());
3786 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3791 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3792 // (and (srl x, (sub c1, c2), MASK)
3793 // Only fold this if the inner shift has no other uses -- if it does, folding
3794 // this will increase the total number of instructions.
3795 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3796 N0.getOperand(1).getOpcode() == ISD::Constant) {
3797 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3798 if (c1 < VT.getSizeInBits()) {
3799 uint64_t c2 = N1C->getZExtValue();
3800 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3801 VT.getSizeInBits() - c1);
3804 Mask = Mask.shl(c2-c1);
3805 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3806 DAG.getConstant(c2-c1, N1.getValueType()));
3808 Mask = Mask.lshr(c1-c2);
3809 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3810 DAG.getConstant(c1-c2, N1.getValueType()));
3812 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3813 DAG.getConstant(Mask, VT));
3816 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3817 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3818 SDValue HiBitsMask =
3819 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3820 VT.getSizeInBits() -
3821 N1C->getZExtValue()),
3823 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3828 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3829 if (NewSHL.getNode())
3836 SDValue DAGCombiner::visitSRA(SDNode *N) {
3837 SDValue N0 = N->getOperand(0);
3838 SDValue N1 = N->getOperand(1);
3839 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3840 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3841 EVT VT = N0.getValueType();
3842 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3845 if (VT.isVector()) {
3846 SDValue FoldedVOp = SimplifyVBinOp(N);
3847 if (FoldedVOp.getNode()) return FoldedVOp;
3850 // fold (sra c1, c2) -> (sra c1, c2)
3852 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3853 // fold (sra 0, x) -> 0
3854 if (N0C && N0C->isNullValue())
3856 // fold (sra -1, x) -> -1
3857 if (N0C && N0C->isAllOnesValue())
3859 // fold (sra x, (setge c, size(x))) -> undef
3860 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3861 return DAG.getUNDEF(VT);
3862 // fold (sra x, 0) -> x
3863 if (N1C && N1C->isNullValue())
3865 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3867 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3868 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3869 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3871 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3872 ExtVT, VT.getVectorNumElements());
3873 if ((!LegalOperations ||
3874 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3875 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3876 N0.getOperand(0), DAG.getValueType(ExtVT));
3879 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3880 if (N1C && N0.getOpcode() == ISD::SRA) {
3881 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3882 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3883 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3884 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3885 DAG.getConstant(Sum, N1C->getValueType(0)));
3889 // fold (sra (shl X, m), (sub result_size, n))
3890 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3891 // result_size - n != m.
3892 // If truncate is free for the target sext(shl) is likely to result in better
3894 if (N0.getOpcode() == ISD::SHL) {
3895 // Get the two constanst of the shifts, CN0 = m, CN = n.
3896 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3898 // Determine what the truncate's result bitsize and type would be.
3900 EVT::getIntegerVT(*DAG.getContext(),
3901 OpSizeInBits - N1C->getZExtValue());
3902 // Determine the residual right-shift amount.
3903 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3905 // If the shift is not a no-op (in which case this should be just a sign
3906 // extend already), the truncated to type is legal, sign_extend is legal
3907 // on that type, and the truncate to that type is both legal and free,
3908 // perform the transform.
3909 if ((ShiftAmt > 0) &&
3910 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3911 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3912 TLI.isTruncateFree(VT, TruncVT)) {
3914 SDValue Amt = DAG.getConstant(ShiftAmt,
3915 getShiftAmountTy(N0.getOperand(0).getValueType()));
3916 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3917 N0.getOperand(0), Amt);
3918 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3920 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3921 N->getValueType(0), Trunc);
3926 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3927 if (N1.getOpcode() == ISD::TRUNCATE &&
3928 N1.getOperand(0).getOpcode() == ISD::AND &&
3929 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3930 SDValue N101 = N1.getOperand(0).getOperand(1);
3931 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3932 EVT TruncVT = N1.getValueType();
3933 SDValue N100 = N1.getOperand(0).getOperand(0);
3934 APInt TruncC = N101C->getAPIntValue();
3935 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3936 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3937 DAG.getNode(ISD::AND, SDLoc(N),
3939 DAG.getNode(ISD::TRUNCATE,
3942 DAG.getConstant(TruncC, TruncVT)));
3946 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3947 // if c1 is equal to the number of bits the trunc removes
3948 if (N0.getOpcode() == ISD::TRUNCATE &&
3949 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3950 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3951 N0.getOperand(0).hasOneUse() &&
3952 N0.getOperand(0).getOperand(1).hasOneUse() &&
3953 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3954 EVT LargeVT = N0.getOperand(0).getValueType();
3955 ConstantSDNode *LargeShiftAmt =
3956 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3958 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3959 LargeShiftAmt->getZExtValue()) {
3961 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3962 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3963 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3964 N0.getOperand(0).getOperand(0), Amt);
3965 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3969 // Simplify, based on bits shifted out of the LHS.
3970 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3971 return SDValue(N, 0);
3974 // If the sign bit is known to be zero, switch this to a SRL.
3975 if (DAG.SignBitIsZero(N0))
3976 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3979 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3980 if (NewSRA.getNode())
3987 SDValue DAGCombiner::visitSRL(SDNode *N) {
3988 SDValue N0 = N->getOperand(0);
3989 SDValue N1 = N->getOperand(1);
3990 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3991 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3992 EVT VT = N0.getValueType();
3993 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3996 if (VT.isVector()) {
3997 SDValue FoldedVOp = SimplifyVBinOp(N);
3998 if (FoldedVOp.getNode()) return FoldedVOp;
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);
4324 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4327 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4329 // Split the inputs.
4330 SDValue Lo, Hi, LL, LH, RL, RH;
4331 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4332 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4334 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4335 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4337 return std::make_pair(Lo, Hi);
4340 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4341 SDValue N0 = N->getOperand(0);
4342 SDValue N1 = N->getOperand(1);
4343 SDValue N2 = N->getOperand(2);
4346 // Canonicalize integer abs.
4347 // vselect (setg[te] X, 0), X, -X ->
4348 // vselect (setgt X, -1), X, -X ->
4349 // vselect (setl[te] X, 0), -X, X ->
4350 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4351 if (N0.getOpcode() == ISD::SETCC) {
4352 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4353 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4355 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4357 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4358 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4359 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4360 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4361 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4362 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4363 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4366 EVT VT = LHS.getValueType();
4367 SDValue Shift = DAG.getNode(
4368 ISD::SRA, DL, VT, LHS,
4369 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4370 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4371 AddToWorkList(Shift.getNode());
4372 AddToWorkList(Add.getNode());
4373 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4377 // If the VSELECT result requires splitting and the mask is provided by a
4378 // SETCC, then split both nodes and its operands before legalization. This
4379 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4380 // and enables future optimizations (e.g. min/max pattern matching on X86).
4381 if (N0.getOpcode() == ISD::SETCC) {
4382 EVT VT = N->getValueType(0);
4384 // Check if any splitting is required.
4385 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4386 TargetLowering::TypeSplitVector)
4389 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4390 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4391 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4392 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4394 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4395 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4397 // Add the new VSELECT nodes to the work list in case they need to be split
4399 AddToWorkList(Lo.getNode());
4400 AddToWorkList(Hi.getNode());
4402 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4408 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4409 SDValue N0 = N->getOperand(0);
4410 SDValue N1 = N->getOperand(1);
4411 SDValue N2 = N->getOperand(2);
4412 SDValue N3 = N->getOperand(3);
4413 SDValue N4 = N->getOperand(4);
4414 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4416 // fold select_cc lhs, rhs, x, x, cc -> x
4420 // Determine if the condition we're dealing with is constant
4421 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4422 N0, N1, CC, SDLoc(N), false);
4423 if (SCC.getNode()) {
4424 AddToWorkList(SCC.getNode());
4426 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4427 if (!SCCC->isNullValue())
4428 return N2; // cond always true -> true val
4430 return N3; // cond always false -> false val
4433 // Fold to a simpler select_cc
4434 if (SCC.getOpcode() == ISD::SETCC)
4435 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4436 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4440 // If we can fold this based on the true/false value, do so.
4441 if (SimplifySelectOps(N, N2, N3))
4442 return SDValue(N, 0); // Don't revisit N.
4444 // fold select_cc into other things, such as min/max/abs
4445 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4448 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4449 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4450 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4454 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4455 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4456 // transformation. Returns true if extension are possible and the above
4457 // mentioned transformation is profitable.
4458 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4460 SmallVectorImpl<SDNode *> &ExtendNodes,
4461 const TargetLowering &TLI) {
4462 bool HasCopyToRegUses = false;
4463 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4464 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4465 UE = N0.getNode()->use_end();
4470 if (UI.getUse().getResNo() != N0.getResNo())
4472 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4473 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4474 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4475 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4476 // Sign bits will be lost after a zext.
4479 for (unsigned i = 0; i != 2; ++i) {
4480 SDValue UseOp = User->getOperand(i);
4483 if (!isa<ConstantSDNode>(UseOp))
4488 ExtendNodes.push_back(User);
4491 // If truncates aren't free and there are users we can't
4492 // extend, it isn't worthwhile.
4495 // Remember if this value is live-out.
4496 if (User->getOpcode() == ISD::CopyToReg)
4497 HasCopyToRegUses = true;
4500 if (HasCopyToRegUses) {
4501 bool BothLiveOut = false;
4502 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4504 SDUse &Use = UI.getUse();
4505 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4511 // Both unextended and extended values are live out. There had better be
4512 // a good reason for the transformation.
4513 return ExtendNodes.size();
4518 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4519 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4520 ISD::NodeType ExtType) {
4521 // Extend SetCC uses if necessary.
4522 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4523 SDNode *SetCC = SetCCs[i];
4524 SmallVector<SDValue, 4> Ops;
4526 for (unsigned j = 0; j != 2; ++j) {
4527 SDValue SOp = SetCC->getOperand(j);
4529 Ops.push_back(ExtLoad);
4531 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4534 Ops.push_back(SetCC->getOperand(2));
4535 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4536 &Ops[0], Ops.size()));
4540 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4541 SDValue N0 = N->getOperand(0);
4542 EVT VT = N->getValueType(0);
4544 // fold (sext c1) -> c1
4545 if (isa<ConstantSDNode>(N0))
4546 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4548 // fold (sext (sext x)) -> (sext x)
4549 // fold (sext (aext x)) -> (sext x)
4550 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4551 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4554 if (N0.getOpcode() == ISD::TRUNCATE) {
4555 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4556 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4557 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4558 if (NarrowLoad.getNode()) {
4559 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4560 if (NarrowLoad.getNode() != N0.getNode()) {
4561 CombineTo(N0.getNode(), NarrowLoad);
4562 // CombineTo deleted the truncate, if needed, but not what's under it.
4565 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4568 // See if the value being truncated is already sign extended. If so, just
4569 // eliminate the trunc/sext pair.
4570 SDValue Op = N0.getOperand(0);
4571 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4572 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4573 unsigned DestBits = VT.getScalarType().getSizeInBits();
4574 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4576 if (OpBits == DestBits) {
4577 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4578 // bits, it is already ready.
4579 if (NumSignBits > DestBits-MidBits)
4581 } else if (OpBits < DestBits) {
4582 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4583 // bits, just sext from i32.
4584 if (NumSignBits > OpBits-MidBits)
4585 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4587 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4588 // bits, just truncate to i32.
4589 if (NumSignBits > OpBits-MidBits)
4590 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4593 // fold (sext (truncate x)) -> (sextinreg x).
4594 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4595 N0.getValueType())) {
4596 if (OpBits < DestBits)
4597 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4598 else if (OpBits > DestBits)
4599 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4600 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4601 DAG.getValueType(N0.getValueType()));
4605 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4606 // None of the supported targets knows how to perform load and sign extend
4607 // on vectors in one instruction. We only perform this transformation on
4609 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4610 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4611 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4612 bool DoXform = true;
4613 SmallVector<SDNode*, 4> SetCCs;
4614 if (!N0.hasOneUse())
4615 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4617 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4618 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4620 LN0->getBasePtr(), N0.getValueType(),
4621 LN0->getMemOperand());
4622 CombineTo(N, ExtLoad);
4623 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4624 N0.getValueType(), ExtLoad);
4625 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4626 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4628 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4632 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4633 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4634 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4635 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4636 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4637 EVT MemVT = LN0->getMemoryVT();
4638 if ((!LegalOperations && !LN0->isVolatile()) ||
4639 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4640 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4642 LN0->getBasePtr(), MemVT,
4643 LN0->getMemOperand());
4644 CombineTo(N, ExtLoad);
4645 CombineTo(N0.getNode(),
4646 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4647 N0.getValueType(), ExtLoad),
4648 ExtLoad.getValue(1));
4649 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4653 // fold (sext (and/or/xor (load x), cst)) ->
4654 // (and/or/xor (sextload x), (sext cst))
4655 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4656 N0.getOpcode() == ISD::XOR) &&
4657 isa<LoadSDNode>(N0.getOperand(0)) &&
4658 N0.getOperand(1).getOpcode() == ISD::Constant &&
4659 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4660 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4661 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4662 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4663 bool DoXform = true;
4664 SmallVector<SDNode*, 4> SetCCs;
4665 if (!N0.hasOneUse())
4666 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4669 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4670 LN0->getChain(), LN0->getBasePtr(),
4672 LN0->getMemOperand());
4673 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4674 Mask = Mask.sext(VT.getSizeInBits());
4675 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4676 ExtLoad, DAG.getConstant(Mask, VT));
4677 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4678 SDLoc(N0.getOperand(0)),
4679 N0.getOperand(0).getValueType(), ExtLoad);
4681 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4682 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4684 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4689 if (N0.getOpcode() == ISD::SETCC) {
4690 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4691 // Only do this before legalize for now.
4692 if (VT.isVector() && !LegalOperations &&
4693 TLI.getBooleanContents(true) ==
4694 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4695 EVT N0VT = N0.getOperand(0).getValueType();
4696 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4697 // of the same size as the compared operands. Only optimize sext(setcc())
4698 // if this is the case.
4699 EVT SVT = getSetCCResultType(N0VT);
4701 // We know that the # elements of the results is the same as the
4702 // # elements of the compare (and the # elements of the compare result
4703 // for that matter). Check to see that they are the same size. If so,
4704 // we know that the element size of the sext'd result matches the
4705 // element size of the compare operands.
4706 if (VT.getSizeInBits() == SVT.getSizeInBits())
4707 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4709 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4711 // If the desired elements are smaller or larger than the source
4712 // elements we can use a matching integer vector type and then
4713 // truncate/sign extend
4714 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4715 if (SVT == MatchingVectorType) {
4716 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4717 N0.getOperand(0), N0.getOperand(1),
4718 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4719 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4723 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4724 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4726 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4728 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4729 NegOne, DAG.getConstant(0, VT),
4730 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4731 if (SCC.getNode()) return SCC;
4732 if (!VT.isVector() &&
4733 (!LegalOperations ||
4734 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4735 return DAG.getSelect(SDLoc(N), VT,
4736 DAG.getSetCC(SDLoc(N),
4737 getSetCCResultType(VT),
4738 N0.getOperand(0), N0.getOperand(1),
4739 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4740 NegOne, DAG.getConstant(0, VT));
4744 // fold (sext x) -> (zext x) if the sign bit is known zero.
4745 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4746 DAG.SignBitIsZero(N0))
4747 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4752 // isTruncateOf - If N is a truncate of some other value, return true, record
4753 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4754 // This function computes KnownZero to avoid a duplicated call to
4755 // ComputeMaskedBits in the caller.
4756 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4759 if (N->getOpcode() == ISD::TRUNCATE) {
4760 Op = N->getOperand(0);
4761 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4765 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4766 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4769 SDValue Op0 = N->getOperand(0);
4770 SDValue Op1 = N->getOperand(1);
4771 assert(Op0.getValueType() == Op1.getValueType());
4773 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4774 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4775 if (COp0 && COp0->isNullValue())
4777 else if (COp1 && COp1->isNullValue())
4782 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4784 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4790 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4791 SDValue N0 = N->getOperand(0);
4792 EVT VT = N->getValueType(0);
4794 // fold (zext c1) -> c1
4795 if (isa<ConstantSDNode>(N0))
4796 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4797 // fold (zext (zext x)) -> (zext x)
4798 // fold (zext (aext x)) -> (zext x)
4799 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4800 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4803 // fold (zext (truncate x)) -> (zext x) or
4804 // (zext (truncate x)) -> (truncate x)
4805 // This is valid when the truncated bits of x are already zero.
4806 // FIXME: We should extend this to work for vectors too.
4809 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4810 APInt TruncatedBits =
4811 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4812 APInt(Op.getValueSizeInBits(), 0) :
4813 APInt::getBitsSet(Op.getValueSizeInBits(),
4814 N0.getValueSizeInBits(),
4815 std::min(Op.getValueSizeInBits(),
4816 VT.getSizeInBits()));
4817 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4818 if (VT.bitsGT(Op.getValueType()))
4819 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4820 if (VT.bitsLT(Op.getValueType()))
4821 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4827 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4828 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4829 if (N0.getOpcode() == ISD::TRUNCATE) {
4830 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4831 if (NarrowLoad.getNode()) {
4832 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4833 if (NarrowLoad.getNode() != N0.getNode()) {
4834 CombineTo(N0.getNode(), NarrowLoad);
4835 // CombineTo deleted the truncate, if needed, but not what's under it.
4838 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4842 // fold (zext (truncate x)) -> (and x, mask)
4843 if (N0.getOpcode() == ISD::TRUNCATE &&
4844 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4846 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4847 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4848 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4849 if (NarrowLoad.getNode()) {
4850 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4851 if (NarrowLoad.getNode() != N0.getNode()) {
4852 CombineTo(N0.getNode(), NarrowLoad);
4853 // CombineTo deleted the truncate, if needed, but not what's under it.
4856 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4859 SDValue Op = N0.getOperand(0);
4860 if (Op.getValueType().bitsLT(VT)) {
4861 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4862 AddToWorkList(Op.getNode());
4863 } else if (Op.getValueType().bitsGT(VT)) {
4864 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4865 AddToWorkList(Op.getNode());
4867 return DAG.getZeroExtendInReg(Op, SDLoc(N),
4868 N0.getValueType().getScalarType());
4871 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4872 // if either of the casts is not free.
4873 if (N0.getOpcode() == ISD::AND &&
4874 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4875 N0.getOperand(1).getOpcode() == ISD::Constant &&
4876 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4877 N0.getValueType()) ||
4878 !TLI.isZExtFree(N0.getValueType(), VT))) {
4879 SDValue X = N0.getOperand(0).getOperand(0);
4880 if (X.getValueType().bitsLT(VT)) {
4881 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4882 } else if (X.getValueType().bitsGT(VT)) {
4883 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4885 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4886 Mask = Mask.zext(VT.getSizeInBits());
4887 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4888 X, DAG.getConstant(Mask, VT));
4891 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4892 // None of the supported targets knows how to perform load and vector_zext
4893 // on vectors in one instruction. We only perform this transformation on
4895 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4896 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4897 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4898 bool DoXform = true;
4899 SmallVector<SDNode*, 4> SetCCs;
4900 if (!N0.hasOneUse())
4901 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4903 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4904 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4906 LN0->getBasePtr(), N0.getValueType(),
4907 LN0->getMemOperand());
4908 CombineTo(N, ExtLoad);
4909 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4910 N0.getValueType(), ExtLoad);
4911 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4913 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4915 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4919 // fold (zext (and/or/xor (load x), cst)) ->
4920 // (and/or/xor (zextload x), (zext cst))
4921 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4922 N0.getOpcode() == ISD::XOR) &&
4923 isa<LoadSDNode>(N0.getOperand(0)) &&
4924 N0.getOperand(1).getOpcode() == ISD::Constant &&
4925 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4926 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4927 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4928 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4929 bool DoXform = true;
4930 SmallVector<SDNode*, 4> SetCCs;
4931 if (!N0.hasOneUse())
4932 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4935 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4936 LN0->getChain(), LN0->getBasePtr(),
4938 LN0->getMemOperand());
4939 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4940 Mask = Mask.zext(VT.getSizeInBits());
4941 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4942 ExtLoad, DAG.getConstant(Mask, VT));
4943 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4944 SDLoc(N0.getOperand(0)),
4945 N0.getOperand(0).getValueType(), ExtLoad);
4947 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4948 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4950 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4955 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4956 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4957 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4958 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4959 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4960 EVT MemVT = LN0->getMemoryVT();
4961 if ((!LegalOperations && !LN0->isVolatile()) ||
4962 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4963 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4965 LN0->getBasePtr(), MemVT,
4966 LN0->getMemOperand());
4967 CombineTo(N, ExtLoad);
4968 CombineTo(N0.getNode(),
4969 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4971 ExtLoad.getValue(1));
4972 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4976 if (N0.getOpcode() == ISD::SETCC) {
4977 if (!LegalOperations && VT.isVector() &&
4978 N0.getValueType().getVectorElementType() == MVT::i1) {
4979 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4980 // Only do this before legalize for now.
4981 EVT N0VT = N0.getOperand(0).getValueType();
4982 EVT EltVT = VT.getVectorElementType();
4983 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4984 DAG.getConstant(1, EltVT));
4985 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4986 // We know that the # elements of the results is the same as the
4987 // # elements of the compare (and the # elements of the compare result
4988 // for that matter). Check to see that they are the same size. If so,
4989 // we know that the element size of the sext'd result matches the
4990 // element size of the compare operands.
4991 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4992 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4994 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4995 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4996 &OneOps[0], OneOps.size()));
4998 // If the desired elements are smaller or larger than the source
4999 // elements we can use a matching integer vector type and then
5000 // truncate/sign extend
5001 EVT MatchingElementType =
5002 EVT::getIntegerVT(*DAG.getContext(),
5003 N0VT.getScalarType().getSizeInBits());
5004 EVT MatchingVectorType =
5005 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5006 N0VT.getVectorNumElements());
5008 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5010 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5011 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5012 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5013 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5014 &OneOps[0], OneOps.size()));
5017 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5019 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5020 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5021 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5022 if (SCC.getNode()) return SCC;
5025 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5026 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5027 isa<ConstantSDNode>(N0.getOperand(1)) &&
5028 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5030 SDValue ShAmt = N0.getOperand(1);
5031 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5032 if (N0.getOpcode() == ISD::SHL) {
5033 SDValue InnerZExt = N0.getOperand(0);
5034 // If the original shl may be shifting out bits, do not perform this
5036 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5037 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5038 if (ShAmtVal > KnownZeroBits)
5044 // Ensure that the shift amount is wide enough for the shifted value.
5045 if (VT.getSizeInBits() >= 256)
5046 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5048 return DAG.getNode(N0.getOpcode(), DL, VT,
5049 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5056 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5057 SDValue N0 = N->getOperand(0);
5058 EVT VT = N->getValueType(0);
5060 // fold (aext c1) -> c1
5061 if (isa<ConstantSDNode>(N0))
5062 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5063 // fold (aext (aext x)) -> (aext x)
5064 // fold (aext (zext x)) -> (zext x)
5065 // fold (aext (sext x)) -> (sext x)
5066 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5067 N0.getOpcode() == ISD::ZERO_EXTEND ||
5068 N0.getOpcode() == ISD::SIGN_EXTEND)
5069 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5071 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5072 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5073 if (N0.getOpcode() == ISD::TRUNCATE) {
5074 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5075 if (NarrowLoad.getNode()) {
5076 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5077 if (NarrowLoad.getNode() != N0.getNode()) {
5078 CombineTo(N0.getNode(), NarrowLoad);
5079 // CombineTo deleted the truncate, if needed, but not what's under it.
5082 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5086 // fold (aext (truncate x))
5087 if (N0.getOpcode() == ISD::TRUNCATE) {
5088 SDValue TruncOp = N0.getOperand(0);
5089 if (TruncOp.getValueType() == VT)
5090 return TruncOp; // x iff x size == zext size.
5091 if (TruncOp.getValueType().bitsGT(VT))
5092 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5093 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5096 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5097 // if the trunc is not free.
5098 if (N0.getOpcode() == ISD::AND &&
5099 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5100 N0.getOperand(1).getOpcode() == ISD::Constant &&
5101 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5102 N0.getValueType())) {
5103 SDValue X = N0.getOperand(0).getOperand(0);
5104 if (X.getValueType().bitsLT(VT)) {
5105 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5106 } else if (X.getValueType().bitsGT(VT)) {
5107 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5109 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5110 Mask = Mask.zext(VT.getSizeInBits());
5111 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5112 X, DAG.getConstant(Mask, VT));
5115 // fold (aext (load x)) -> (aext (truncate (extload x)))
5116 // None of the supported targets knows how to perform load and any_ext
5117 // on vectors in one instruction. We only perform this transformation on
5119 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5120 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5121 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5122 bool DoXform = true;
5123 SmallVector<SDNode*, 4> SetCCs;
5124 if (!N0.hasOneUse())
5125 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5127 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5128 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5130 LN0->getBasePtr(), N0.getValueType(),
5131 LN0->getMemOperand());
5132 CombineTo(N, ExtLoad);
5133 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5134 N0.getValueType(), ExtLoad);
5135 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5136 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5138 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5142 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5143 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5144 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5145 if (N0.getOpcode() == ISD::LOAD &&
5146 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5148 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5149 EVT MemVT = LN0->getMemoryVT();
5150 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5151 VT, LN0->getChain(), LN0->getBasePtr(),
5152 MemVT, LN0->getMemOperand());
5153 CombineTo(N, ExtLoad);
5154 CombineTo(N0.getNode(),
5155 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5156 N0.getValueType(), ExtLoad),
5157 ExtLoad.getValue(1));
5158 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5161 if (N0.getOpcode() == ISD::SETCC) {
5162 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5163 // Only do this before legalize for now.
5164 if (VT.isVector() && !LegalOperations) {
5165 EVT N0VT = N0.getOperand(0).getValueType();
5166 // We know that the # elements of the results is the same as the
5167 // # elements of the compare (and the # elements of the compare result
5168 // for that matter). Check to see that they are the same size. If so,
5169 // we know that the element size of the sext'd result matches the
5170 // element size of the compare operands.
5171 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5172 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5174 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5175 // If the desired elements are smaller or larger than the source
5176 // elements we can use a matching integer vector type and then
5177 // truncate/sign extend
5179 EVT MatchingElementType =
5180 EVT::getIntegerVT(*DAG.getContext(),
5181 N0VT.getScalarType().getSizeInBits());
5182 EVT MatchingVectorType =
5183 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5184 N0VT.getVectorNumElements());
5186 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5188 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5189 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5193 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5195 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5196 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5197 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5205 /// GetDemandedBits - See if the specified operand can be simplified with the
5206 /// knowledge that only the bits specified by Mask are used. If so, return the
5207 /// simpler operand, otherwise return a null SDValue.
5208 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5209 switch (V.getOpcode()) {
5211 case ISD::Constant: {
5212 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5213 assert(CV != 0 && "Const value should be ConstSDNode.");
5214 const APInt &CVal = CV->getAPIntValue();
5215 APInt NewVal = CVal & Mask;
5217 return DAG.getConstant(NewVal, V.getValueType());
5222 // If the LHS or RHS don't contribute bits to the or, drop them.
5223 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5224 return V.getOperand(1);
5225 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5226 return V.getOperand(0);
5229 // Only look at single-use SRLs.
5230 if (!V.getNode()->hasOneUse())
5232 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5233 // See if we can recursively simplify the LHS.
5234 unsigned Amt = RHSC->getZExtValue();
5236 // Watch out for shift count overflow though.
5237 if (Amt >= Mask.getBitWidth()) break;
5238 APInt NewMask = Mask << Amt;
5239 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5240 if (SimplifyLHS.getNode())
5241 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5242 SimplifyLHS, V.getOperand(1));
5248 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5249 /// bits and then truncated to a narrower type and where N is a multiple
5250 /// of number of bits of the narrower type, transform it to a narrower load
5251 /// from address + N / num of bits of new type. If the result is to be
5252 /// extended, also fold the extension to form a extending load.
5253 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5254 unsigned Opc = N->getOpcode();
5256 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5257 SDValue N0 = N->getOperand(0);
5258 EVT VT = N->getValueType(0);
5261 // This transformation isn't valid for vector loads.
5265 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5267 if (Opc == ISD::SIGN_EXTEND_INREG) {
5268 ExtType = ISD::SEXTLOAD;
5269 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5270 } else if (Opc == ISD::SRL) {
5271 // Another special-case: SRL is basically zero-extending a narrower value.
5272 ExtType = ISD::ZEXTLOAD;
5274 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5275 if (!N01) return SDValue();
5276 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5277 VT.getSizeInBits() - N01->getZExtValue());
5279 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5282 unsigned EVTBits = ExtVT.getSizeInBits();
5284 // Do not generate loads of non-round integer types since these can
5285 // be expensive (and would be wrong if the type is not byte sized).
5286 if (!ExtVT.isRound())
5290 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5291 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5292 ShAmt = N01->getZExtValue();
5293 // Is the shift amount a multiple of size of VT?
5294 if ((ShAmt & (EVTBits-1)) == 0) {
5295 N0 = N0.getOperand(0);
5296 // Is the load width a multiple of size of VT?
5297 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5301 // At this point, we must have a load or else we can't do the transform.
5302 if (!isa<LoadSDNode>(N0)) return SDValue();
5304 // Because a SRL must be assumed to *need* to zero-extend the high bits
5305 // (as opposed to anyext the high bits), we can't combine the zextload
5306 // lowering of SRL and an sextload.
5307 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5310 // If the shift amount is larger than the input type then we're not
5311 // accessing any of the loaded bytes. If the load was a zextload/extload
5312 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5313 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5318 // If the load is shifted left (and the result isn't shifted back right),
5319 // we can fold the truncate through the shift.
5320 unsigned ShLeftAmt = 0;
5321 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5322 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5323 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5324 ShLeftAmt = N01->getZExtValue();
5325 N0 = N0.getOperand(0);
5329 // If we haven't found a load, we can't narrow it. Don't transform one with
5330 // multiple uses, this would require adding a new load.
5331 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5334 // Don't change the width of a volatile load.
5335 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5336 if (LN0->isVolatile())
5339 // Verify that we are actually reducing a load width here.
5340 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5343 // For the transform to be legal, the load must produce only two values
5344 // (the value loaded and the chain). Don't transform a pre-increment
5345 // load, for example, which produces an extra value. Otherwise the
5346 // transformation is not equivalent, and the downstream logic to replace
5347 // uses gets things wrong.
5348 if (LN0->getNumValues() > 2)
5351 // If the load that we're shrinking is an extload and we're not just
5352 // discarding the extension we can't simply shrink the load. Bail.
5353 // TODO: It would be possible to merge the extensions in some cases.
5354 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5355 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5358 EVT PtrType = N0.getOperand(1).getValueType();
5360 if (PtrType == MVT::Untyped || PtrType.isExtended())
5361 // It's not possible to generate a constant of extended or untyped type.
5364 // For big endian targets, we need to adjust the offset to the pointer to
5365 // load the correct bytes.
5366 if (TLI.isBigEndian()) {
5367 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5368 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5369 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5372 uint64_t PtrOff = ShAmt / 8;
5373 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5374 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5375 PtrType, LN0->getBasePtr(),
5376 DAG.getConstant(PtrOff, PtrType));
5377 AddToWorkList(NewPtr.getNode());
5380 if (ExtType == ISD::NON_EXTLOAD)
5381 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5382 LN0->getPointerInfo().getWithOffset(PtrOff),
5383 LN0->isVolatile(), LN0->isNonTemporal(),
5384 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5386 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5387 LN0->getPointerInfo().getWithOffset(PtrOff),
5388 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5389 NewAlign, LN0->getTBAAInfo());
5391 // Replace the old load's chain with the new load's chain.
5392 WorkListRemover DeadNodes(*this);
5393 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5395 // Shift the result left, if we've swallowed a left shift.
5396 SDValue Result = Load;
5397 if (ShLeftAmt != 0) {
5398 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5399 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5401 // If the shift amount is as large as the result size (but, presumably,
5402 // no larger than the source) then the useful bits of the result are
5403 // zero; we can't simply return the shortened shift, because the result
5404 // of that operation is undefined.
5405 if (ShLeftAmt >= VT.getSizeInBits())
5406 Result = DAG.getConstant(0, VT);
5408 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5409 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5412 // Return the new loaded value.
5416 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5417 SDValue N0 = N->getOperand(0);
5418 SDValue N1 = N->getOperand(1);
5419 EVT VT = N->getValueType(0);
5420 EVT EVT = cast<VTSDNode>(N1)->getVT();
5421 unsigned VTBits = VT.getScalarType().getSizeInBits();
5422 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5424 // fold (sext_in_reg c1) -> c1
5425 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5426 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5428 // If the input is already sign extended, just drop the extension.
5429 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5432 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5433 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5434 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5435 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5436 N0.getOperand(0), N1);
5438 // fold (sext_in_reg (sext x)) -> (sext x)
5439 // fold (sext_in_reg (aext x)) -> (sext x)
5440 // if x is small enough.
5441 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5442 SDValue N00 = N0.getOperand(0);
5443 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5444 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5445 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5448 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5449 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5450 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5452 // fold operands of sext_in_reg based on knowledge that the top bits are not
5454 if (SimplifyDemandedBits(SDValue(N, 0)))
5455 return SDValue(N, 0);
5457 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5458 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5459 SDValue NarrowLoad = ReduceLoadWidth(N);
5460 if (NarrowLoad.getNode())
5463 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5464 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5465 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5466 if (N0.getOpcode() == ISD::SRL) {
5467 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5468 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5469 // We can turn this into an SRA iff the input to the SRL is already sign
5471 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5472 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5473 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5474 N0.getOperand(0), N0.getOperand(1));
5478 // fold (sext_inreg (extload x)) -> (sextload x)
5479 if (ISD::isEXTLoad(N0.getNode()) &&
5480 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5481 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5482 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5483 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5484 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5485 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5487 LN0->getBasePtr(), EVT,
5488 LN0->getMemOperand());
5489 CombineTo(N, ExtLoad);
5490 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5491 AddToWorkList(ExtLoad.getNode());
5492 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5494 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5495 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5497 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5498 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5499 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5500 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5501 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5503 LN0->getBasePtr(), EVT,
5504 LN0->getMemOperand());
5505 CombineTo(N, ExtLoad);
5506 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5507 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5510 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5511 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5512 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5513 N0.getOperand(1), false);
5514 if (BSwap.getNode() != 0)
5515 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5519 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5520 // into a build_vector.
5521 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5522 SmallVector<SDValue, 8> Elts;
5523 unsigned NumElts = N0->getNumOperands();
5524 unsigned ShAmt = VTBits - EVTBits;
5526 for (unsigned i = 0; i != NumElts; ++i) {
5527 SDValue Op = N0->getOperand(i);
5528 if (Op->getOpcode() == ISD::UNDEF) {
5533 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5534 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5535 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5536 Op.getValueType()));
5539 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5545 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5546 SDValue N0 = N->getOperand(0);
5547 EVT VT = N->getValueType(0);
5548 bool isLE = TLI.isLittleEndian();
5551 if (N0.getValueType() == N->getValueType(0))
5553 // fold (truncate c1) -> c1
5554 if (isa<ConstantSDNode>(N0))
5555 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5556 // fold (truncate (truncate x)) -> (truncate x)
5557 if (N0.getOpcode() == ISD::TRUNCATE)
5558 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5559 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5560 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5561 N0.getOpcode() == ISD::SIGN_EXTEND ||
5562 N0.getOpcode() == ISD::ANY_EXTEND) {
5563 if (N0.getOperand(0).getValueType().bitsLT(VT))
5564 // if the source is smaller than the dest, we still need an extend
5565 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5567 if (N0.getOperand(0).getValueType().bitsGT(VT))
5568 // if the source is larger than the dest, than we just need the truncate
5569 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5570 // if the source and dest are the same type, we can drop both the extend
5571 // and the truncate.
5572 return N0.getOperand(0);
5575 // Fold extract-and-trunc into a narrow extract. For example:
5576 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5577 // i32 y = TRUNCATE(i64 x)
5579 // v16i8 b = BITCAST (v2i64 val)
5580 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5582 // Note: We only run this optimization after type legalization (which often
5583 // creates this pattern) and before operation legalization after which
5584 // we need to be more careful about the vector instructions that we generate.
5585 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5586 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5588 EVT VecTy = N0.getOperand(0).getValueType();
5589 EVT ExTy = N0.getValueType();
5590 EVT TrTy = N->getValueType(0);
5592 unsigned NumElem = VecTy.getVectorNumElements();
5593 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5595 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5596 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5598 SDValue EltNo = N0->getOperand(1);
5599 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5600 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5601 EVT IndexTy = TLI.getVectorIdxTy();
5602 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5604 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5605 NVT, N0.getOperand(0));
5607 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5609 DAG.getConstant(Index, IndexTy));
5613 // Fold a series of buildvector, bitcast, and truncate if possible.
5615 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5616 // (2xi32 (buildvector x, y)).
5617 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5618 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5619 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5620 N0.getOperand(0).hasOneUse()) {
5622 SDValue BuildVect = N0.getOperand(0);
5623 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5624 EVT TruncVecEltTy = VT.getVectorElementType();
5626 // Check that the element types match.
5627 if (BuildVectEltTy == TruncVecEltTy) {
5628 // Now we only need to compute the offset of the truncated elements.
5629 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5630 unsigned TruncVecNumElts = VT.getVectorNumElements();
5631 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5633 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5634 "Invalid number of elements");
5636 SmallVector<SDValue, 8> Opnds;
5637 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5638 Opnds.push_back(BuildVect.getOperand(i));
5640 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5645 // See if we can simplify the input to this truncate through knowledge that
5646 // only the low bits are being used.
5647 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5648 // Currently we only perform this optimization on scalars because vectors
5649 // may have different active low bits.
5650 if (!VT.isVector()) {
5652 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5653 VT.getSizeInBits()));
5654 if (Shorter.getNode())
5655 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5657 // fold (truncate (load x)) -> (smaller load x)
5658 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5659 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5660 SDValue Reduced = ReduceLoadWidth(N);
5661 if (Reduced.getNode())
5663 // Handle the case where the load remains an extending load even
5664 // after truncation.
5665 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5666 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5667 if (!LN0->isVolatile() &&
5668 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5669 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5670 VT, LN0->getChain(), LN0->getBasePtr(),
5672 LN0->getMemOperand());
5673 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5678 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5679 // where ... are all 'undef'.
5680 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5681 SmallVector<EVT, 8> VTs;
5684 unsigned NumDefs = 0;
5686 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5687 SDValue X = N0.getOperand(i);
5688 if (X.getOpcode() != ISD::UNDEF) {
5693 // Stop if more than one members are non-undef.
5696 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5697 VT.getVectorElementType(),
5698 X.getValueType().getVectorNumElements()));
5702 return DAG.getUNDEF(VT);
5705 assert(V.getNode() && "The single defined operand is empty!");
5706 SmallVector<SDValue, 8> Opnds;
5707 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5709 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5712 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5713 AddToWorkList(NV.getNode());
5714 Opnds.push_back(NV);
5716 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5717 &Opnds[0], Opnds.size());
5721 // Simplify the operands using demanded-bits information.
5722 if (!VT.isVector() &&
5723 SimplifyDemandedBits(SDValue(N, 0)))
5724 return SDValue(N, 0);
5729 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5730 SDValue Elt = N->getOperand(i);
5731 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5732 return Elt.getNode();
5733 return Elt.getOperand(Elt.getResNo()).getNode();
5736 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5737 /// if load locations are consecutive.
5738 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5739 assert(N->getOpcode() == ISD::BUILD_PAIR);
5741 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5742 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5743 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5744 LD1->getPointerInfo().getAddrSpace() !=
5745 LD2->getPointerInfo().getAddrSpace())
5747 EVT LD1VT = LD1->getValueType(0);
5749 if (ISD::isNON_EXTLoad(LD2) &&
5751 // If both are volatile this would reduce the number of volatile loads.
5752 // If one is volatile it might be ok, but play conservative and bail out.
5753 !LD1->isVolatile() &&
5754 !LD2->isVolatile() &&
5755 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5756 unsigned Align = LD1->getAlignment();
5757 unsigned NewAlign = TLI.getDataLayout()->
5758 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5760 if (NewAlign <= Align &&
5761 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5762 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5763 LD1->getBasePtr(), LD1->getPointerInfo(),
5764 false, false, false, Align);
5770 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5771 SDValue N0 = N->getOperand(0);
5772 EVT VT = N->getValueType(0);
5774 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5775 // Only do this before legalize, since afterward the target may be depending
5776 // on the bitconvert.
5777 // First check to see if this is all constant.
5779 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5781 bool isSimple = true;
5782 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5783 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5784 N0.getOperand(i).getOpcode() != ISD::Constant &&
5785 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5790 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5791 assert(!DestEltVT.isVector() &&
5792 "Element type of vector ValueType must not be vector!");
5794 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5797 // If the input is a constant, let getNode fold it.
5798 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5799 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5800 if (Res.getNode() != N) {
5801 if (!LegalOperations ||
5802 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5805 // Folding it resulted in an illegal node, and it's too late to
5806 // do that. Clean up the old node and forego the transformation.
5807 // Ideally this won't happen very often, because instcombine
5808 // and the earlier dagcombine runs (where illegal nodes are
5809 // permitted) should have folded most of them already.
5810 DAG.DeleteNode(Res.getNode());
5814 // (conv (conv x, t1), t2) -> (conv x, t2)
5815 if (N0.getOpcode() == ISD::BITCAST)
5816 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5819 // fold (conv (load x)) -> (load (conv*)x)
5820 // If the resultant load doesn't need a higher alignment than the original!
5821 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5822 // Do not change the width of a volatile load.
5823 !cast<LoadSDNode>(N0)->isVolatile() &&
5824 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5825 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
5826 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5827 unsigned Align = TLI.getDataLayout()->
5828 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5829 unsigned OrigAlign = LN0->getAlignment();
5831 if (Align <= OrigAlign) {
5832 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5833 LN0->getBasePtr(), LN0->getPointerInfo(),
5834 LN0->isVolatile(), LN0->isNonTemporal(),
5835 LN0->isInvariant(), OrigAlign,
5836 LN0->getTBAAInfo());
5838 CombineTo(N0.getNode(),
5839 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5840 N0.getValueType(), Load),
5846 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5847 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5848 // This often reduces constant pool loads.
5849 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5850 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5851 N0.getNode()->hasOneUse() && VT.isInteger() &&
5852 !VT.isVector() && !N0.getValueType().isVector()) {
5853 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5855 AddToWorkList(NewConv.getNode());
5857 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5858 if (N0.getOpcode() == ISD::FNEG)
5859 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5860 NewConv, DAG.getConstant(SignBit, VT));
5861 assert(N0.getOpcode() == ISD::FABS);
5862 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5863 NewConv, DAG.getConstant(~SignBit, VT));
5866 // fold (bitconvert (fcopysign cst, x)) ->
5867 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5868 // Note that we don't handle (copysign x, cst) because this can always be
5869 // folded to an fneg or fabs.
5870 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5871 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5872 VT.isInteger() && !VT.isVector()) {
5873 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5874 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5875 if (isTypeLegal(IntXVT)) {
5876 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5877 IntXVT, N0.getOperand(1));
5878 AddToWorkList(X.getNode());
5880 // If X has a different width than the result/lhs, sext it or truncate it.
5881 unsigned VTWidth = VT.getSizeInBits();
5882 if (OrigXWidth < VTWidth) {
5883 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5884 AddToWorkList(X.getNode());
5885 } else if (OrigXWidth > VTWidth) {
5886 // To get the sign bit in the right place, we have to shift it right
5887 // before truncating.
5888 X = DAG.getNode(ISD::SRL, SDLoc(X),
5889 X.getValueType(), X,
5890 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5891 AddToWorkList(X.getNode());
5892 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5893 AddToWorkList(X.getNode());
5896 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5897 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5898 X, DAG.getConstant(SignBit, VT));
5899 AddToWorkList(X.getNode());
5901 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5902 VT, N0.getOperand(0));
5903 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5904 Cst, DAG.getConstant(~SignBit, VT));
5905 AddToWorkList(Cst.getNode());
5907 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5911 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5912 if (N0.getOpcode() == ISD::BUILD_PAIR) {
5913 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5914 if (CombineLD.getNode())
5921 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5922 EVT VT = N->getValueType(0);
5923 return CombineConsecutiveLoads(N, VT);
5926 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5927 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
5928 /// destination element value type.
5929 SDValue DAGCombiner::
5930 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5931 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5933 // If this is already the right type, we're done.
5934 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5936 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5937 unsigned DstBitSize = DstEltVT.getSizeInBits();
5939 // If this is a conversion of N elements of one type to N elements of another
5940 // type, convert each element. This handles FP<->INT cases.
5941 if (SrcBitSize == DstBitSize) {
5942 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5943 BV->getValueType(0).getVectorNumElements());
5945 // Due to the FP element handling below calling this routine recursively,
5946 // we can end up with a scalar-to-vector node here.
5947 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5948 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5949 DAG.getNode(ISD::BITCAST, SDLoc(BV),
5950 DstEltVT, BV->getOperand(0)));
5952 SmallVector<SDValue, 8> Ops;
5953 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5954 SDValue Op = BV->getOperand(i);
5955 // If the vector element type is not legal, the BUILD_VECTOR operands
5956 // are promoted and implicitly truncated. Make that explicit here.
5957 if (Op.getValueType() != SrcEltVT)
5958 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5959 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5961 AddToWorkList(Ops.back().getNode());
5963 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5964 &Ops[0], Ops.size());
5967 // Otherwise, we're growing or shrinking the elements. To avoid having to
5968 // handle annoying details of growing/shrinking FP values, we convert them to
5970 if (SrcEltVT.isFloatingPoint()) {
5971 // Convert the input float vector to a int vector where the elements are the
5973 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5974 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5975 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5979 // Now we know the input is an integer vector. If the output is a FP type,
5980 // convert to integer first, then to FP of the right size.
5981 if (DstEltVT.isFloatingPoint()) {
5982 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5983 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5984 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5986 // Next, convert to FP elements of the same size.
5987 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5990 // Okay, we know the src/dst types are both integers of differing types.
5991 // Handling growing first.
5992 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5993 if (SrcBitSize < DstBitSize) {
5994 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5996 SmallVector<SDValue, 8> Ops;
5997 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5998 i += NumInputsPerOutput) {
5999 bool isLE = TLI.isLittleEndian();
6000 APInt NewBits = APInt(DstBitSize, 0);
6001 bool EltIsUndef = true;
6002 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6003 // Shift the previously computed bits over.
6004 NewBits <<= SrcBitSize;
6005 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6006 if (Op.getOpcode() == ISD::UNDEF) continue;
6009 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6010 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6014 Ops.push_back(DAG.getUNDEF(DstEltVT));
6016 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6019 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6020 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6021 &Ops[0], Ops.size());
6024 // Finally, this must be the case where we are shrinking elements: each input
6025 // turns into multiple outputs.
6026 bool isS2V = ISD::isScalarToVector(BV);
6027 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6028 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6029 NumOutputsPerInput*BV->getNumOperands());
6030 SmallVector<SDValue, 8> Ops;
6032 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6033 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6034 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6035 Ops.push_back(DAG.getUNDEF(DstEltVT));
6039 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6040 getAPIntValue().zextOrTrunc(SrcBitSize);
6042 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6043 APInt ThisVal = OpVal.trunc(DstBitSize);
6044 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6045 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6046 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6047 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6049 OpVal = OpVal.lshr(DstBitSize);
6052 // For big endian targets, swap the order of the pieces of each element.
6053 if (TLI.isBigEndian())
6054 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6057 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6058 &Ops[0], Ops.size());
6061 SDValue DAGCombiner::visitFADD(SDNode *N) {
6062 SDValue N0 = N->getOperand(0);
6063 SDValue N1 = N->getOperand(1);
6064 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6065 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6066 EVT VT = N->getValueType(0);
6069 if (VT.isVector()) {
6070 SDValue FoldedVOp = SimplifyVBinOp(N);
6071 if (FoldedVOp.getNode()) return FoldedVOp;
6074 // fold (fadd c1, c2) -> c1 + c2
6076 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6077 // canonicalize constant to RHS
6078 if (N0CFP && !N1CFP)
6079 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6080 // fold (fadd A, 0) -> A
6081 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6082 N1CFP->getValueAPF().isZero())
6084 // fold (fadd A, (fneg B)) -> (fsub A, B)
6085 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6086 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6087 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6088 GetNegatedExpression(N1, DAG, LegalOperations));
6089 // fold (fadd (fneg A), B) -> (fsub B, A)
6090 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6091 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6092 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6093 GetNegatedExpression(N0, DAG, LegalOperations));
6095 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6096 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6097 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6098 isa<ConstantFPSDNode>(N0.getOperand(1)))
6099 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6100 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6101 N0.getOperand(1), N1));
6103 // No FP constant should be created after legalization as Instruction
6104 // Selection pass has hard time in dealing with FP constant.
6106 // We don't need test this condition for transformation like following, as
6107 // the DAG being transformed implies it is legal to take FP constant as
6110 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6112 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6114 // If allow, fold (fadd (fneg x), x) -> 0.0
6115 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6116 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6117 return DAG.getConstantFP(0.0, VT);
6119 // If allow, fold (fadd x, (fneg x)) -> 0.0
6120 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6121 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6122 return DAG.getConstantFP(0.0, VT);
6124 // In unsafe math mode, we can fold chains of FADD's of the same value
6125 // into multiplications. This transform is not safe in general because
6126 // we are reducing the number of rounding steps.
6127 if (DAG.getTarget().Options.UnsafeFPMath &&
6128 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6130 if (N0.getOpcode() == ISD::FMUL) {
6131 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6132 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6134 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6135 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6136 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6138 DAG.getConstantFP(1.0, VT));
6139 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6143 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6144 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6145 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6147 DAG.getConstantFP(1.0, VT));
6148 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6152 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6153 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6154 N1.getOperand(0) == N1.getOperand(1) &&
6155 N0.getOperand(1) == N1.getOperand(0)) {
6156 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6158 DAG.getConstantFP(2.0, VT));
6159 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6160 N0.getOperand(1), NewCFP);
6163 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6164 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6165 N1.getOperand(0) == N1.getOperand(1) &&
6166 N0.getOperand(0) == N1.getOperand(0)) {
6167 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6169 DAG.getConstantFP(2.0, VT));
6170 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6171 N0.getOperand(0), NewCFP);
6175 if (N1.getOpcode() == ISD::FMUL) {
6176 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6177 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6179 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6180 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6181 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6183 DAG.getConstantFP(1.0, VT));
6184 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6188 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6189 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6190 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6192 DAG.getConstantFP(1.0, VT));
6193 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6198 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6199 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6200 N0.getOperand(0) == N0.getOperand(1) &&
6201 N1.getOperand(1) == N0.getOperand(0)) {
6202 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6204 DAG.getConstantFP(2.0, VT));
6205 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6206 N1.getOperand(1), NewCFP);
6209 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6210 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6211 N0.getOperand(0) == N0.getOperand(1) &&
6212 N1.getOperand(0) == N0.getOperand(0)) {
6213 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6215 DAG.getConstantFP(2.0, VT));
6216 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6217 N1.getOperand(0), NewCFP);
6221 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6222 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6223 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6224 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6225 (N0.getOperand(0) == N1))
6226 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6227 N1, DAG.getConstantFP(3.0, VT));
6230 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6231 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6232 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6233 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6234 N1.getOperand(0) == N0)
6235 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6236 N0, DAG.getConstantFP(3.0, VT));
6239 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6240 if (AllowNewFpConst &&
6241 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6242 N0.getOperand(0) == N0.getOperand(1) &&
6243 N1.getOperand(0) == N1.getOperand(1) &&
6244 N0.getOperand(0) == N1.getOperand(0))
6245 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6247 DAG.getConstantFP(4.0, VT));
6250 // FADD -> FMA combines:
6251 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6252 DAG.getTarget().Options.UnsafeFPMath) &&
6253 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6254 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6256 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6257 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6258 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6259 N0.getOperand(0), N0.getOperand(1), N1);
6261 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6262 // Note: Commutes FADD operands.
6263 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6264 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6265 N1.getOperand(0), N1.getOperand(1), N0);
6271 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6272 SDValue N0 = N->getOperand(0);
6273 SDValue N1 = N->getOperand(1);
6274 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6275 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6276 EVT VT = N->getValueType(0);
6280 if (VT.isVector()) {
6281 SDValue FoldedVOp = SimplifyVBinOp(N);
6282 if (FoldedVOp.getNode()) return FoldedVOp;
6285 // fold (fsub c1, c2) -> c1-c2
6287 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6288 // fold (fsub A, 0) -> A
6289 if (DAG.getTarget().Options.UnsafeFPMath &&
6290 N1CFP && N1CFP->getValueAPF().isZero())
6292 // fold (fsub 0, B) -> -B
6293 if (DAG.getTarget().Options.UnsafeFPMath &&
6294 N0CFP && N0CFP->getValueAPF().isZero()) {
6295 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6296 return GetNegatedExpression(N1, DAG, LegalOperations);
6297 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6298 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6300 // fold (fsub A, (fneg B)) -> (fadd A, B)
6301 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6302 return DAG.getNode(ISD::FADD, dl, VT, N0,
6303 GetNegatedExpression(N1, DAG, LegalOperations));
6305 // If 'unsafe math' is enabled, fold
6306 // (fsub x, x) -> 0.0 &
6307 // (fsub x, (fadd x, y)) -> (fneg y) &
6308 // (fsub x, (fadd y, x)) -> (fneg y)
6309 if (DAG.getTarget().Options.UnsafeFPMath) {
6311 return DAG.getConstantFP(0.0f, VT);
6313 if (N1.getOpcode() == ISD::FADD) {
6314 SDValue N10 = N1->getOperand(0);
6315 SDValue N11 = N1->getOperand(1);
6317 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6318 &DAG.getTarget().Options))
6319 return GetNegatedExpression(N11, DAG, LegalOperations);
6321 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6322 &DAG.getTarget().Options))
6323 return GetNegatedExpression(N10, DAG, LegalOperations);
6327 // FSUB -> FMA combines:
6328 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6329 DAG.getTarget().Options.UnsafeFPMath) &&
6330 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6331 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6333 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6334 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6335 return DAG.getNode(ISD::FMA, dl, VT,
6336 N0.getOperand(0), N0.getOperand(1),
6337 DAG.getNode(ISD::FNEG, dl, VT, N1));
6339 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6340 // Note: Commutes FSUB operands.
6341 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6342 return DAG.getNode(ISD::FMA, dl, VT,
6343 DAG.getNode(ISD::FNEG, dl, VT,
6345 N1.getOperand(1), N0);
6347 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6348 if (N0.getOpcode() == ISD::FNEG &&
6349 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6350 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6351 SDValue N00 = N0.getOperand(0).getOperand(0);
6352 SDValue N01 = N0.getOperand(0).getOperand(1);
6353 return DAG.getNode(ISD::FMA, dl, VT,
6354 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6355 DAG.getNode(ISD::FNEG, dl, VT, N1));
6362 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6363 SDValue N0 = N->getOperand(0);
6364 SDValue N1 = N->getOperand(1);
6365 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6366 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6367 EVT VT = N->getValueType(0);
6368 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6371 if (VT.isVector()) {
6372 SDValue FoldedVOp = SimplifyVBinOp(N);
6373 if (FoldedVOp.getNode()) return FoldedVOp;
6376 // fold (fmul c1, c2) -> c1*c2
6378 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6379 // canonicalize constant to RHS
6380 if (N0CFP && !N1CFP)
6381 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6382 // fold (fmul A, 0) -> 0
6383 if (DAG.getTarget().Options.UnsafeFPMath &&
6384 N1CFP && N1CFP->getValueAPF().isZero())
6386 // fold (fmul A, 0) -> 0, vector edition.
6387 if (DAG.getTarget().Options.UnsafeFPMath &&
6388 ISD::isBuildVectorAllZeros(N1.getNode()))
6390 // fold (fmul A, 1.0) -> A
6391 if (N1CFP && N1CFP->isExactlyValue(1.0))
6393 // fold (fmul X, 2.0) -> (fadd X, X)
6394 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6395 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6396 // fold (fmul X, -1.0) -> (fneg X)
6397 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6398 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6399 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6401 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6402 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6403 &DAG.getTarget().Options)) {
6404 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6405 &DAG.getTarget().Options)) {
6406 // Both can be negated for free, check to see if at least one is cheaper
6408 if (LHSNeg == 2 || RHSNeg == 2)
6409 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6410 GetNegatedExpression(N0, DAG, LegalOperations),
6411 GetNegatedExpression(N1, DAG, LegalOperations));
6415 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6416 if (DAG.getTarget().Options.UnsafeFPMath &&
6417 N1CFP && N0.getOpcode() == ISD::FMUL &&
6418 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6419 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6420 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6421 N0.getOperand(1), N1));
6426 SDValue DAGCombiner::visitFMA(SDNode *N) {
6427 SDValue N0 = N->getOperand(0);
6428 SDValue N1 = N->getOperand(1);
6429 SDValue N2 = N->getOperand(2);
6430 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6431 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6432 EVT VT = N->getValueType(0);
6435 if (DAG.getTarget().Options.UnsafeFPMath) {
6436 if (N0CFP && N0CFP->isZero())
6438 if (N1CFP && N1CFP->isZero())
6441 if (N0CFP && N0CFP->isExactlyValue(1.0))
6442 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6443 if (N1CFP && N1CFP->isExactlyValue(1.0))
6444 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6446 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6447 if (N0CFP && !N1CFP)
6448 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6450 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6451 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6452 N2.getOpcode() == ISD::FMUL &&
6453 N0 == N2.getOperand(0) &&
6454 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6455 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6456 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6460 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6461 if (DAG.getTarget().Options.UnsafeFPMath &&
6462 N0.getOpcode() == ISD::FMUL && N1CFP &&
6463 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6464 return DAG.getNode(ISD::FMA, dl, VT,
6466 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6470 // (fma x, 1, y) -> (fadd x, y)
6471 // (fma x, -1, y) -> (fadd (fneg x), y)
6473 if (N1CFP->isExactlyValue(1.0))
6474 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6476 if (N1CFP->isExactlyValue(-1.0) &&
6477 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6478 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6479 AddToWorkList(RHSNeg.getNode());
6480 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6484 // (fma x, c, x) -> (fmul x, (c+1))
6485 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6486 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6487 DAG.getNode(ISD::FADD, dl, VT,
6488 N1, DAG.getConstantFP(1.0, VT)));
6490 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6491 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6492 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6493 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6494 DAG.getNode(ISD::FADD, dl, VT,
6495 N1, DAG.getConstantFP(-1.0, VT)));
6501 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6502 SDValue N0 = N->getOperand(0);
6503 SDValue N1 = N->getOperand(1);
6504 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6505 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6506 EVT VT = N->getValueType(0);
6507 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6510 if (VT.isVector()) {
6511 SDValue FoldedVOp = SimplifyVBinOp(N);
6512 if (FoldedVOp.getNode()) return FoldedVOp;
6515 // fold (fdiv c1, c2) -> c1/c2
6517 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6519 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6520 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6521 // Compute the reciprocal 1.0 / c2.
6522 APFloat N1APF = N1CFP->getValueAPF();
6523 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6524 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6525 // Only do the transform if the reciprocal is a legal fp immediate that
6526 // isn't too nasty (eg NaN, denormal, ...).
6527 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6528 (!LegalOperations ||
6529 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6530 // backend)... we should handle this gracefully after Legalize.
6531 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6532 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6533 TLI.isFPImmLegal(Recip, VT)))
6534 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6535 DAG.getConstantFP(Recip, VT));
6538 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6539 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6540 &DAG.getTarget().Options)) {
6541 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6542 &DAG.getTarget().Options)) {
6543 // Both can be negated for free, check to see if at least one is cheaper
6545 if (LHSNeg == 2 || RHSNeg == 2)
6546 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6547 GetNegatedExpression(N0, DAG, LegalOperations),
6548 GetNegatedExpression(N1, DAG, LegalOperations));
6555 SDValue DAGCombiner::visitFREM(SDNode *N) {
6556 SDValue N0 = N->getOperand(0);
6557 SDValue N1 = N->getOperand(1);
6558 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6559 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6560 EVT VT = N->getValueType(0);
6562 // fold (frem c1, c2) -> fmod(c1,c2)
6564 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6569 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6570 SDValue N0 = N->getOperand(0);
6571 SDValue N1 = N->getOperand(1);
6572 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6573 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6574 EVT VT = N->getValueType(0);
6576 if (N0CFP && N1CFP) // Constant fold
6577 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6580 const APFloat& V = N1CFP->getValueAPF();
6581 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6582 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6583 if (!V.isNegative()) {
6584 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6585 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6587 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6588 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6589 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6593 // copysign(fabs(x), y) -> copysign(x, y)
6594 // copysign(fneg(x), y) -> copysign(x, y)
6595 // copysign(copysign(x,z), y) -> copysign(x, y)
6596 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6597 N0.getOpcode() == ISD::FCOPYSIGN)
6598 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6599 N0.getOperand(0), N1);
6601 // copysign(x, abs(y)) -> abs(x)
6602 if (N1.getOpcode() == ISD::FABS)
6603 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6605 // copysign(x, copysign(y,z)) -> copysign(x, z)
6606 if (N1.getOpcode() == ISD::FCOPYSIGN)
6607 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6608 N0, N1.getOperand(1));
6610 // copysign(x, fp_extend(y)) -> copysign(x, y)
6611 // copysign(x, fp_round(y)) -> copysign(x, y)
6612 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6613 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6614 N0, N1.getOperand(0));
6619 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6620 SDValue N0 = N->getOperand(0);
6621 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6622 EVT VT = N->getValueType(0);
6623 EVT OpVT = N0.getValueType();
6625 // fold (sint_to_fp c1) -> c1fp
6627 // ...but only if the target supports immediate floating-point values
6628 (!LegalOperations ||
6629 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6630 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6632 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6633 // but UINT_TO_FP is legal on this target, try to convert.
6634 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6635 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6636 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6637 if (DAG.SignBitIsZero(N0))
6638 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6641 // The next optimizations are desireable only if SELECT_CC can be lowered.
6642 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6643 // having to say they don't support SELECT_CC on every type the DAG knows
6644 // about, since there is no way to mark an opcode illegal at all value types
6645 // (See also visitSELECT)
6646 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6647 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6648 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6650 (!LegalOperations ||
6651 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6653 { N0.getOperand(0), N0.getOperand(1),
6654 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6656 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6659 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6660 // (select_cc x, y, 1.0, 0.0,, cc)
6661 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6662 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6663 (!LegalOperations ||
6664 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6666 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6667 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6668 N0.getOperand(0).getOperand(2) };
6669 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6676 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6677 SDValue N0 = N->getOperand(0);
6678 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6679 EVT VT = N->getValueType(0);
6680 EVT OpVT = N0.getValueType();
6682 // fold (uint_to_fp c1) -> c1fp
6684 // ...but only if the target supports immediate floating-point values
6685 (!LegalOperations ||
6686 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6687 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6689 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6690 // but SINT_TO_FP is legal on this target, try to convert.
6691 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6692 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6693 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6694 if (DAG.SignBitIsZero(N0))
6695 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6698 // The next optimizations are desireable only if SELECT_CC can be lowered.
6699 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6700 // having to say they don't support SELECT_CC on every type the DAG knows
6701 // about, since there is no way to mark an opcode illegal at all value types
6702 // (See also visitSELECT)
6703 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6704 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6706 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6707 (!LegalOperations ||
6708 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6710 { N0.getOperand(0), N0.getOperand(1),
6711 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6713 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6720 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6721 SDValue N0 = N->getOperand(0);
6722 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6723 EVT VT = N->getValueType(0);
6725 // fold (fp_to_sint c1fp) -> c1
6727 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6732 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6733 SDValue N0 = N->getOperand(0);
6734 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6735 EVT VT = N->getValueType(0);
6737 // fold (fp_to_uint c1fp) -> c1
6739 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6744 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6745 SDValue N0 = N->getOperand(0);
6746 SDValue N1 = N->getOperand(1);
6747 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6748 EVT VT = N->getValueType(0);
6750 // fold (fp_round c1fp) -> c1fp
6752 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6754 // fold (fp_round (fp_extend x)) -> x
6755 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6756 return N0.getOperand(0);
6758 // fold (fp_round (fp_round x)) -> (fp_round x)
6759 if (N0.getOpcode() == ISD::FP_ROUND) {
6760 // This is a value preserving truncation if both round's are.
6761 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6762 N0.getNode()->getConstantOperandVal(1) == 1;
6763 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6764 DAG.getIntPtrConstant(IsTrunc));
6767 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6768 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6769 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6770 N0.getOperand(0), N1);
6771 AddToWorkList(Tmp.getNode());
6772 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6773 Tmp, N0.getOperand(1));
6779 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6780 SDValue N0 = N->getOperand(0);
6781 EVT VT = N->getValueType(0);
6782 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6783 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6785 // fold (fp_round_inreg c1fp) -> c1fp
6786 if (N0CFP && isTypeLegal(EVT)) {
6787 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6788 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6794 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6795 SDValue N0 = N->getOperand(0);
6796 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6797 EVT VT = N->getValueType(0);
6799 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6800 if (N->hasOneUse() &&
6801 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6804 // fold (fp_extend c1fp) -> c1fp
6806 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6808 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6810 if (N0.getOpcode() == ISD::FP_ROUND
6811 && N0.getNode()->getConstantOperandVal(1) == 1) {
6812 SDValue In = N0.getOperand(0);
6813 if (In.getValueType() == VT) return In;
6814 if (VT.bitsLT(In.getValueType()))
6815 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6816 In, N0.getOperand(1));
6817 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6820 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6821 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6822 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6823 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6824 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6825 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6827 LN0->getBasePtr(), N0.getValueType(),
6828 LN0->getMemOperand());
6829 CombineTo(N, ExtLoad);
6830 CombineTo(N0.getNode(),
6831 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6832 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6833 ExtLoad.getValue(1));
6834 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6840 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6841 SDValue N0 = N->getOperand(0);
6842 EVT VT = N->getValueType(0);
6844 if (VT.isVector()) {
6845 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6846 if (FoldedVOp.getNode()) return FoldedVOp;
6849 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6850 &DAG.getTarget().Options))
6851 return GetNegatedExpression(N0, DAG, LegalOperations);
6853 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6854 // constant pool values.
6855 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6857 N0.getNode()->hasOneUse() &&
6858 N0.getOperand(0).getValueType().isInteger()) {
6859 SDValue Int = N0.getOperand(0);
6860 EVT IntVT = Int.getValueType();
6861 if (IntVT.isInteger() && !IntVT.isVector()) {
6862 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6863 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6864 AddToWorkList(Int.getNode());
6865 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6870 // (fneg (fmul c, x)) -> (fmul -c, x)
6871 if (N0.getOpcode() == ISD::FMUL) {
6872 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6874 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6876 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6883 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6884 SDValue N0 = N->getOperand(0);
6885 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6886 EVT VT = N->getValueType(0);
6888 // fold (fceil c1) -> fceil(c1)
6890 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6895 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6896 SDValue N0 = N->getOperand(0);
6897 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6898 EVT VT = N->getValueType(0);
6900 // fold (ftrunc c1) -> ftrunc(c1)
6902 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6907 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6908 SDValue N0 = N->getOperand(0);
6909 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6910 EVT VT = N->getValueType(0);
6912 // fold (ffloor c1) -> ffloor(c1)
6914 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6919 SDValue DAGCombiner::visitFABS(SDNode *N) {
6920 SDValue N0 = N->getOperand(0);
6921 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6922 EVT VT = N->getValueType(0);
6924 if (VT.isVector()) {
6925 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6926 if (FoldedVOp.getNode()) return FoldedVOp;
6929 // fold (fabs c1) -> fabs(c1)
6931 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6932 // fold (fabs (fabs x)) -> (fabs x)
6933 if (N0.getOpcode() == ISD::FABS)
6934 return N->getOperand(0);
6935 // fold (fabs (fneg x)) -> (fabs x)
6936 // fold (fabs (fcopysign x, y)) -> (fabs x)
6937 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6938 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6940 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6941 // constant pool values.
6942 if (!TLI.isFAbsFree(VT) &&
6943 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6944 N0.getOperand(0).getValueType().isInteger() &&
6945 !N0.getOperand(0).getValueType().isVector()) {
6946 SDValue Int = N0.getOperand(0);
6947 EVT IntVT = Int.getValueType();
6948 if (IntVT.isInteger() && !IntVT.isVector()) {
6949 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6950 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6951 AddToWorkList(Int.getNode());
6952 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6953 N->getValueType(0), Int);
6960 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6961 SDValue Chain = N->getOperand(0);
6962 SDValue N1 = N->getOperand(1);
6963 SDValue N2 = N->getOperand(2);
6965 // If N is a constant we could fold this into a fallthrough or unconditional
6966 // branch. However that doesn't happen very often in normal code, because
6967 // Instcombine/SimplifyCFG should have handled the available opportunities.
6968 // If we did this folding here, it would be necessary to update the
6969 // MachineBasicBlock CFG, which is awkward.
6971 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6973 if (N1.getOpcode() == ISD::SETCC &&
6974 TLI.isOperationLegalOrCustom(ISD::BR_CC,
6975 N1.getOperand(0).getValueType())) {
6976 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6977 Chain, N1.getOperand(2),
6978 N1.getOperand(0), N1.getOperand(1), N2);
6981 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6982 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6983 (N1.getOperand(0).hasOneUse() &&
6984 N1.getOperand(0).getOpcode() == ISD::SRL))) {
6986 if (N1.getOpcode() == ISD::TRUNCATE) {
6987 // Look pass the truncate.
6988 Trunc = N1.getNode();
6989 N1 = N1.getOperand(0);
6992 // Match this pattern so that we can generate simpler code:
6995 // %b = and i32 %a, 2
6996 // %c = srl i32 %b, 1
6997 // brcond i32 %c ...
7002 // %b = and i32 %a, 2
7003 // %c = setcc eq %b, 0
7006 // This applies only when the AND constant value has one bit set and the
7007 // SRL constant is equal to the log2 of the AND constant. The back-end is
7008 // smart enough to convert the result into a TEST/JMP sequence.
7009 SDValue Op0 = N1.getOperand(0);
7010 SDValue Op1 = N1.getOperand(1);
7012 if (Op0.getOpcode() == ISD::AND &&
7013 Op1.getOpcode() == ISD::Constant) {
7014 SDValue AndOp1 = Op0.getOperand(1);
7016 if (AndOp1.getOpcode() == ISD::Constant) {
7017 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7019 if (AndConst.isPowerOf2() &&
7020 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7022 DAG.getSetCC(SDLoc(N),
7023 getSetCCResultType(Op0.getValueType()),
7024 Op0, DAG.getConstant(0, Op0.getValueType()),
7027 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7028 MVT::Other, Chain, SetCC, N2);
7029 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7030 // will convert it back to (X & C1) >> C2.
7031 CombineTo(N, NewBRCond, false);
7032 // Truncate is dead.
7034 removeFromWorkList(Trunc);
7035 DAG.DeleteNode(Trunc);
7037 // Replace the uses of SRL with SETCC
7038 WorkListRemover DeadNodes(*this);
7039 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7040 removeFromWorkList(N1.getNode());
7041 DAG.DeleteNode(N1.getNode());
7042 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7048 // Restore N1 if the above transformation doesn't match.
7049 N1 = N->getOperand(1);
7052 // Transform br(xor(x, y)) -> br(x != y)
7053 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7054 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7055 SDNode *TheXor = N1.getNode();
7056 SDValue Op0 = TheXor->getOperand(0);
7057 SDValue Op1 = TheXor->getOperand(1);
7058 if (Op0.getOpcode() == Op1.getOpcode()) {
7059 // Avoid missing important xor optimizations.
7060 SDValue Tmp = visitXOR(TheXor);
7061 if (Tmp.getNode()) {
7062 if (Tmp.getNode() != TheXor) {
7063 DEBUG(dbgs() << "\nReplacing.8 ";
7065 dbgs() << "\nWith: ";
7066 Tmp.getNode()->dump(&DAG);
7068 WorkListRemover DeadNodes(*this);
7069 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7070 removeFromWorkList(TheXor);
7071 DAG.DeleteNode(TheXor);
7072 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7073 MVT::Other, Chain, Tmp, N2);
7076 // visitXOR has changed XOR's operands or replaced the XOR completely,
7078 return SDValue(N, 0);
7082 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7084 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7085 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7086 Op0.getOpcode() == ISD::XOR) {
7087 TheXor = Op0.getNode();
7091 EVT SetCCVT = N1.getValueType();
7093 SetCCVT = getSetCCResultType(SetCCVT);
7094 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7097 Equal ? ISD::SETEQ : ISD::SETNE);
7098 // Replace the uses of XOR with SETCC
7099 WorkListRemover DeadNodes(*this);
7100 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7101 removeFromWorkList(N1.getNode());
7102 DAG.DeleteNode(N1.getNode());
7103 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7104 MVT::Other, Chain, SetCC, N2);
7111 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7113 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7114 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7115 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7117 // If N is a constant we could fold this into a fallthrough or unconditional
7118 // branch. However that doesn't happen very often in normal code, because
7119 // Instcombine/SimplifyCFG should have handled the available opportunities.
7120 // If we did this folding here, it would be necessary to update the
7121 // MachineBasicBlock CFG, which is awkward.
7123 // Use SimplifySetCC to simplify SETCC's.
7124 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7125 CondLHS, CondRHS, CC->get(), SDLoc(N),
7127 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7129 // fold to a simpler setcc
7130 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7131 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7132 N->getOperand(0), Simp.getOperand(2),
7133 Simp.getOperand(0), Simp.getOperand(1),
7139 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7140 /// uses N as its base pointer and that N may be folded in the load / store
7141 /// addressing mode.
7142 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7144 const TargetLowering &TLI) {
7146 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7147 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7149 VT = Use->getValueType(0);
7150 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7151 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7153 VT = ST->getValue().getValueType();
7157 TargetLowering::AddrMode AM;
7158 if (N->getOpcode() == ISD::ADD) {
7159 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7162 AM.BaseOffs = Offset->getSExtValue();
7166 } else if (N->getOpcode() == ISD::SUB) {
7167 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7170 AM.BaseOffs = -Offset->getSExtValue();
7177 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7180 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7181 /// pre-indexed load / store when the base pointer is an add or subtract
7182 /// and it has other uses besides the load / store. After the
7183 /// transformation, the new indexed load / store has effectively folded
7184 /// the add / subtract in and all of its other uses are redirected to the
7185 /// new load / store.
7186 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7187 if (Level < AfterLegalizeDAG)
7193 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7194 if (LD->isIndexed())
7196 VT = LD->getMemoryVT();
7197 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7198 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7200 Ptr = LD->getBasePtr();
7201 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7202 if (ST->isIndexed())
7204 VT = ST->getMemoryVT();
7205 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7206 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7208 Ptr = ST->getBasePtr();
7214 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7215 // out. There is no reason to make this a preinc/predec.
7216 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7217 Ptr.getNode()->hasOneUse())
7220 // Ask the target to do addressing mode selection.
7223 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7224 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7227 // Backends without true r+i pre-indexed forms may need to pass a
7228 // constant base with a variable offset so that constant coercion
7229 // will work with the patterns in canonical form.
7230 bool Swapped = false;
7231 if (isa<ConstantSDNode>(BasePtr)) {
7232 std::swap(BasePtr, Offset);
7236 // Don't create a indexed load / store with zero offset.
7237 if (isa<ConstantSDNode>(Offset) &&
7238 cast<ConstantSDNode>(Offset)->isNullValue())
7241 // Try turning it into a pre-indexed load / store except when:
7242 // 1) The new base ptr is a frame index.
7243 // 2) If N is a store and the new base ptr is either the same as or is a
7244 // predecessor of the value being stored.
7245 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7246 // that would create a cycle.
7247 // 4) All uses are load / store ops that use it as old base ptr.
7249 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7250 // (plus the implicit offset) to a register to preinc anyway.
7251 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7256 SDValue Val = cast<StoreSDNode>(N)->getValue();
7257 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7261 // If the offset is a constant, there may be other adds of constants that
7262 // can be folded with this one. We should do this to avoid having to keep
7263 // a copy of the original base pointer.
7264 SmallVector<SDNode *, 16> OtherUses;
7265 if (isa<ConstantSDNode>(Offset))
7266 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7267 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7269 if (Use == Ptr.getNode())
7272 if (Use->isPredecessorOf(N))
7275 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7280 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7281 if (Op1.getNode() == BasePtr.getNode())
7282 std::swap(Op0, Op1);
7283 assert(Op0.getNode() == BasePtr.getNode() &&
7284 "Use of ADD/SUB but not an operand");
7286 if (!isa<ConstantSDNode>(Op1)) {
7291 // FIXME: In some cases, we can be smarter about this.
7292 if (Op1.getValueType() != Offset.getValueType()) {
7297 OtherUses.push_back(Use);
7301 std::swap(BasePtr, Offset);
7303 // Now check for #3 and #4.
7304 bool RealUse = false;
7306 // Caches for hasPredecessorHelper
7307 SmallPtrSet<const SDNode *, 32> Visited;
7308 SmallVector<const SDNode *, 16> Worklist;
7310 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7311 E = Ptr.getNode()->use_end(); I != E; ++I) {
7315 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7318 // If Ptr may be folded in addressing mode of other use, then it's
7319 // not profitable to do this transformation.
7320 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7329 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7330 BasePtr, Offset, AM);
7332 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7333 BasePtr, Offset, AM);
7336 DEBUG(dbgs() << "\nReplacing.4 ";
7338 dbgs() << "\nWith: ";
7339 Result.getNode()->dump(&DAG);
7341 WorkListRemover DeadNodes(*this);
7343 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7344 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7346 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7349 // Finally, since the node is now dead, remove it from the graph.
7353 std::swap(BasePtr, Offset);
7355 // Replace other uses of BasePtr that can be updated to use Ptr
7356 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7357 unsigned OffsetIdx = 1;
7358 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7360 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7361 BasePtr.getNode() && "Expected BasePtr operand");
7363 // We need to replace ptr0 in the following expression:
7364 // x0 * offset0 + y0 * ptr0 = t0
7366 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7368 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7369 // indexed load/store and the expresion that needs to be re-written.
7371 // Therefore, we have:
7372 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7374 ConstantSDNode *CN =
7375 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7377 APInt Offset0 = CN->getAPIntValue();
7378 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7380 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7381 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7382 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7383 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7385 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7387 APInt CNV = Offset0;
7388 if (X0 < 0) CNV = -CNV;
7389 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7390 else CNV = CNV - Offset1;
7392 // We can now generate the new expression.
7393 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7394 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7396 SDValue NewUse = DAG.getNode(Opcode,
7397 SDLoc(OtherUses[i]),
7398 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7399 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7400 removeFromWorkList(OtherUses[i]);
7401 DAG.DeleteNode(OtherUses[i]);
7404 // Replace the uses of Ptr with uses of the updated base value.
7405 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7406 removeFromWorkList(Ptr.getNode());
7407 DAG.DeleteNode(Ptr.getNode());
7412 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7413 /// add / sub of the base pointer node into a post-indexed load / store.
7414 /// The transformation folded the add / subtract into the new indexed
7415 /// load / store effectively and all of its uses are redirected to the
7416 /// new load / store.
7417 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7418 if (Level < AfterLegalizeDAG)
7424 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7425 if (LD->isIndexed())
7427 VT = LD->getMemoryVT();
7428 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7429 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7431 Ptr = LD->getBasePtr();
7432 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7433 if (ST->isIndexed())
7435 VT = ST->getMemoryVT();
7436 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7437 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7439 Ptr = ST->getBasePtr();
7445 if (Ptr.getNode()->hasOneUse())
7448 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7449 E = Ptr.getNode()->use_end(); I != E; ++I) {
7452 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7457 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7458 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7459 // Don't create a indexed load / store with zero offset.
7460 if (isa<ConstantSDNode>(Offset) &&
7461 cast<ConstantSDNode>(Offset)->isNullValue())
7464 // Try turning it into a post-indexed load / store except when
7465 // 1) All uses are load / store ops that use it as base ptr (and
7466 // it may be folded as addressing mmode).
7467 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7468 // nor a successor of N. Otherwise, if Op is folded that would
7471 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7475 bool TryNext = false;
7476 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7477 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7479 if (Use == Ptr.getNode())
7482 // If all the uses are load / store addresses, then don't do the
7484 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7485 bool RealUse = false;
7486 for (SDNode::use_iterator III = Use->use_begin(),
7487 EEE = Use->use_end(); III != EEE; ++III) {
7488 SDNode *UseUse = *III;
7489 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7504 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7505 SDValue Result = isLoad
7506 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7507 BasePtr, Offset, AM)
7508 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7509 BasePtr, Offset, AM);
7512 DEBUG(dbgs() << "\nReplacing.5 ";
7514 dbgs() << "\nWith: ";
7515 Result.getNode()->dump(&DAG);
7517 WorkListRemover DeadNodes(*this);
7519 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7520 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7522 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7525 // Finally, since the node is now dead, remove it from the graph.
7528 // Replace the uses of Use with uses of the updated base value.
7529 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7530 Result.getValue(isLoad ? 1 : 0));
7531 removeFromWorkList(Op);
7541 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7542 LoadSDNode *LD = cast<LoadSDNode>(N);
7543 SDValue Chain = LD->getChain();
7544 SDValue Ptr = LD->getBasePtr();
7546 // If load is not volatile and there are no uses of the loaded value (and
7547 // the updated indexed value in case of indexed loads), change uses of the
7548 // chain value into uses of the chain input (i.e. delete the dead load).
7549 if (!LD->isVolatile()) {
7550 if (N->getValueType(1) == MVT::Other) {
7552 if (!N->hasAnyUseOfValue(0)) {
7553 // It's not safe to use the two value CombineTo variant here. e.g.
7554 // v1, chain2 = load chain1, loc
7555 // v2, chain3 = load chain2, loc
7557 // Now we replace use of chain2 with chain1. This makes the second load
7558 // isomorphic to the one we are deleting, and thus makes this load live.
7559 DEBUG(dbgs() << "\nReplacing.6 ";
7561 dbgs() << "\nWith chain: ";
7562 Chain.getNode()->dump(&DAG);
7564 WorkListRemover DeadNodes(*this);
7565 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7567 if (N->use_empty()) {
7568 removeFromWorkList(N);
7572 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7576 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7577 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7578 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7579 DEBUG(dbgs() << "\nReplacing.7 ";
7581 dbgs() << "\nWith: ";
7582 Undef.getNode()->dump(&DAG);
7583 dbgs() << " and 2 other values\n");
7584 WorkListRemover DeadNodes(*this);
7585 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7586 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7587 DAG.getUNDEF(N->getValueType(1)));
7588 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7589 removeFromWorkList(N);
7591 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7596 // If this load is directly stored, replace the load value with the stored
7598 // TODO: Handle store large -> read small portion.
7599 // TODO: Handle TRUNCSTORE/LOADEXT
7600 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7601 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7602 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7603 if (PrevST->getBasePtr() == Ptr &&
7604 PrevST->getValue().getValueType() == N->getValueType(0))
7605 return CombineTo(N, Chain.getOperand(1), Chain);
7609 // Try to infer better alignment information than the load already has.
7610 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7611 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7612 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7614 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7615 LD->getValueType(0),
7616 Chain, Ptr, LD->getPointerInfo(),
7618 LD->isVolatile(), LD->isNonTemporal(), Align,
7620 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7625 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7626 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7628 // Walk up chain skipping non-aliasing memory nodes.
7629 SDValue BetterChain = FindBetterChain(N, Chain);
7631 // If there is a better chain.
7632 if (Chain != BetterChain) {
7635 // Replace the chain to void dependency.
7636 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7637 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7638 BetterChain, Ptr, LD->getMemOperand());
7640 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7641 LD->getValueType(0),
7642 BetterChain, Ptr, LD->getMemoryVT(),
7643 LD->getMemOperand());
7646 // Create token factor to keep old chain connected.
7647 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7648 MVT::Other, Chain, ReplLoad.getValue(1));
7650 // Make sure the new and old chains are cleaned up.
7651 AddToWorkList(Token.getNode());
7653 // Replace uses with load result and token factor. Don't add users
7655 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7659 // Try transforming N to an indexed load.
7660 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7661 return SDValue(N, 0);
7663 // Try to slice up N to more direct loads if the slices are mapped to
7664 // different register banks or pairing can take place.
7666 return SDValue(N, 0);
7672 /// \brief Helper structure used to slice a load in smaller loads.
7673 /// Basically a slice is obtained from the following sequence:
7674 /// Origin = load Ty1, Base
7675 /// Shift = srl Ty1 Origin, CstTy Amount
7676 /// Inst = trunc Shift to Ty2
7678 /// Then, it will be rewriten into:
7679 /// Slice = load SliceTy, Base + SliceOffset
7680 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7682 /// SliceTy is deduced from the number of bits that are actually used to
7684 struct LoadedSlice {
7685 /// \brief Helper structure used to compute the cost of a slice.
7687 /// Are we optimizing for code size.
7692 unsigned CrossRegisterBanksCopies;
7696 Cost(bool ForCodeSize = false)
7697 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7698 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7700 /// \brief Get the cost of one isolated slice.
7701 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7702 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7703 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7704 EVT TruncType = LS.Inst->getValueType(0);
7705 EVT LoadedType = LS.getLoadedType();
7706 if (TruncType != LoadedType &&
7707 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7711 /// \brief Account for slicing gain in the current cost.
7712 /// Slicing provide a few gains like removing a shift or a
7713 /// truncate. This method allows to grow the cost of the original
7714 /// load with the gain from this slice.
7715 void addSliceGain(const LoadedSlice &LS) {
7716 // Each slice saves a truncate.
7717 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7718 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7719 LS.Inst->getOperand(0).getValueType()))
7721 // If there is a shift amount, this slice gets rid of it.
7724 // If this slice can merge a cross register bank copy, account for it.
7725 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7726 ++CrossRegisterBanksCopies;
7729 Cost &operator+=(const Cost &RHS) {
7731 Truncates += RHS.Truncates;
7732 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7738 bool operator==(const Cost &RHS) const {
7739 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7740 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7741 ZExts == RHS.ZExts && Shift == RHS.Shift;
7744 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7746 bool operator<(const Cost &RHS) const {
7747 // Assume cross register banks copies are as expensive as loads.
7748 // FIXME: Do we want some more target hooks?
7749 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7750 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7751 // Unless we are optimizing for code size, consider the
7752 // expensive operation first.
7753 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7754 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7755 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7756 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7759 bool operator>(const Cost &RHS) const { return RHS < *this; }
7761 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7763 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7765 // The last instruction that represent the slice. This should be a
7766 // truncate instruction.
7768 // The original load instruction.
7770 // The right shift amount in bits from the original load.
7772 // The DAG from which Origin came from.
7773 // This is used to get some contextual information about legal types, etc.
7776 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7777 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7778 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7780 LoadedSlice(const LoadedSlice &LS)
7781 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7783 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7784 /// \return Result is \p BitWidth and has used bits set to 1 and
7785 /// not used bits set to 0.
7786 APInt getUsedBits() const {
7787 // Reproduce the trunc(lshr) sequence:
7788 // - Start from the truncated value.
7789 // - Zero extend to the desired bit width.
7791 assert(Origin && "No original load to compare against.");
7792 unsigned BitWidth = Origin->getValueSizeInBits(0);
7793 assert(Inst && "This slice is not bound to an instruction");
7794 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7795 "Extracted slice is bigger than the whole type!");
7796 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7797 UsedBits.setAllBits();
7798 UsedBits = UsedBits.zext(BitWidth);
7803 /// \brief Get the size of the slice to be loaded in bytes.
7804 unsigned getLoadedSize() const {
7805 unsigned SliceSize = getUsedBits().countPopulation();
7806 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7807 return SliceSize / 8;
7810 /// \brief Get the type that will be loaded for this slice.
7811 /// Note: This may not be the final type for the slice.
7812 EVT getLoadedType() const {
7813 assert(DAG && "Missing context");
7814 LLVMContext &Ctxt = *DAG->getContext();
7815 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7818 /// \brief Get the alignment of the load used for this slice.
7819 unsigned getAlignment() const {
7820 unsigned Alignment = Origin->getAlignment();
7821 unsigned Offset = getOffsetFromBase();
7823 Alignment = MinAlign(Alignment, Alignment + Offset);
7827 /// \brief Check if this slice can be rewritten with legal operations.
7828 bool isLegal() const {
7829 // An invalid slice is not legal.
7830 if (!Origin || !Inst || !DAG)
7833 // Offsets are for indexed load only, we do not handle that.
7834 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7837 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7839 // Check that the type is legal.
7840 EVT SliceType = getLoadedType();
7841 if (!TLI.isTypeLegal(SliceType))
7844 // Check that the load is legal for this type.
7845 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7848 // Check that the offset can be computed.
7849 // 1. Check its type.
7850 EVT PtrType = Origin->getBasePtr().getValueType();
7851 if (PtrType == MVT::Untyped || PtrType.isExtended())
7854 // 2. Check that it fits in the immediate.
7855 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7858 // 3. Check that the computation is legal.
7859 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7862 // Check that the zext is legal if it needs one.
7863 EVT TruncateType = Inst->getValueType(0);
7864 if (TruncateType != SliceType &&
7865 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7871 /// \brief Get the offset in bytes of this slice in the original chunk of
7873 /// \pre DAG != NULL.
7874 uint64_t getOffsetFromBase() const {
7875 assert(DAG && "Missing context.");
7877 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7878 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7879 uint64_t Offset = Shift / 8;
7880 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7881 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7882 "The size of the original loaded type is not a multiple of a"
7884 // If Offset is bigger than TySizeInBytes, it means we are loading all
7885 // zeros. This should have been optimized before in the process.
7886 assert(TySizeInBytes > Offset &&
7887 "Invalid shift amount for given loaded size");
7889 Offset = TySizeInBytes - Offset - getLoadedSize();
7893 /// \brief Generate the sequence of instructions to load the slice
7894 /// represented by this object and redirect the uses of this slice to
7895 /// this new sequence of instructions.
7896 /// \pre this->Inst && this->Origin are valid Instructions and this
7897 /// object passed the legal check: LoadedSlice::isLegal returned true.
7898 /// \return The last instruction of the sequence used to load the slice.
7899 SDValue loadSlice() const {
7900 assert(Inst && Origin && "Unable to replace a non-existing slice.");
7901 const SDValue &OldBaseAddr = Origin->getBasePtr();
7902 SDValue BaseAddr = OldBaseAddr;
7903 // Get the offset in that chunk of bytes w.r.t. the endianess.
7904 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
7905 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
7907 // BaseAddr = BaseAddr + Offset.
7908 EVT ArithType = BaseAddr.getValueType();
7909 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
7910 DAG->getConstant(Offset, ArithType));
7913 // Create the type of the loaded slice according to its size.
7914 EVT SliceType = getLoadedType();
7916 // Create the load for the slice.
7917 SDValue LastInst = DAG->getLoad(
7918 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
7919 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
7920 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
7921 // If the final type is not the same as the loaded type, this means that
7922 // we have to pad with zero. Create a zero extend for that.
7923 EVT FinalType = Inst->getValueType(0);
7924 if (SliceType != FinalType)
7926 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
7930 /// \brief Check if this slice can be merged with an expensive cross register
7931 /// bank copy. E.g.,
7933 /// f = bitcast i32 i to float
7934 bool canMergeExpensiveCrossRegisterBankCopy() const {
7935 if (!Inst || !Inst->hasOneUse())
7937 SDNode *Use = *Inst->use_begin();
7938 if (Use->getOpcode() != ISD::BITCAST)
7940 assert(DAG && "Missing context");
7941 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7942 EVT ResVT = Use->getValueType(0);
7943 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
7944 const TargetRegisterClass *ArgRC =
7945 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
7946 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
7949 // At this point, we know that we perform a cross-register-bank copy.
7950 // Check if it is expensive.
7951 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
7952 // Assume bitcasts are cheap, unless both register classes do not
7953 // explicitly share a common sub class.
7954 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
7957 // Check if it will be merged with the load.
7958 // 1. Check the alignment constraint.
7959 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
7960 ResVT.getTypeForEVT(*DAG->getContext()));
7962 if (RequiredAlignment > getAlignment())
7965 // 2. Check that the load is a legal operation for that type.
7966 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
7969 // 3. Check that we do not have a zext in the way.
7970 if (Inst->getValueType(0) != getLoadedType())
7978 /// \brief Sorts LoadedSlice according to their offset.
7979 struct LoadedSliceSorter {
7980 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
7981 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
7982 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
7986 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
7987 /// \p UsedBits looks like 0..0 1..1 0..0.
7988 static bool areUsedBitsDense(const APInt &UsedBits) {
7989 // If all the bits are one, this is dense!
7990 if (UsedBits.isAllOnesValue())
7993 // Get rid of the unused bits on the right.
7994 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
7995 // Get rid of the unused bits on the left.
7996 if (NarrowedUsedBits.countLeadingZeros())
7997 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
7998 // Check that the chunk of bits is completely used.
7999 return NarrowedUsedBits.isAllOnesValue();
8002 /// \brief Check whether or not \p First and \p Second are next to each other
8003 /// in memory. This means that there is no hole between the bits loaded
8004 /// by \p First and the bits loaded by \p Second.
8005 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8006 const LoadedSlice &Second) {
8007 assert(First.Origin == Second.Origin && First.Origin &&
8008 "Unable to match different memory origins.");
8009 APInt UsedBits = First.getUsedBits();
8010 assert((UsedBits & Second.getUsedBits()) == 0 &&
8011 "Slices are not supposed to overlap.");
8012 UsedBits |= Second.getUsedBits();
8013 return areUsedBitsDense(UsedBits);
8016 /// \brief Adjust the \p GlobalLSCost according to the target
8017 /// paring capabilities and the layout of the slices.
8018 /// \pre \p GlobalLSCost should account for at least as many loads as
8019 /// there is in the slices in \p LoadedSlices.
8020 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8021 LoadedSlice::Cost &GlobalLSCost) {
8022 unsigned NumberOfSlices = LoadedSlices.size();
8023 // If there is less than 2 elements, no pairing is possible.
8024 if (NumberOfSlices < 2)
8027 // Sort the slices so that elements that are likely to be next to each
8028 // other in memory are next to each other in the list.
8029 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8030 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8031 // First (resp. Second) is the first (resp. Second) potentially candidate
8032 // to be placed in a paired load.
8033 const LoadedSlice *First = NULL;
8034 const LoadedSlice *Second = NULL;
8035 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8036 // Set the beginning of the pair.
8039 Second = &LoadedSlices[CurrSlice];
8041 // If First is NULL, it means we start a new pair.
8042 // Get to the next slice.
8046 EVT LoadedType = First->getLoadedType();
8048 // If the types of the slices are different, we cannot pair them.
8049 if (LoadedType != Second->getLoadedType())
8052 // Check if the target supplies paired loads for this type.
8053 unsigned RequiredAlignment = 0;
8054 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8055 // move to the next pair, this type is hopeless.
8059 // Check if we meet the alignment requirement.
8060 if (RequiredAlignment > First->getAlignment())
8063 // Check that both loads are next to each other in memory.
8064 if (!areSlicesNextToEachOther(*First, *Second))
8067 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8068 --GlobalLSCost.Loads;
8069 // Move to the next pair.
8074 /// \brief Check the profitability of all involved LoadedSlice.
8075 /// Currently, it is considered profitable if there is exactly two
8076 /// involved slices (1) which are (2) next to each other in memory, and
8077 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8079 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8080 /// the elements themselves.
8082 /// FIXME: When the cost model will be mature enough, we can relax
8083 /// constraints (1) and (2).
8084 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8085 const APInt &UsedBits, bool ForCodeSize) {
8086 unsigned NumberOfSlices = LoadedSlices.size();
8087 if (StressLoadSlicing)
8088 return NumberOfSlices > 1;
8091 if (NumberOfSlices != 2)
8095 if (!areUsedBitsDense(UsedBits))
8099 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8100 // The original code has one big load.
8102 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8103 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8104 // Accumulate the cost of all the slices.
8105 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8106 GlobalSlicingCost += SliceCost;
8108 // Account as cost in the original configuration the gain obtained
8109 // with the current slices.
8110 OrigCost.addSliceGain(LS);
8113 // If the target supports paired load, adjust the cost accordingly.
8114 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8115 return OrigCost > GlobalSlicingCost;
8118 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8119 /// operations, split it in the various pieces being extracted.
8121 /// This sort of thing is introduced by SROA.
8122 /// This slicing takes care not to insert overlapping loads.
8123 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8124 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8125 if (Level < AfterLegalizeDAG)
8128 LoadSDNode *LD = cast<LoadSDNode>(N);
8129 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8130 !LD->getValueType(0).isInteger())
8133 // Keep track of already used bits to detect overlapping values.
8134 // In that case, we will just abort the transformation.
8135 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8137 SmallVector<LoadedSlice, 4> LoadedSlices;
8139 // Check if this load is used as several smaller chunks of bits.
8140 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8141 // of computation for each trunc.
8142 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8143 UI != UIEnd; ++UI) {
8144 // Skip the uses of the chain.
8145 if (UI.getUse().getResNo() != 0)
8151 // Check if this is a trunc(lshr).
8152 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8153 isa<ConstantSDNode>(User->getOperand(1))) {
8154 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8155 User = *User->use_begin();
8158 // At this point, User is a Truncate, iff we encountered, trunc or
8160 if (User->getOpcode() != ISD::TRUNCATE)
8163 // The width of the type must be a power of 2 and greater than 8-bits.
8164 // Otherwise the load cannot be represented in LLVM IR.
8165 // Moreover, if we shifted with a non-8-bits multiple, the slice
8166 // will be accross several bytes. We do not support that.
8167 unsigned Width = User->getValueSizeInBits(0);
8168 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8171 // Build the slice for this chain of computations.
8172 LoadedSlice LS(User, LD, Shift, &DAG);
8173 APInt CurrentUsedBits = LS.getUsedBits();
8175 // Check if this slice overlaps with another.
8176 if ((CurrentUsedBits & UsedBits) != 0)
8178 // Update the bits used globally.
8179 UsedBits |= CurrentUsedBits;
8181 // Check if the new slice would be legal.
8185 // Record the slice.
8186 LoadedSlices.push_back(LS);
8189 // Abort slicing if it does not seem to be profitable.
8190 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8195 // Rewrite each chain to use an independent load.
8196 // By construction, each chain can be represented by a unique load.
8198 // Prepare the argument for the new token factor for all the slices.
8199 SmallVector<SDValue, 8> ArgChains;
8200 for (SmallVectorImpl<LoadedSlice>::const_iterator
8201 LSIt = LoadedSlices.begin(),
8202 LSItEnd = LoadedSlices.end();
8203 LSIt != LSItEnd; ++LSIt) {
8204 SDValue SliceInst = LSIt->loadSlice();
8205 CombineTo(LSIt->Inst, SliceInst, true);
8206 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8207 SliceInst = SliceInst.getOperand(0);
8208 assert(SliceInst->getOpcode() == ISD::LOAD &&
8209 "It takes more than a zext to get to the loaded slice!!");
8210 ArgChains.push_back(SliceInst.getValue(1));
8213 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8214 &ArgChains[0], ArgChains.size());
8215 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8219 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8220 /// load is having specific bytes cleared out. If so, return the byte size
8221 /// being masked out and the shift amount.
8222 static std::pair<unsigned, unsigned>
8223 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8224 std::pair<unsigned, unsigned> Result(0, 0);
8226 // Check for the structure we're looking for.
8227 if (V->getOpcode() != ISD::AND ||
8228 !isa<ConstantSDNode>(V->getOperand(1)) ||
8229 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8232 // Check the chain and pointer.
8233 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8234 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8236 // The store should be chained directly to the load or be an operand of a
8238 if (LD == Chain.getNode())
8240 else if (Chain->getOpcode() != ISD::TokenFactor)
8241 return Result; // Fail.
8244 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8245 if (Chain->getOperand(i).getNode() == LD) {
8249 if (!isOk) return Result;
8252 // This only handles simple types.
8253 if (V.getValueType() != MVT::i16 &&
8254 V.getValueType() != MVT::i32 &&
8255 V.getValueType() != MVT::i64)
8258 // Check the constant mask. Invert it so that the bits being masked out are
8259 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8260 // follow the sign bit for uniformity.
8261 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8262 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8263 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8264 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8265 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8266 if (NotMaskLZ == 64) return Result; // All zero mask.
8268 // See if we have a continuous run of bits. If so, we have 0*1+0*
8269 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8272 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8273 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8274 NotMaskLZ -= 64-V.getValueSizeInBits();
8276 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8277 switch (MaskedBytes) {
8281 default: return Result; // All one mask, or 5-byte mask.
8284 // Verify that the first bit starts at a multiple of mask so that the access
8285 // is aligned the same as the access width.
8286 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8288 Result.first = MaskedBytes;
8289 Result.second = NotMaskTZ/8;
8294 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8295 /// provides a value as specified by MaskInfo. If so, replace the specified
8296 /// store with a narrower store of truncated IVal.
8298 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8299 SDValue IVal, StoreSDNode *St,
8301 unsigned NumBytes = MaskInfo.first;
8302 unsigned ByteShift = MaskInfo.second;
8303 SelectionDAG &DAG = DC->getDAG();
8305 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8306 // that uses this. If not, this is not a replacement.
8307 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8308 ByteShift*8, (ByteShift+NumBytes)*8);
8309 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8311 // Check that it is legal on the target to do this. It is legal if the new
8312 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8314 MVT VT = MVT::getIntegerVT(NumBytes*8);
8315 if (!DC->isTypeLegal(VT))
8318 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8319 // shifted by ByteShift and truncated down to NumBytes.
8321 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8322 DAG.getConstant(ByteShift*8,
8323 DC->getShiftAmountTy(IVal.getValueType())));
8325 // Figure out the offset for the store and the alignment of the access.
8327 unsigned NewAlign = St->getAlignment();
8329 if (DAG.getTargetLoweringInfo().isLittleEndian())
8330 StOffset = ByteShift;
8332 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8334 SDValue Ptr = St->getBasePtr();
8336 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8337 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8338 NewAlign = MinAlign(NewAlign, StOffset);
8341 // Truncate down to the new size.
8342 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8345 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8346 St->getPointerInfo().getWithOffset(StOffset),
8347 false, false, NewAlign).getNode();
8351 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8352 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8353 /// of the loaded bits, try narrowing the load and store if it would end up
8354 /// being a win for performance or code size.
8355 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8356 StoreSDNode *ST = cast<StoreSDNode>(N);
8357 if (ST->isVolatile())
8360 SDValue Chain = ST->getChain();
8361 SDValue Value = ST->getValue();
8362 SDValue Ptr = ST->getBasePtr();
8363 EVT VT = Value.getValueType();
8365 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8368 unsigned Opc = Value.getOpcode();
8370 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8371 // is a byte mask indicating a consecutive number of bytes, check to see if
8372 // Y is known to provide just those bytes. If so, we try to replace the
8373 // load + replace + store sequence with a single (narrower) store, which makes
8375 if (Opc == ISD::OR) {
8376 std::pair<unsigned, unsigned> MaskedLoad;
8377 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8378 if (MaskedLoad.first)
8379 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8380 Value.getOperand(1), ST,this))
8381 return SDValue(NewST, 0);
8383 // Or is commutative, so try swapping X and Y.
8384 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8385 if (MaskedLoad.first)
8386 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8387 Value.getOperand(0), ST,this))
8388 return SDValue(NewST, 0);
8391 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8392 Value.getOperand(1).getOpcode() != ISD::Constant)
8395 SDValue N0 = Value.getOperand(0);
8396 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8397 Chain == SDValue(N0.getNode(), 1)) {
8398 LoadSDNode *LD = cast<LoadSDNode>(N0);
8399 if (LD->getBasePtr() != Ptr ||
8400 LD->getPointerInfo().getAddrSpace() !=
8401 ST->getPointerInfo().getAddrSpace())
8404 // Find the type to narrow it the load / op / store to.
8405 SDValue N1 = Value.getOperand(1);
8406 unsigned BitWidth = N1.getValueSizeInBits();
8407 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8408 if (Opc == ISD::AND)
8409 Imm ^= APInt::getAllOnesValue(BitWidth);
8410 if (Imm == 0 || Imm.isAllOnesValue())
8412 unsigned ShAmt = Imm.countTrailingZeros();
8413 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8414 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8415 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8416 while (NewBW < BitWidth &&
8417 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8418 TLI.isNarrowingProfitable(VT, NewVT))) {
8419 NewBW = NextPowerOf2(NewBW);
8420 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8422 if (NewBW >= BitWidth)
8425 // If the lsb changed does not start at the type bitwidth boundary,
8426 // start at the previous one.
8428 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8429 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8430 std::min(BitWidth, ShAmt + NewBW));
8431 if ((Imm & Mask) == Imm) {
8432 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8433 if (Opc == ISD::AND)
8434 NewImm ^= APInt::getAllOnesValue(NewBW);
8435 uint64_t PtrOff = ShAmt / 8;
8436 // For big endian targets, we need to adjust the offset to the pointer to
8437 // load the correct bytes.
8438 if (TLI.isBigEndian())
8439 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8441 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8442 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8443 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8446 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8447 Ptr.getValueType(), Ptr,
8448 DAG.getConstant(PtrOff, Ptr.getValueType()));
8449 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8450 LD->getChain(), NewPtr,
8451 LD->getPointerInfo().getWithOffset(PtrOff),
8452 LD->isVolatile(), LD->isNonTemporal(),
8453 LD->isInvariant(), NewAlign,
8455 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8456 DAG.getConstant(NewImm, NewVT));
8457 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8459 ST->getPointerInfo().getWithOffset(PtrOff),
8460 false, false, NewAlign);
8462 AddToWorkList(NewPtr.getNode());
8463 AddToWorkList(NewLD.getNode());
8464 AddToWorkList(NewVal.getNode());
8465 WorkListRemover DeadNodes(*this);
8466 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8475 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8476 /// if the load value isn't used by any other operations, then consider
8477 /// transforming the pair to integer load / store operations if the target
8478 /// deems the transformation profitable.
8479 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8480 StoreSDNode *ST = cast<StoreSDNode>(N);
8481 SDValue Chain = ST->getChain();
8482 SDValue Value = ST->getValue();
8483 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8484 Value.hasOneUse() &&
8485 Chain == SDValue(Value.getNode(), 1)) {
8486 LoadSDNode *LD = cast<LoadSDNode>(Value);
8487 EVT VT = LD->getMemoryVT();
8488 if (!VT.isFloatingPoint() ||
8489 VT != ST->getMemoryVT() ||
8490 LD->isNonTemporal() ||
8491 ST->isNonTemporal() ||
8492 LD->getPointerInfo().getAddrSpace() != 0 ||
8493 ST->getPointerInfo().getAddrSpace() != 0)
8496 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8497 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8498 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8499 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8500 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8503 unsigned LDAlign = LD->getAlignment();
8504 unsigned STAlign = ST->getAlignment();
8505 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8506 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8507 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8510 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8511 LD->getChain(), LD->getBasePtr(),
8512 LD->getPointerInfo(),
8513 false, false, false, LDAlign);
8515 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8516 NewLD, ST->getBasePtr(),
8517 ST->getPointerInfo(),
8518 false, false, STAlign);
8520 AddToWorkList(NewLD.getNode());
8521 AddToWorkList(NewST.getNode());
8522 WorkListRemover DeadNodes(*this);
8523 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8531 /// Helper struct to parse and store a memory address as base + index + offset.
8532 /// We ignore sign extensions when it is safe to do so.
8533 /// The following two expressions are not equivalent. To differentiate we need
8534 /// to store whether there was a sign extension involved in the index
8536 /// (load (i64 add (i64 copyfromreg %c)
8537 /// (i64 signextend (add (i8 load %index)
8541 /// (load (i64 add (i64 copyfromreg %c)
8542 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8544 struct BaseIndexOffset {
8548 bool IsIndexSignExt;
8550 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8552 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8553 bool IsIndexSignExt) :
8554 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8556 bool equalBaseIndex(const BaseIndexOffset &Other) {
8557 return Other.Base == Base && Other.Index == Index &&
8558 Other.IsIndexSignExt == IsIndexSignExt;
8561 /// Parses tree in Ptr for base, index, offset addresses.
8562 static BaseIndexOffset match(SDValue Ptr) {
8563 bool IsIndexSignExt = false;
8565 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8566 // instruction, then it could be just the BASE or everything else we don't
8567 // know how to handle. Just use Ptr as BASE and give up.
8568 if (Ptr->getOpcode() != ISD::ADD)
8569 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8571 // We know that we have at least an ADD instruction. Try to pattern match
8572 // the simple case of BASE + OFFSET.
8573 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8574 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8575 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8579 // Inside a loop the current BASE pointer is calculated using an ADD and a
8580 // MUL instruction. In this case Ptr is the actual BASE pointer.
8581 // (i64 add (i64 %array_ptr)
8582 // (i64 mul (i64 %induction_var)
8583 // (i64 %element_size)))
8584 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8585 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8587 // Look at Base + Index + Offset cases.
8588 SDValue Base = Ptr->getOperand(0);
8589 SDValue IndexOffset = Ptr->getOperand(1);
8591 // Skip signextends.
8592 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8593 IndexOffset = IndexOffset->getOperand(0);
8594 IsIndexSignExt = true;
8597 // Either the case of Base + Index (no offset) or something else.
8598 if (IndexOffset->getOpcode() != ISD::ADD)
8599 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8601 // Now we have the case of Base + Index + offset.
8602 SDValue Index = IndexOffset->getOperand(0);
8603 SDValue Offset = IndexOffset->getOperand(1);
8605 if (!isa<ConstantSDNode>(Offset))
8606 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8608 // Ignore signextends.
8609 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8610 Index = Index->getOperand(0);
8611 IsIndexSignExt = true;
8612 } else IsIndexSignExt = false;
8614 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8615 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8619 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8620 /// is located in a sequence of memory operations connected by a chain.
8622 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8623 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8624 // Ptr to the mem node.
8625 LSBaseSDNode *MemNode;
8626 // Offset from the base ptr.
8627 int64_t OffsetFromBase;
8628 // What is the sequence number of this mem node.
8629 // Lowest mem operand in the DAG starts at zero.
8630 unsigned SequenceNum;
8633 /// Sorts store nodes in a link according to their offset from a shared
8635 struct ConsecutiveMemoryChainSorter {
8636 bool operator()(MemOpLink LHS, MemOpLink RHS) {
8637 return LHS.OffsetFromBase < RHS.OffsetFromBase;
8641 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8642 EVT MemVT = St->getMemoryVT();
8643 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8644 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8645 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8647 // Don't merge vectors into wider inputs.
8648 if (MemVT.isVector() || !MemVT.isSimple())
8651 // Perform an early exit check. Do not bother looking at stored values that
8652 // are not constants or loads.
8653 SDValue StoredVal = St->getValue();
8654 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8655 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8659 // Only look at ends of store sequences.
8660 SDValue Chain = SDValue(St, 1);
8661 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8664 // This holds the base pointer, index, and the offset in bytes from the base
8666 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8668 // We must have a base and an offset.
8669 if (!BasePtr.Base.getNode())
8672 // Do not handle stores to undef base pointers.
8673 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8676 // Save the LoadSDNodes that we find in the chain.
8677 // We need to make sure that these nodes do not interfere with
8678 // any of the store nodes.
8679 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8681 // Save the StoreSDNodes that we find in the chain.
8682 SmallVector<MemOpLink, 8> StoreNodes;
8684 // Walk up the chain and look for nodes with offsets from the same
8685 // base pointer. Stop when reaching an instruction with a different kind
8686 // or instruction which has a different base pointer.
8688 StoreSDNode *Index = St;
8690 // If the chain has more than one use, then we can't reorder the mem ops.
8691 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8694 // Find the base pointer and offset for this memory node.
8695 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8697 // Check that the base pointer is the same as the original one.
8698 if (!Ptr.equalBaseIndex(BasePtr))
8701 // Check that the alignment is the same.
8702 if (Index->getAlignment() != St->getAlignment())
8705 // The memory operands must not be volatile.
8706 if (Index->isVolatile() || Index->isIndexed())
8710 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8711 if (St->isTruncatingStore())
8714 // The stored memory type must be the same.
8715 if (Index->getMemoryVT() != MemVT)
8718 // We do not allow unaligned stores because we want to prevent overriding
8720 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8723 // We found a potential memory operand to merge.
8724 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8726 // Find the next memory operand in the chain. If the next operand in the
8727 // chain is a store then move up and continue the scan with the next
8728 // memory operand. If the next operand is a load save it and use alias
8729 // information to check if it interferes with anything.
8730 SDNode *NextInChain = Index->getChain().getNode();
8732 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8733 // We found a store node. Use it for the next iteration.
8736 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8737 if (Ldn->isVolatile()) {
8742 // Save the load node for later. Continue the scan.
8743 AliasLoadNodes.push_back(Ldn);
8744 NextInChain = Ldn->getChain().getNode();
8753 // Check if there is anything to merge.
8754 if (StoreNodes.size() < 2)
8757 // Sort the memory operands according to their distance from the base pointer.
8758 std::sort(StoreNodes.begin(), StoreNodes.end(),
8759 ConsecutiveMemoryChainSorter());
8761 // Scan the memory operations on the chain and find the first non-consecutive
8762 // store memory address.
8763 unsigned LastConsecutiveStore = 0;
8764 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8765 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8767 // Check that the addresses are consecutive starting from the second
8768 // element in the list of stores.
8770 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8771 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8776 // Check if this store interferes with any of the loads that we found.
8777 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8778 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8782 // We found a load that alias with this store. Stop the sequence.
8786 // Mark this node as useful.
8787 LastConsecutiveStore = i;
8790 // The node with the lowest store address.
8791 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8793 // Store the constants into memory as one consecutive store.
8795 unsigned LastLegalType = 0;
8796 unsigned LastLegalVectorType = 0;
8797 bool NonZero = false;
8798 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8799 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8800 SDValue StoredVal = St->getValue();
8802 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8803 NonZero |= !C->isNullValue();
8804 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8805 NonZero |= !C->getConstantFPValue()->isNullValue();
8811 // Find a legal type for the constant store.
8812 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8813 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8814 if (TLI.isTypeLegal(StoreTy))
8815 LastLegalType = i+1;
8816 // Or check whether a truncstore is legal.
8817 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8818 TargetLowering::TypePromoteInteger) {
8819 EVT LegalizedStoredValueTy =
8820 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8821 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8822 LastLegalType = i+1;
8825 // Find a legal type for the vector store.
8826 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8827 if (TLI.isTypeLegal(Ty))
8828 LastLegalVectorType = i + 1;
8831 // We only use vectors if the constant is known to be zero and the
8832 // function is not marked with the noimplicitfloat attribute.
8833 if (NonZero || NoVectors)
8834 LastLegalVectorType = 0;
8836 // Check if we found a legal integer type to store.
8837 if (LastLegalType == 0 && LastLegalVectorType == 0)
8840 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8841 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8843 // Make sure we have something to merge.
8847 unsigned EarliestNodeUsed = 0;
8848 for (unsigned i=0; i < NumElem; ++i) {
8849 // Find a chain for the new wide-store operand. Notice that some
8850 // of the store nodes that we found may not be selected for inclusion
8851 // in the wide store. The chain we use needs to be the chain of the
8852 // earliest store node which is *used* and replaced by the wide store.
8853 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8854 EarliestNodeUsed = i;
8857 // The earliest Node in the DAG.
8858 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8859 SDLoc DL(StoreNodes[0].MemNode);
8863 // Find a legal type for the vector store.
8864 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8865 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8866 StoredVal = DAG.getConstant(0, Ty);
8868 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8869 APInt StoreInt(StoreBW, 0);
8871 // Construct a single integer constant which is made of the smaller
8873 bool IsLE = TLI.isLittleEndian();
8874 for (unsigned i = 0; i < NumElem ; ++i) {
8875 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8876 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8877 SDValue Val = St->getValue();
8878 StoreInt<<=ElementSizeBytes*8;
8879 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8880 StoreInt|=C->getAPIntValue().zext(StoreBW);
8881 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8882 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8884 assert(false && "Invalid constant element type");
8888 // Create the new Load and Store operations.
8889 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8890 StoredVal = DAG.getConstant(StoreInt, StoreTy);
8893 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8894 FirstInChain->getBasePtr(),
8895 FirstInChain->getPointerInfo(),
8897 FirstInChain->getAlignment());
8899 // Replace the first store with the new store
8900 CombineTo(EarliestOp, NewStore);
8901 // Erase all other stores.
8902 for (unsigned i = 0; i < NumElem ; ++i) {
8903 if (StoreNodes[i].MemNode == EarliestOp)
8905 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8906 // ReplaceAllUsesWith will replace all uses that existed when it was
8907 // called, but graph optimizations may cause new ones to appear. For
8908 // example, the case in pr14333 looks like
8910 // St's chain -> St -> another store -> X
8912 // And the only difference from St to the other store is the chain.
8913 // When we change it's chain to be St's chain they become identical,
8914 // get CSEed and the net result is that X is now a use of St.
8915 // Since we know that St is redundant, just iterate.
8916 while (!St->use_empty())
8917 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8918 removeFromWorkList(St);
8925 // Below we handle the case of multiple consecutive stores that
8926 // come from multiple consecutive loads. We merge them into a single
8927 // wide load and a single wide store.
8929 // Look for load nodes which are used by the stored values.
8930 SmallVector<MemOpLink, 8> LoadNodes;
8932 // Find acceptable loads. Loads need to have the same chain (token factor),
8933 // must not be zext, volatile, indexed, and they must be consecutive.
8934 BaseIndexOffset LdBasePtr;
8935 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8936 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8937 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8940 // Loads must only have one use.
8941 if (!Ld->hasNUsesOfValue(1, 0))
8944 // Check that the alignment is the same as the stores.
8945 if (Ld->getAlignment() != St->getAlignment())
8948 // The memory operands must not be volatile.
8949 if (Ld->isVolatile() || Ld->isIndexed())
8952 // We do not accept ext loads.
8953 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8956 // The stored memory type must be the same.
8957 if (Ld->getMemoryVT() != MemVT)
8960 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8961 // If this is not the first ptr that we check.
8962 if (LdBasePtr.Base.getNode()) {
8963 // The base ptr must be the same.
8964 if (!LdPtr.equalBaseIndex(LdBasePtr))
8967 // Check that all other base pointers are the same as this one.
8971 // We found a potential memory operand to merge.
8972 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8975 if (LoadNodes.size() < 2)
8978 // Scan the memory operations on the chain and find the first non-consecutive
8979 // load memory address. These variables hold the index in the store node
8981 unsigned LastConsecutiveLoad = 0;
8982 // This variable refers to the size and not index in the array.
8983 unsigned LastLegalVectorType = 0;
8984 unsigned LastLegalIntegerType = 0;
8985 StartAddress = LoadNodes[0].OffsetFromBase;
8986 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8987 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8988 // All loads much share the same chain.
8989 if (LoadNodes[i].MemNode->getChain() != FirstChain)
8992 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8993 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8995 LastConsecutiveLoad = i;
8997 // Find a legal type for the vector store.
8998 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8999 if (TLI.isTypeLegal(StoreTy))
9000 LastLegalVectorType = i + 1;
9002 // Find a legal type for the integer store.
9003 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9004 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9005 if (TLI.isTypeLegal(StoreTy))
9006 LastLegalIntegerType = i + 1;
9007 // Or check whether a truncstore and extload is legal.
9008 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9009 TargetLowering::TypePromoteInteger) {
9010 EVT LegalizedStoredValueTy =
9011 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9012 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9013 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9014 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9015 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9016 LastLegalIntegerType = i+1;
9020 // Only use vector types if the vector type is larger than the integer type.
9021 // If they are the same, use integers.
9022 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9023 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9025 // We add +1 here because the LastXXX variables refer to location while
9026 // the NumElem refers to array/index size.
9027 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9028 NumElem = std::min(LastLegalType, NumElem);
9033 // The earliest Node in the DAG.
9034 unsigned EarliestNodeUsed = 0;
9035 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9036 for (unsigned i=1; i<NumElem; ++i) {
9037 // Find a chain for the new wide-store operand. Notice that some
9038 // of the store nodes that we found may not be selected for inclusion
9039 // in the wide store. The chain we use needs to be the chain of the
9040 // earliest store node which is *used* and replaced by the wide store.
9041 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9042 EarliestNodeUsed = i;
9045 // Find if it is better to use vectors or integers to load and store
9049 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9051 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9052 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9055 SDLoc LoadDL(LoadNodes[0].MemNode);
9056 SDLoc StoreDL(StoreNodes[0].MemNode);
9058 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9059 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9060 FirstLoad->getChain(),
9061 FirstLoad->getBasePtr(),
9062 FirstLoad->getPointerInfo(),
9063 false, false, false,
9064 FirstLoad->getAlignment());
9066 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9067 FirstInChain->getBasePtr(),
9068 FirstInChain->getPointerInfo(), false, false,
9069 FirstInChain->getAlignment());
9071 // Replace one of the loads with the new load.
9072 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9073 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9074 SDValue(NewLoad.getNode(), 1));
9076 // Remove the rest of the load chains.
9077 for (unsigned i = 1; i < NumElem ; ++i) {
9078 // Replace all chain users of the old load nodes with the chain of the new
9080 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9081 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9084 // Replace the first store with the new store.
9085 CombineTo(EarliestOp, NewStore);
9086 // Erase all other stores.
9087 for (unsigned i = 0; i < NumElem ; ++i) {
9088 // Remove all Store nodes.
9089 if (StoreNodes[i].MemNode == EarliestOp)
9091 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9092 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9093 removeFromWorkList(St);
9100 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9101 StoreSDNode *ST = cast<StoreSDNode>(N);
9102 SDValue Chain = ST->getChain();
9103 SDValue Value = ST->getValue();
9104 SDValue Ptr = ST->getBasePtr();
9106 // If this is a store of a bit convert, store the input value if the
9107 // resultant store does not need a higher alignment than the original.
9108 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9109 ST->isUnindexed()) {
9110 unsigned OrigAlign = ST->getAlignment();
9111 EVT SVT = Value.getOperand(0).getValueType();
9112 unsigned Align = TLI.getDataLayout()->
9113 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9114 if (Align <= OrigAlign &&
9115 ((!LegalOperations && !ST->isVolatile()) ||
9116 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9117 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9118 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9119 ST->isNonTemporal(), OrigAlign,
9123 // Turn 'store undef, Ptr' -> nothing.
9124 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9127 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9128 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9129 // NOTE: If the original store is volatile, this transform must not increase
9130 // the number of stores. For example, on x86-32 an f64 can be stored in one
9131 // processor operation but an i64 (which is not legal) requires two. So the
9132 // transform should not be done in this case.
9133 if (Value.getOpcode() != ISD::TargetConstantFP) {
9135 switch (CFP->getSimpleValueType(0).SimpleTy) {
9136 default: llvm_unreachable("Unknown FP type");
9137 case MVT::f16: // We don't do this for these yet.
9143 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9144 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9145 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9146 bitcastToAPInt().getZExtValue(), MVT::i32);
9147 return DAG.getStore(Chain, SDLoc(N), Tmp,
9148 Ptr, ST->getMemOperand());
9152 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9153 !ST->isVolatile()) ||
9154 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9155 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9156 getZExtValue(), MVT::i64);
9157 return DAG.getStore(Chain, SDLoc(N), Tmp,
9158 Ptr, ST->getMemOperand());
9161 if (!ST->isVolatile() &&
9162 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9163 // Many FP stores are not made apparent until after legalize, e.g. for
9164 // argument passing. Since this is so common, custom legalize the
9165 // 64-bit integer store into two 32-bit stores.
9166 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9167 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9168 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9169 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9171 unsigned Alignment = ST->getAlignment();
9172 bool isVolatile = ST->isVolatile();
9173 bool isNonTemporal = ST->isNonTemporal();
9174 const MDNode *TBAAInfo = ST->getTBAAInfo();
9176 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9177 Ptr, ST->getPointerInfo(),
9178 isVolatile, isNonTemporal,
9179 ST->getAlignment(), TBAAInfo);
9180 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9181 DAG.getConstant(4, Ptr.getValueType()));
9182 Alignment = MinAlign(Alignment, 4U);
9183 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9184 Ptr, ST->getPointerInfo().getWithOffset(4),
9185 isVolatile, isNonTemporal,
9186 Alignment, TBAAInfo);
9187 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9196 // Try to infer better alignment information than the store already has.
9197 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9198 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9199 if (Align > ST->getAlignment())
9200 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9201 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9202 ST->isVolatile(), ST->isNonTemporal(), Align,
9207 // Try transforming a pair floating point load / store ops to integer
9208 // load / store ops.
9209 SDValue NewST = TransformFPLoadStorePair(N);
9210 if (NewST.getNode())
9213 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9214 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9216 // Walk up chain skipping non-aliasing memory nodes.
9217 SDValue BetterChain = FindBetterChain(N, Chain);
9219 // If there is a better chain.
9220 if (Chain != BetterChain) {
9223 // Replace the chain to avoid dependency.
9224 if (ST->isTruncatingStore()) {
9225 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9226 ST->getMemoryVT(), ST->getMemOperand());
9228 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9229 ST->getMemOperand());
9232 // Create token to keep both nodes around.
9233 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9234 MVT::Other, Chain, ReplStore);
9236 // Make sure the new and old chains are cleaned up.
9237 AddToWorkList(Token.getNode());
9239 // Don't add users to work list.
9240 return CombineTo(N, Token, false);
9244 // Try transforming N to an indexed store.
9245 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9246 return SDValue(N, 0);
9248 // FIXME: is there such a thing as a truncating indexed store?
9249 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9250 Value.getValueType().isInteger()) {
9251 // See if we can simplify the input to this truncstore with knowledge that
9252 // only the low bits are being used. For example:
9253 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9255 GetDemandedBits(Value,
9256 APInt::getLowBitsSet(
9257 Value.getValueType().getScalarType().getSizeInBits(),
9258 ST->getMemoryVT().getScalarType().getSizeInBits()));
9259 AddToWorkList(Value.getNode());
9260 if (Shorter.getNode())
9261 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9262 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9264 // Otherwise, see if we can simplify the operation with
9265 // SimplifyDemandedBits, which only works if the value has a single use.
9266 if (SimplifyDemandedBits(Value,
9267 APInt::getLowBitsSet(
9268 Value.getValueType().getScalarType().getSizeInBits(),
9269 ST->getMemoryVT().getScalarType().getSizeInBits())))
9270 return SDValue(N, 0);
9273 // If this is a load followed by a store to the same location, then the store
9275 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9276 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9277 ST->isUnindexed() && !ST->isVolatile() &&
9278 // There can't be any side effects between the load and store, such as
9280 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9281 // The store is dead, remove it.
9286 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9287 // truncating store. We can do this even if this is already a truncstore.
9288 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9289 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9290 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9291 ST->getMemoryVT())) {
9292 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9293 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9296 // Only perform this optimization before the types are legal, because we
9297 // don't want to perform this optimization on every DAGCombine invocation.
9299 bool EverChanged = false;
9302 // There can be multiple store sequences on the same chain.
9303 // Keep trying to merge store sequences until we are unable to do so
9304 // or until we merge the last store on the chain.
9305 bool Changed = MergeConsecutiveStores(ST);
9306 EverChanged |= Changed;
9307 if (!Changed) break;
9308 } while (ST->getOpcode() != ISD::DELETED_NODE);
9311 return SDValue(N, 0);
9314 return ReduceLoadOpStoreWidth(N);
9317 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9318 SDValue InVec = N->getOperand(0);
9319 SDValue InVal = N->getOperand(1);
9320 SDValue EltNo = N->getOperand(2);
9323 // If the inserted element is an UNDEF, just use the input vector.
9324 if (InVal.getOpcode() == ISD::UNDEF)
9327 EVT VT = InVec.getValueType();
9329 // If we can't generate a legal BUILD_VECTOR, exit
9330 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9333 // Check that we know which element is being inserted
9334 if (!isa<ConstantSDNode>(EltNo))
9336 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9338 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9339 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9341 SmallVector<SDValue, 8> Ops;
9342 // Do not combine these two vectors if the output vector will not replace
9343 // the input vector.
9344 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9345 Ops.append(InVec.getNode()->op_begin(),
9346 InVec.getNode()->op_end());
9347 } else if (InVec.getOpcode() == ISD::UNDEF) {
9348 unsigned NElts = VT.getVectorNumElements();
9349 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9354 // Insert the element
9355 if (Elt < Ops.size()) {
9356 // All the operands of BUILD_VECTOR must have the same type;
9357 // we enforce that here.
9358 EVT OpVT = Ops[0].getValueType();
9359 if (InVal.getValueType() != OpVT)
9360 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9361 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9362 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9366 // Return the new vector
9367 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9368 VT, &Ops[0], Ops.size());
9371 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9372 // (vextract (scalar_to_vector val, 0) -> val
9373 SDValue InVec = N->getOperand(0);
9374 EVT VT = InVec.getValueType();
9375 EVT NVT = N->getValueType(0);
9377 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9378 // Check if the result type doesn't match the inserted element type. A
9379 // SCALAR_TO_VECTOR may truncate the inserted element and the
9380 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9381 SDValue InOp = InVec.getOperand(0);
9382 if (InOp.getValueType() != NVT) {
9383 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9384 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9389 SDValue EltNo = N->getOperand(1);
9390 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9392 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9393 // We only perform this optimization before the op legalization phase because
9394 // we may introduce new vector instructions which are not backed by TD
9395 // patterns. For example on AVX, extracting elements from a wide vector
9396 // without using extract_subvector.
9397 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9398 && ConstEltNo && !LegalOperations) {
9399 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9400 int NumElem = VT.getVectorNumElements();
9401 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9402 // Find the new index to extract from.
9403 int OrigElt = SVOp->getMaskElt(Elt);
9405 // Extracting an undef index is undef.
9407 return DAG.getUNDEF(NVT);
9409 // Select the right vector half to extract from.
9410 if (OrigElt < NumElem) {
9411 InVec = InVec->getOperand(0);
9413 InVec = InVec->getOperand(1);
9417 EVT IndexTy = TLI.getVectorIdxTy();
9418 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9419 InVec, DAG.getConstant(OrigElt, IndexTy));
9422 // Perform only after legalization to ensure build_vector / vector_shuffle
9423 // optimizations have already been done.
9424 if (!LegalOperations) return SDValue();
9426 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9427 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9428 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9431 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9432 bool NewLoad = false;
9433 bool BCNumEltsChanged = false;
9434 EVT ExtVT = VT.getVectorElementType();
9437 // If the result of load has to be truncated, then it's not necessarily
9439 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9442 if (InVec.getOpcode() == ISD::BITCAST) {
9443 // Don't duplicate a load with other uses.
9444 if (!InVec.hasOneUse())
9447 EVT BCVT = InVec.getOperand(0).getValueType();
9448 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9450 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9451 BCNumEltsChanged = true;
9452 InVec = InVec.getOperand(0);
9453 ExtVT = BCVT.getVectorElementType();
9457 LoadSDNode *LN0 = NULL;
9458 const ShuffleVectorSDNode *SVN = NULL;
9459 if (ISD::isNormalLoad(InVec.getNode())) {
9460 LN0 = cast<LoadSDNode>(InVec);
9461 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9462 InVec.getOperand(0).getValueType() == ExtVT &&
9463 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9464 // Don't duplicate a load with other uses.
9465 if (!InVec.hasOneUse())
9468 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9469 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9470 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9472 // (load $addr+1*size)
9474 // Don't duplicate a load with other uses.
9475 if (!InVec.hasOneUse())
9478 // If the bit convert changed the number of elements, it is unsafe
9479 // to examine the mask.
9480 if (BCNumEltsChanged)
9483 // Select the input vector, guarding against out of range extract vector.
9484 unsigned NumElems = VT.getVectorNumElements();
9485 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9486 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9488 if (InVec.getOpcode() == ISD::BITCAST) {
9489 // Don't duplicate a load with other uses.
9490 if (!InVec.hasOneUse())
9493 InVec = InVec.getOperand(0);
9495 if (ISD::isNormalLoad(InVec.getNode())) {
9496 LN0 = cast<LoadSDNode>(InVec);
9497 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9501 // Make sure we found a non-volatile load and the extractelement is
9503 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9506 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9508 return DAG.getUNDEF(LVT);
9510 unsigned Align = LN0->getAlignment();
9512 // Check the resultant load doesn't need a higher alignment than the
9516 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9518 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9524 SDValue NewPtr = LN0->getBasePtr();
9525 unsigned PtrOff = 0;
9528 PtrOff = LVT.getSizeInBits() * Elt / 8;
9529 EVT PtrType = NewPtr.getValueType();
9530 if (TLI.isBigEndian())
9531 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9532 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9533 DAG.getConstant(PtrOff, PtrType));
9536 // The replacement we need to do here is a little tricky: we need to
9537 // replace an extractelement of a load with a load.
9538 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9539 // Note that this replacement assumes that the extractvalue is the only
9540 // use of the load; that's okay because we don't want to perform this
9541 // transformation in other cases anyway.
9544 if (NVT.bitsGT(LVT)) {
9545 // If the result type of vextract is wider than the load, then issue an
9546 // extending load instead.
9547 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9548 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9549 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9550 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9551 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9552 Align, LN0->getTBAAInfo());
9553 Chain = Load.getValue(1);
9555 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9556 LN0->getPointerInfo().getWithOffset(PtrOff),
9557 LN0->isVolatile(), LN0->isNonTemporal(),
9558 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9559 Chain = Load.getValue(1);
9560 if (NVT.bitsLT(LVT))
9561 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9563 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9565 WorkListRemover DeadNodes(*this);
9566 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9567 SDValue To[] = { Load, Chain };
9568 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9569 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9570 // worklist explicitly as well.
9571 AddToWorkList(Load.getNode());
9572 AddUsersToWorkList(Load.getNode()); // Add users too
9573 // Make sure to revisit this node to clean it up; it will usually be dead.
9575 return SDValue(N, 0);
9581 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9582 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9583 // We perform this optimization post type-legalization because
9584 // the type-legalizer often scalarizes integer-promoted vectors.
9585 // Performing this optimization before may create bit-casts which
9586 // will be type-legalized to complex code sequences.
9587 // We perform this optimization only before the operation legalizer because we
9588 // may introduce illegal operations.
9589 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9592 unsigned NumInScalars = N->getNumOperands();
9594 EVT VT = N->getValueType(0);
9596 // Check to see if this is a BUILD_VECTOR of a bunch of values
9597 // which come from any_extend or zero_extend nodes. If so, we can create
9598 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9599 // optimizations. We do not handle sign-extend because we can't fill the sign
9601 EVT SourceType = MVT::Other;
9602 bool AllAnyExt = true;
9604 for (unsigned i = 0; i != NumInScalars; ++i) {
9605 SDValue In = N->getOperand(i);
9606 // Ignore undef inputs.
9607 if (In.getOpcode() == ISD::UNDEF) continue;
9609 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9610 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9612 // Abort if the element is not an extension.
9613 if (!ZeroExt && !AnyExt) {
9614 SourceType = MVT::Other;
9618 // The input is a ZeroExt or AnyExt. Check the original type.
9619 EVT InTy = In.getOperand(0).getValueType();
9621 // Check that all of the widened source types are the same.
9622 if (SourceType == MVT::Other)
9625 else if (InTy != SourceType) {
9626 // Multiple income types. Abort.
9627 SourceType = MVT::Other;
9631 // Check if all of the extends are ANY_EXTENDs.
9632 AllAnyExt &= AnyExt;
9635 // In order to have valid types, all of the inputs must be extended from the
9636 // same source type and all of the inputs must be any or zero extend.
9637 // Scalar sizes must be a power of two.
9638 EVT OutScalarTy = VT.getScalarType();
9639 bool ValidTypes = SourceType != MVT::Other &&
9640 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9641 isPowerOf2_32(SourceType.getSizeInBits());
9643 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9644 // turn into a single shuffle instruction.
9648 bool isLE = TLI.isLittleEndian();
9649 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9650 assert(ElemRatio > 1 && "Invalid element size ratio");
9651 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9652 DAG.getConstant(0, SourceType);
9654 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9655 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9657 // Populate the new build_vector
9658 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9659 SDValue Cast = N->getOperand(i);
9660 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9661 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9662 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9664 if (Cast.getOpcode() == ISD::UNDEF)
9665 In = DAG.getUNDEF(SourceType);
9667 In = Cast->getOperand(0);
9668 unsigned Index = isLE ? (i * ElemRatio) :
9669 (i * ElemRatio + (ElemRatio - 1));
9671 assert(Index < Ops.size() && "Invalid index");
9675 // The type of the new BUILD_VECTOR node.
9676 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9677 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9678 "Invalid vector size");
9679 // Check if the new vector type is legal.
9680 if (!isTypeLegal(VecVT)) return SDValue();
9682 // Make the new BUILD_VECTOR.
9683 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9685 // The new BUILD_VECTOR node has the potential to be further optimized.
9686 AddToWorkList(BV.getNode());
9687 // Bitcast to the desired type.
9688 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9691 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9692 EVT VT = N->getValueType(0);
9694 unsigned NumInScalars = N->getNumOperands();
9697 EVT SrcVT = MVT::Other;
9698 unsigned Opcode = ISD::DELETED_NODE;
9699 unsigned NumDefs = 0;
9701 for (unsigned i = 0; i != NumInScalars; ++i) {
9702 SDValue In = N->getOperand(i);
9703 unsigned Opc = In.getOpcode();
9705 if (Opc == ISD::UNDEF)
9708 // If all scalar values are floats and converted from integers.
9709 if (Opcode == ISD::DELETED_NODE &&
9710 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9717 EVT InVT = In.getOperand(0).getValueType();
9719 // If all scalar values are typed differently, bail out. It's chosen to
9720 // simplify BUILD_VECTOR of integer types.
9721 if (SrcVT == MVT::Other)
9728 // If the vector has just one element defined, it's not worth to fold it into
9729 // a vectorized one.
9733 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9734 && "Should only handle conversion from integer to float.");
9735 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9737 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9739 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9742 SmallVector<SDValue, 8> Opnds;
9743 for (unsigned i = 0; i != NumInScalars; ++i) {
9744 SDValue In = N->getOperand(i);
9746 if (In.getOpcode() == ISD::UNDEF)
9747 Opnds.push_back(DAG.getUNDEF(SrcVT));
9749 Opnds.push_back(In.getOperand(0));
9751 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9752 &Opnds[0], Opnds.size());
9753 AddToWorkList(BV.getNode());
9755 return DAG.getNode(Opcode, dl, VT, BV);
9758 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9759 unsigned NumInScalars = N->getNumOperands();
9761 EVT VT = N->getValueType(0);
9763 // A vector built entirely of undefs is undef.
9764 if (ISD::allOperandsUndef(N))
9765 return DAG.getUNDEF(VT);
9767 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9771 V = reduceBuildVecConvertToConvertBuildVec(N);
9775 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9776 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9777 // at most two distinct vectors, turn this into a shuffle node.
9779 // May only combine to shuffle after legalize if shuffle is legal.
9780 if (LegalOperations &&
9781 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9784 SDValue VecIn1, VecIn2;
9785 for (unsigned i = 0; i != NumInScalars; ++i) {
9786 // Ignore undef inputs.
9787 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9789 // If this input is something other than a EXTRACT_VECTOR_ELT with a
9790 // constant index, bail out.
9791 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9792 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9793 VecIn1 = VecIn2 = SDValue(0, 0);
9797 // We allow up to two distinct input vectors.
9798 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9799 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9802 if (VecIn1.getNode() == 0) {
9803 VecIn1 = ExtractedFromVec;
9804 } else if (VecIn2.getNode() == 0) {
9805 VecIn2 = ExtractedFromVec;
9808 VecIn1 = VecIn2 = SDValue(0, 0);
9813 // If everything is good, we can make a shuffle operation.
9814 if (VecIn1.getNode()) {
9815 SmallVector<int, 8> Mask;
9816 for (unsigned i = 0; i != NumInScalars; ++i) {
9817 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9822 // If extracting from the first vector, just use the index directly.
9823 SDValue Extract = N->getOperand(i);
9824 SDValue ExtVal = Extract.getOperand(1);
9825 if (Extract.getOperand(0) == VecIn1) {
9826 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9827 if (ExtIndex > VT.getVectorNumElements())
9830 Mask.push_back(ExtIndex);
9834 // Otherwise, use InIdx + VecSize
9835 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9836 Mask.push_back(Idx+NumInScalars);
9839 // We can't generate a shuffle node with mismatched input and output types.
9840 // Attempt to transform a single input vector to the correct type.
9841 if ((VT != VecIn1.getValueType())) {
9842 // We don't support shuffeling between TWO values of different types.
9843 if (VecIn2.getNode() != 0)
9846 // We only support widening of vectors which are half the size of the
9847 // output registers. For example XMM->YMM widening on X86 with AVX.
9848 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9851 // If the input vector type has a different base type to the output
9852 // vector type, bail out.
9853 if (VecIn1.getValueType().getVectorElementType() !=
9854 VT.getVectorElementType())
9857 // Widen the input vector by adding undef values.
9858 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9859 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9862 // If VecIn2 is unused then change it to undef.
9863 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9865 // Check that we were able to transform all incoming values to the same
9867 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9868 VecIn1.getValueType() != VT)
9871 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9872 if (!isTypeLegal(VT))
9875 // Return the new VECTOR_SHUFFLE node.
9879 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9885 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9886 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9887 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9888 // inputs come from at most two distinct vectors, turn this into a shuffle
9891 // If we only have one input vector, we don't need to do any concatenation.
9892 if (N->getNumOperands() == 1)
9893 return N->getOperand(0);
9895 // Check if all of the operands are undefs.
9896 EVT VT = N->getValueType(0);
9897 if (ISD::allOperandsUndef(N))
9898 return DAG.getUNDEF(VT);
9900 // Optimize concat_vectors where one of the vectors is undef.
9901 if (N->getNumOperands() == 2 &&
9902 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
9903 SDValue In = N->getOperand(0);
9904 assert(In.getValueType().isVector() && "Must concat vectors");
9906 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
9907 if (In->getOpcode() == ISD::BITCAST &&
9908 !In->getOperand(0)->getValueType(0).isVector()) {
9909 SDValue Scalar = In->getOperand(0);
9910 EVT SclTy = Scalar->getValueType(0);
9912 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
9915 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
9916 VT.getSizeInBits() / SclTy.getSizeInBits());
9917 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
9920 SDLoc dl = SDLoc(N);
9921 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
9922 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
9926 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9927 // nodes often generate nop CONCAT_VECTOR nodes.
9928 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9929 // place the incoming vectors at the exact same location.
9930 SDValue SingleSource = SDValue();
9931 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9933 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9934 SDValue Op = N->getOperand(i);
9936 if (Op.getOpcode() == ISD::UNDEF)
9939 // Check if this is the identity extract:
9940 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9943 // Find the single incoming vector for the extract_subvector.
9944 if (SingleSource.getNode()) {
9945 if (Op.getOperand(0) != SingleSource)
9948 SingleSource = Op.getOperand(0);
9950 // Check the source type is the same as the type of the result.
9951 // If not, this concat may extend the vector, so we can not
9952 // optimize it away.
9953 if (SingleSource.getValueType() != N->getValueType(0))
9957 unsigned IdentityIndex = i * PartNumElem;
9958 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9959 // The extract index must be constant.
9963 // Check that we are reading from the identity index.
9964 if (CS->getZExtValue() != IdentityIndex)
9968 if (SingleSource.getNode())
9969 return SingleSource;
9974 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9975 EVT NVT = N->getValueType(0);
9976 SDValue V = N->getOperand(0);
9978 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9980 // (extract_subvec (concat V1, V2, ...), i)
9983 // Only operand 0 is checked as 'concat' assumes all inputs of the same
9985 if (V->getOperand(0).getValueType() != NVT)
9987 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9988 unsigned NumElems = NVT.getVectorNumElements();
9989 assert((Idx % NumElems) == 0 &&
9990 "IDX in concat is not a multiple of the result vector length.");
9991 return V->getOperand(Idx / NumElems);
9995 if (V->getOpcode() == ISD::BITCAST)
9996 V = V.getOperand(0);
9998 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10000 // Handle only simple case where vector being inserted and vector
10001 // being extracted are of same type, and are half size of larger vectors.
10002 EVT BigVT = V->getOperand(0).getValueType();
10003 EVT SmallVT = V->getOperand(1).getValueType();
10004 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10007 // Only handle cases where both indexes are constants with the same type.
10008 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10009 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10011 if (InsIdx && ExtIdx &&
10012 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10013 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10015 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10017 // indices are equal or bit offsets are equal => V1
10018 // otherwise => (extract_subvec V1, ExtIdx)
10019 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10020 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10021 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10022 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10023 DAG.getNode(ISD::BITCAST, dl,
10024 N->getOperand(0).getValueType(),
10025 V->getOperand(0)), N->getOperand(1));
10032 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10033 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10034 EVT VT = N->getValueType(0);
10035 unsigned NumElts = VT.getVectorNumElements();
10037 SDValue N0 = N->getOperand(0);
10038 SDValue N1 = N->getOperand(1);
10039 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10041 SmallVector<SDValue, 4> Ops;
10042 EVT ConcatVT = N0.getOperand(0).getValueType();
10043 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10044 unsigned NumConcats = NumElts / NumElemsPerConcat;
10046 // Look at every vector that's inserted. We're looking for exact
10047 // subvector-sized copies from a concatenated vector
10048 for (unsigned I = 0; I != NumConcats; ++I) {
10049 // Make sure we're dealing with a copy.
10050 unsigned Begin = I * NumElemsPerConcat;
10051 bool AllUndef = true, NoUndef = true;
10052 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10053 if (SVN->getMaskElt(J) >= 0)
10060 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10063 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10064 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10067 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10068 if (FirstElt < N0.getNumOperands())
10069 Ops.push_back(N0.getOperand(FirstElt));
10071 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10073 } else if (AllUndef) {
10074 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10075 } else { // Mixed with general masks and undefs, can't do optimization.
10080 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10084 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10085 EVT VT = N->getValueType(0);
10086 unsigned NumElts = VT.getVectorNumElements();
10088 SDValue N0 = N->getOperand(0);
10089 SDValue N1 = N->getOperand(1);
10091 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10093 // Canonicalize shuffle undef, undef -> undef
10094 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10095 return DAG.getUNDEF(VT);
10097 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10099 // Canonicalize shuffle v, v -> v, undef
10101 SmallVector<int, 8> NewMask;
10102 for (unsigned i = 0; i != NumElts; ++i) {
10103 int Idx = SVN->getMaskElt(i);
10104 if (Idx >= (int)NumElts) Idx -= NumElts;
10105 NewMask.push_back(Idx);
10107 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10111 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10112 if (N0.getOpcode() == ISD::UNDEF) {
10113 SmallVector<int, 8> NewMask;
10114 for (unsigned i = 0; i != NumElts; ++i) {
10115 int Idx = SVN->getMaskElt(i);
10117 if (Idx >= (int)NumElts)
10120 Idx = -1; // remove reference to lhs
10122 NewMask.push_back(Idx);
10124 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10128 // Remove references to rhs if it is undef
10129 if (N1.getOpcode() == ISD::UNDEF) {
10130 bool Changed = false;
10131 SmallVector<int, 8> NewMask;
10132 for (unsigned i = 0; i != NumElts; ++i) {
10133 int Idx = SVN->getMaskElt(i);
10134 if (Idx >= (int)NumElts) {
10138 NewMask.push_back(Idx);
10141 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10144 // If it is a splat, check if the argument vector is another splat or a
10145 // build_vector with all scalar elements the same.
10146 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10147 SDNode *V = N0.getNode();
10149 // If this is a bit convert that changes the element type of the vector but
10150 // not the number of vector elements, look through it. Be careful not to
10151 // look though conversions that change things like v4f32 to v2f64.
10152 if (V->getOpcode() == ISD::BITCAST) {
10153 SDValue ConvInput = V->getOperand(0);
10154 if (ConvInput.getValueType().isVector() &&
10155 ConvInput.getValueType().getVectorNumElements() == NumElts)
10156 V = ConvInput.getNode();
10159 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10160 assert(V->getNumOperands() == NumElts &&
10161 "BUILD_VECTOR has wrong number of operands");
10163 bool AllSame = true;
10164 for (unsigned i = 0; i != NumElts; ++i) {
10165 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10166 Base = V->getOperand(i);
10170 // Splat of <u, u, u, u>, return <u, u, u, u>
10171 if (!Base.getNode())
10173 for (unsigned i = 0; i != NumElts; ++i) {
10174 if (V->getOperand(i) != Base) {
10179 // Splat of <x, x, x, x>, return <x, x, x, x>
10185 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10186 Level < AfterLegalizeVectorOps &&
10187 (N1.getOpcode() == ISD::UNDEF ||
10188 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10189 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10190 SDValue V = partitionShuffleOfConcats(N, DAG);
10196 // If this shuffle node is simply a swizzle of another shuffle node,
10197 // and it reverses the swizzle of the previous shuffle then we can
10198 // optimize shuffle(shuffle(x, undef), undef) -> x.
10199 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10200 N1.getOpcode() == ISD::UNDEF) {
10202 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10204 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10205 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10208 // The incoming shuffle must be of the same type as the result of the
10209 // current shuffle.
10210 assert(OtherSV->getOperand(0).getValueType() == VT &&
10211 "Shuffle types don't match");
10213 for (unsigned i = 0; i != NumElts; ++i) {
10214 int Idx = SVN->getMaskElt(i);
10215 assert(Idx < (int)NumElts && "Index references undef operand");
10216 // Next, this index comes from the first value, which is the incoming
10217 // shuffle. Adopt the incoming index.
10219 Idx = OtherSV->getMaskElt(Idx);
10221 // The combined shuffle must map each index to itself.
10222 if (Idx >= 0 && (unsigned)Idx != i)
10226 return OtherSV->getOperand(0);
10232 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10233 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10234 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10235 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10236 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10237 EVT VT = N->getValueType(0);
10239 SDValue LHS = N->getOperand(0);
10240 SDValue RHS = N->getOperand(1);
10241 if (N->getOpcode() == ISD::AND) {
10242 if (RHS.getOpcode() == ISD::BITCAST)
10243 RHS = RHS.getOperand(0);
10244 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10245 SmallVector<int, 8> Indices;
10246 unsigned NumElts = RHS.getNumOperands();
10247 for (unsigned i = 0; i != NumElts; ++i) {
10248 SDValue Elt = RHS.getOperand(i);
10249 if (!isa<ConstantSDNode>(Elt))
10252 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10253 Indices.push_back(i);
10254 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10255 Indices.push_back(NumElts);
10260 // Let's see if the target supports this vector_shuffle.
10261 EVT RVT = RHS.getValueType();
10262 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10265 // Return the new VECTOR_SHUFFLE node.
10266 EVT EltVT = RVT.getVectorElementType();
10267 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10268 DAG.getConstant(0, EltVT));
10269 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10270 RVT, &ZeroOps[0], ZeroOps.size());
10271 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10272 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10273 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10280 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10281 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10282 assert(N->getValueType(0).isVector() &&
10283 "SimplifyVBinOp only works on vectors!");
10285 SDValue LHS = N->getOperand(0);
10286 SDValue RHS = N->getOperand(1);
10287 SDValue Shuffle = XformToShuffleWithZero(N);
10288 if (Shuffle.getNode()) return Shuffle;
10290 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10292 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10293 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10294 SmallVector<SDValue, 8> Ops;
10295 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10296 SDValue LHSOp = LHS.getOperand(i);
10297 SDValue RHSOp = RHS.getOperand(i);
10298 // If these two elements can't be folded, bail out.
10299 if ((LHSOp.getOpcode() != ISD::UNDEF &&
10300 LHSOp.getOpcode() != ISD::Constant &&
10301 LHSOp.getOpcode() != ISD::ConstantFP) ||
10302 (RHSOp.getOpcode() != ISD::UNDEF &&
10303 RHSOp.getOpcode() != ISD::Constant &&
10304 RHSOp.getOpcode() != ISD::ConstantFP))
10307 // Can't fold divide by zero.
10308 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10309 N->getOpcode() == ISD::FDIV) {
10310 if ((RHSOp.getOpcode() == ISD::Constant &&
10311 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10312 (RHSOp.getOpcode() == ISD::ConstantFP &&
10313 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10317 EVT VT = LHSOp.getValueType();
10318 EVT RVT = RHSOp.getValueType();
10320 // Integer BUILD_VECTOR operands may have types larger than the element
10321 // size (e.g., when the element type is not legal). Prior to type
10322 // legalization, the types may not match between the two BUILD_VECTORS.
10323 // Truncate one of the operands to make them match.
10324 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10325 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10327 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10331 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10333 if (FoldOp.getOpcode() != ISD::UNDEF &&
10334 FoldOp.getOpcode() != ISD::Constant &&
10335 FoldOp.getOpcode() != ISD::ConstantFP)
10337 Ops.push_back(FoldOp);
10338 AddToWorkList(FoldOp.getNode());
10341 if (Ops.size() == LHS.getNumOperands())
10342 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10343 LHS.getValueType(), &Ops[0], Ops.size());
10349 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10350 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10351 assert(N->getValueType(0).isVector() &&
10352 "SimplifyVUnaryOp only works on vectors!");
10354 SDValue N0 = N->getOperand(0);
10356 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10359 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10360 SmallVector<SDValue, 8> Ops;
10361 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10362 SDValue Op = N0.getOperand(i);
10363 if (Op.getOpcode() != ISD::UNDEF &&
10364 Op.getOpcode() != ISD::ConstantFP)
10366 EVT EltVT = Op.getValueType();
10367 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10368 if (FoldOp.getOpcode() != ISD::UNDEF &&
10369 FoldOp.getOpcode() != ISD::ConstantFP)
10371 Ops.push_back(FoldOp);
10372 AddToWorkList(FoldOp.getNode());
10375 if (Ops.size() != N0.getNumOperands())
10378 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10379 N0.getValueType(), &Ops[0], Ops.size());
10382 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10383 SDValue N1, SDValue N2){
10384 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10386 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10387 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10389 // If we got a simplified select_cc node back from SimplifySelectCC, then
10390 // break it down into a new SETCC node, and a new SELECT node, and then return
10391 // the SELECT node, since we were called with a SELECT node.
10392 if (SCC.getNode()) {
10393 // Check to see if we got a select_cc back (to turn into setcc/select).
10394 // Otherwise, just return whatever node we got back, like fabs.
10395 if (SCC.getOpcode() == ISD::SELECT_CC) {
10396 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10398 SCC.getOperand(0), SCC.getOperand(1),
10399 SCC.getOperand(4));
10400 AddToWorkList(SETCC.getNode());
10401 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10402 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10410 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10411 /// are the two values being selected between, see if we can simplify the
10412 /// select. Callers of this should assume that TheSelect is deleted if this
10413 /// returns true. As such, they should return the appropriate thing (e.g. the
10414 /// node) back to the top-level of the DAG combiner loop to avoid it being
10416 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10419 // Cannot simplify select with vector condition
10420 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10422 // If this is a select from two identical things, try to pull the operation
10423 // through the select.
10424 if (LHS.getOpcode() != RHS.getOpcode() ||
10425 !LHS.hasOneUse() || !RHS.hasOneUse())
10428 // If this is a load and the token chain is identical, replace the select
10429 // of two loads with a load through a select of the address to load from.
10430 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10431 // constants have been dropped into the constant pool.
10432 if (LHS.getOpcode() == ISD::LOAD) {
10433 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10434 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10436 // Token chains must be identical.
10437 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10438 // Do not let this transformation reduce the number of volatile loads.
10439 LLD->isVolatile() || RLD->isVolatile() ||
10440 // If this is an EXTLOAD, the VT's must match.
10441 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10442 // If this is an EXTLOAD, the kind of extension must match.
10443 (LLD->getExtensionType() != RLD->getExtensionType() &&
10444 // The only exception is if one of the extensions is anyext.
10445 LLD->getExtensionType() != ISD::EXTLOAD &&
10446 RLD->getExtensionType() != ISD::EXTLOAD) ||
10447 // FIXME: this discards src value information. This is
10448 // over-conservative. It would be beneficial to be able to remember
10449 // both potential memory locations. Since we are discarding
10450 // src value info, don't do the transformation if the memory
10451 // locations are not in the default address space.
10452 LLD->getPointerInfo().getAddrSpace() != 0 ||
10453 RLD->getPointerInfo().getAddrSpace() != 0 ||
10454 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10455 LLD->getBasePtr().getValueType()))
10458 // Check that the select condition doesn't reach either load. If so,
10459 // folding this will induce a cycle into the DAG. If not, this is safe to
10460 // xform, so create a select of the addresses.
10462 if (TheSelect->getOpcode() == ISD::SELECT) {
10463 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10464 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10465 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10467 // The loads must not depend on one another.
10468 if (LLD->isPredecessorOf(RLD) ||
10469 RLD->isPredecessorOf(LLD))
10471 Addr = DAG.getSelect(SDLoc(TheSelect),
10472 LLD->getBasePtr().getValueType(),
10473 TheSelect->getOperand(0), LLD->getBasePtr(),
10474 RLD->getBasePtr());
10475 } else { // Otherwise SELECT_CC
10476 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10477 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10479 if ((LLD->hasAnyUseOfValue(1) &&
10480 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10481 (RLD->hasAnyUseOfValue(1) &&
10482 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10485 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10486 LLD->getBasePtr().getValueType(),
10487 TheSelect->getOperand(0),
10488 TheSelect->getOperand(1),
10489 LLD->getBasePtr(), RLD->getBasePtr(),
10490 TheSelect->getOperand(4));
10494 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10495 Load = DAG.getLoad(TheSelect->getValueType(0),
10497 // FIXME: Discards pointer and TBAA info.
10498 LLD->getChain(), Addr, MachinePointerInfo(),
10499 LLD->isVolatile(), LLD->isNonTemporal(),
10500 LLD->isInvariant(), LLD->getAlignment());
10502 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10503 RLD->getExtensionType() : LLD->getExtensionType(),
10505 TheSelect->getValueType(0),
10506 // FIXME: Discards pointer and TBAA info.
10507 LLD->getChain(), Addr, MachinePointerInfo(),
10508 LLD->getMemoryVT(), LLD->isVolatile(),
10509 LLD->isNonTemporal(), LLD->getAlignment());
10512 // Users of the select now use the result of the load.
10513 CombineTo(TheSelect, Load);
10515 // Users of the old loads now use the new load's chain. We know the
10516 // old-load value is dead now.
10517 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10518 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10525 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10526 /// where 'cond' is the comparison specified by CC.
10527 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10528 SDValue N2, SDValue N3,
10529 ISD::CondCode CC, bool NotExtCompare) {
10530 // (x ? y : y) -> y.
10531 if (N2 == N3) return N2;
10533 EVT VT = N2.getValueType();
10534 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10535 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10536 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10538 // Determine if the condition we're dealing with is constant
10539 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10540 N0, N1, CC, DL, false);
10541 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10542 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10544 // fold select_cc true, x, y -> x
10545 if (SCCC && !SCCC->isNullValue())
10547 // fold select_cc false, x, y -> y
10548 if (SCCC && SCCC->isNullValue())
10551 // Check to see if we can simplify the select into an fabs node
10552 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10553 // Allow either -0.0 or 0.0
10554 if (CFP->getValueAPF().isZero()) {
10555 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10556 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10557 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10558 N2 == N3.getOperand(0))
10559 return DAG.getNode(ISD::FABS, DL, VT, N0);
10561 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10562 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10563 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10564 N2.getOperand(0) == N3)
10565 return DAG.getNode(ISD::FABS, DL, VT, N3);
10569 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10570 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10571 // in it. This is a win when the constant is not otherwise available because
10572 // it replaces two constant pool loads with one. We only do this if the FP
10573 // type is known to be legal, because if it isn't, then we are before legalize
10574 // types an we want the other legalization to happen first (e.g. to avoid
10575 // messing with soft float) and if the ConstantFP is not legal, because if
10576 // it is legal, we may not need to store the FP constant in a constant pool.
10577 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10578 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10579 if (TLI.isTypeLegal(N2.getValueType()) &&
10580 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10581 TargetLowering::Legal) &&
10582 // If both constants have multiple uses, then we won't need to do an
10583 // extra load, they are likely around in registers for other users.
10584 (TV->hasOneUse() || FV->hasOneUse())) {
10585 Constant *Elts[] = {
10586 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10587 const_cast<ConstantFP*>(TV->getConstantFPValue())
10589 Type *FPTy = Elts[0]->getType();
10590 const DataLayout &TD = *TLI.getDataLayout();
10592 // Create a ConstantArray of the two constants.
10593 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10594 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10595 TD.getPrefTypeAlignment(FPTy));
10596 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10598 // Get the offsets to the 0 and 1 element of the array so that we can
10599 // select between them.
10600 SDValue Zero = DAG.getIntPtrConstant(0);
10601 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10602 SDValue One = DAG.getIntPtrConstant(EltSize);
10604 SDValue Cond = DAG.getSetCC(DL,
10605 getSetCCResultType(N0.getValueType()),
10607 AddToWorkList(Cond.getNode());
10608 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10610 AddToWorkList(CstOffset.getNode());
10611 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10613 AddToWorkList(CPIdx.getNode());
10614 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10615 MachinePointerInfo::getConstantPool(), false,
10616 false, false, Alignment);
10621 // Check to see if we can perform the "gzip trick", transforming
10622 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10623 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10624 (N1C->isNullValue() || // (a < 0) ? b : 0
10625 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10626 EVT XType = N0.getValueType();
10627 EVT AType = N2.getValueType();
10628 if (XType.bitsGE(AType)) {
10629 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10630 // single-bit constant.
10631 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10632 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10633 ShCtV = XType.getSizeInBits()-ShCtV-1;
10634 SDValue ShCt = DAG.getConstant(ShCtV,
10635 getShiftAmountTy(N0.getValueType()));
10636 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10638 AddToWorkList(Shift.getNode());
10640 if (XType.bitsGT(AType)) {
10641 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10642 AddToWorkList(Shift.getNode());
10645 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10648 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10650 DAG.getConstant(XType.getSizeInBits()-1,
10651 getShiftAmountTy(N0.getValueType())));
10652 AddToWorkList(Shift.getNode());
10654 if (XType.bitsGT(AType)) {
10655 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10656 AddToWorkList(Shift.getNode());
10659 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10663 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10664 // where y is has a single bit set.
10665 // A plaintext description would be, we can turn the SELECT_CC into an AND
10666 // when the condition can be materialized as an all-ones register. Any
10667 // single bit-test can be materialized as an all-ones register with
10668 // shift-left and shift-right-arith.
10669 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10670 N0->getValueType(0) == VT &&
10671 N1C && N1C->isNullValue() &&
10672 N2C && N2C->isNullValue()) {
10673 SDValue AndLHS = N0->getOperand(0);
10674 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10675 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10676 // Shift the tested bit over the sign bit.
10677 APInt AndMask = ConstAndRHS->getAPIntValue();
10679 DAG.getConstant(AndMask.countLeadingZeros(),
10680 getShiftAmountTy(AndLHS.getValueType()));
10681 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10683 // Now arithmetic right shift it all the way over, so the result is either
10684 // all-ones, or zero.
10686 DAG.getConstant(AndMask.getBitWidth()-1,
10687 getShiftAmountTy(Shl.getValueType()));
10688 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10690 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10694 // fold select C, 16, 0 -> shl C, 4
10695 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10696 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10697 TargetLowering::ZeroOrOneBooleanContent) {
10699 // If the caller doesn't want us to simplify this into a zext of a compare,
10701 if (NotExtCompare && N2C->getAPIntValue() == 1)
10704 // Get a SetCC of the condition
10705 // NOTE: Don't create a SETCC if it's not legal on this target.
10706 if (!LegalOperations ||
10707 TLI.isOperationLegal(ISD::SETCC,
10708 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10710 // cast from setcc result type to select result type
10712 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10714 if (N2.getValueType().bitsLT(SCC.getValueType()))
10715 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10716 N2.getValueType());
10718 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10719 N2.getValueType(), SCC);
10721 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10722 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10723 N2.getValueType(), SCC);
10726 AddToWorkList(SCC.getNode());
10727 AddToWorkList(Temp.getNode());
10729 if (N2C->getAPIntValue() == 1)
10732 // shl setcc result by log2 n2c
10733 return DAG.getNode(
10734 ISD::SHL, DL, N2.getValueType(), Temp,
10735 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10736 getShiftAmountTy(Temp.getValueType())));
10740 // Check to see if this is the equivalent of setcc
10741 // FIXME: Turn all of these into setcc if setcc if setcc is legal
10742 // otherwise, go ahead with the folds.
10743 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10744 EVT XType = N0.getValueType();
10745 if (!LegalOperations ||
10746 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10747 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10748 if (Res.getValueType() != VT)
10749 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10753 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10754 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10755 (!LegalOperations ||
10756 TLI.isOperationLegal(ISD::CTLZ, XType))) {
10757 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10758 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10759 DAG.getConstant(Log2_32(XType.getSizeInBits()),
10760 getShiftAmountTy(Ctlz.getValueType())));
10762 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10763 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10764 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10765 XType, DAG.getConstant(0, XType), N0);
10766 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10767 return DAG.getNode(ISD::SRL, DL, XType,
10768 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10769 DAG.getConstant(XType.getSizeInBits()-1,
10770 getShiftAmountTy(XType)));
10772 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10773 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10774 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10775 DAG.getConstant(XType.getSizeInBits()-1,
10776 getShiftAmountTy(N0.getValueType())));
10777 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10781 // Check to see if this is an integer abs.
10782 // select_cc setg[te] X, 0, X, -X ->
10783 // select_cc setgt X, -1, X, -X ->
10784 // select_cc setl[te] X, 0, -X, X ->
10785 // select_cc setlt X, 1, -X, X ->
10786 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10788 ConstantSDNode *SubC = NULL;
10789 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10790 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10791 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10792 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10793 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10794 (N1C->isOne() && CC == ISD::SETLT)) &&
10795 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10796 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10798 EVT XType = N0.getValueType();
10799 if (SubC && SubC->isNullValue() && XType.isInteger()) {
10800 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10802 DAG.getConstant(XType.getSizeInBits()-1,
10803 getShiftAmountTy(N0.getValueType())));
10804 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10806 AddToWorkList(Shift.getNode());
10807 AddToWorkList(Add.getNode());
10808 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10815 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10816 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10817 SDValue N1, ISD::CondCode Cond,
10818 SDLoc DL, bool foldBooleans) {
10819 TargetLowering::DAGCombinerInfo
10820 DagCombineInfo(DAG, Level, false, this);
10821 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10824 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10825 /// return a DAG expression to select that will generate the same value by
10826 /// multiplying by a magic number. See:
10827 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10828 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10829 std::vector<SDNode*> Built;
10830 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10832 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10834 AddToWorkList(*ii);
10838 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10839 /// return a DAG expression to select that will generate the same value by
10840 /// multiplying by a magic number. See:
10841 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10842 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10843 std::vector<SDNode*> Built;
10844 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10846 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10848 AddToWorkList(*ii);
10852 /// FindBaseOffset - Return true if base is a frame index, which is known not
10853 // to alias with anything but itself. Provides base object and offset as
10855 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10856 const GlobalValue *&GV, const void *&CV) {
10857 // Assume it is a primitive operation.
10858 Base = Ptr; Offset = 0; GV = 0; CV = 0;
10860 // If it's an adding a simple constant then integrate the offset.
10861 if (Base.getOpcode() == ISD::ADD) {
10862 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10863 Base = Base.getOperand(0);
10864 Offset += C->getZExtValue();
10868 // Return the underlying GlobalValue, and update the Offset. Return false
10869 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10870 // by multiple nodes with different offsets.
10871 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10872 GV = G->getGlobal();
10873 Offset += G->getOffset();
10877 // Return the underlying Constant value, and update the Offset. Return false
10878 // for ConstantSDNodes since the same constant pool entry may be represented
10879 // by multiple nodes with different offsets.
10880 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10881 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10882 : (const void *)C->getConstVal();
10883 Offset += C->getOffset();
10886 // If it's any of the following then it can't alias with anything but itself.
10887 return isa<FrameIndexSDNode>(Base);
10890 /// isAlias - Return true if there is any possibility that the two addresses
10892 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
10893 const Value *SrcValue1, int SrcValueOffset1,
10894 unsigned SrcValueAlign1,
10895 const MDNode *TBAAInfo1,
10896 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
10897 const Value *SrcValue2, int SrcValueOffset2,
10898 unsigned SrcValueAlign2,
10899 const MDNode *TBAAInfo2) const {
10900 // If they are the same then they must be aliases.
10901 if (Ptr1 == Ptr2) return true;
10903 // If they are both volatile then they cannot be reordered.
10904 if (IsVolatile1 && IsVolatile2) return true;
10906 // Gather base node and offset information.
10907 SDValue Base1, Base2;
10908 int64_t Offset1, Offset2;
10909 const GlobalValue *GV1, *GV2;
10910 const void *CV1, *CV2;
10911 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10912 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10914 // If they have a same base address then check to see if they overlap.
10915 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10916 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10918 // It is possible for different frame indices to alias each other, mostly
10919 // when tail call optimization reuses return address slots for arguments.
10920 // To catch this case, look up the actual index of frame indices to compute
10921 // the real alias relationship.
10922 if (isFrameIndex1 && isFrameIndex2) {
10923 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10924 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10925 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10926 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10929 // Otherwise, if we know what the bases are, and they aren't identical, then
10930 // we know they cannot alias.
10931 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10934 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10935 // compared to the size and offset of the access, we may be able to prove they
10936 // do not alias. This check is conservative for now to catch cases created by
10937 // splitting vector types.
10938 if ((SrcValueAlign1 == SrcValueAlign2) &&
10939 (SrcValueOffset1 != SrcValueOffset2) &&
10940 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10941 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10942 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10944 // There is no overlap between these relatively aligned accesses of similar
10945 // size, return no alias.
10946 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10950 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10951 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10952 if (UseAA && SrcValue1 && SrcValue2) {
10953 // Use alias analysis information.
10954 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10955 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10956 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10957 AliasAnalysis::AliasResult AAResult =
10958 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10959 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10960 if (AAResult == AliasAnalysis::NoAlias)
10964 // Otherwise we have to assume they alias.
10968 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10969 SDValue Ptr0, Ptr1;
10970 int64_t Size0, Size1;
10971 bool IsVolatile0, IsVolatile1;
10972 const Value *SrcValue0, *SrcValue1;
10973 int SrcValueOffset0, SrcValueOffset1;
10974 unsigned SrcValueAlign0, SrcValueAlign1;
10975 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10976 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
10977 SrcValueAlign0, SrcTBAAInfo0);
10978 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
10979 SrcValueAlign1, SrcTBAAInfo1);
10980 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
10981 SrcValueAlign0, SrcTBAAInfo0,
10982 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
10983 SrcValueAlign1, SrcTBAAInfo1);
10986 /// FindAliasInfo - Extracts the relevant alias information from the memory
10987 /// node. Returns true if the operand was a nonvolatile load.
10988 bool DAGCombiner::FindAliasInfo(SDNode *N,
10989 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
10990 const Value *&SrcValue,
10991 int &SrcValueOffset,
10992 unsigned &SrcValueAlign,
10993 const MDNode *&TBAAInfo) const {
10994 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10996 Ptr = LS->getBasePtr();
10997 Size = LS->getMemoryVT().getSizeInBits() >> 3;
10998 IsVolatile = LS->isVolatile();
10999 SrcValue = LS->getSrcValue();
11000 SrcValueOffset = LS->getSrcValueOffset();
11001 SrcValueAlign = LS->getOriginalAlignment();
11002 TBAAInfo = LS->getTBAAInfo();
11003 return isa<LoadSDNode>(LS) && !IsVolatile;
11006 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11007 /// looking for aliasing nodes and adding them to the Aliases vector.
11008 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11009 SmallVectorImpl<SDValue> &Aliases) {
11010 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11011 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11013 // Get alias information for node.
11017 const Value *SrcValue;
11018 int SrcValueOffset;
11019 unsigned SrcValueAlign;
11020 const MDNode *SrcTBAAInfo;
11021 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11022 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11025 Chains.push_back(OriginalChain);
11026 unsigned Depth = 0;
11028 // Look at each chain and determine if it is an alias. If so, add it to the
11029 // aliases list. If not, then continue up the chain looking for the next
11031 while (!Chains.empty()) {
11032 SDValue Chain = Chains.back();
11035 // For TokenFactor nodes, look at each operand and only continue up the
11036 // chain until we find two aliases. If we've seen two aliases, assume we'll
11037 // find more and revert to original chain since the xform is unlikely to be
11040 // FIXME: The depth check could be made to return the last non-aliasing
11041 // chain we found before we hit a tokenfactor rather than the original
11043 if (Depth > 6 || Aliases.size() == 2) {
11045 Aliases.push_back(OriginalChain);
11049 // Don't bother if we've been before.
11050 if (!Visited.insert(Chain.getNode()))
11053 switch (Chain.getOpcode()) {
11054 case ISD::EntryToken:
11055 // Entry token is ideal chain operand, but handled in FindBetterChain.
11060 // Get alias information for Chain.
11064 const Value *OpSrcValue;
11065 int OpSrcValueOffset;
11066 unsigned OpSrcValueAlign;
11067 const MDNode *OpSrcTBAAInfo;
11068 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11069 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11073 // If chain is alias then stop here.
11074 if (!(IsLoad && IsOpLoad) &&
11075 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11076 SrcValueAlign, SrcTBAAInfo,
11077 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11078 OpSrcValueAlign, OpSrcTBAAInfo)) {
11079 Aliases.push_back(Chain);
11081 // Look further up the chain.
11082 Chains.push_back(Chain.getOperand(0));
11088 case ISD::TokenFactor:
11089 // We have to check each of the operands of the token factor for "small"
11090 // token factors, so we queue them up. Adding the operands to the queue
11091 // (stack) in reverse order maintains the original order and increases the
11092 // likelihood that getNode will find a matching token factor (CSE.)
11093 if (Chain.getNumOperands() > 16) {
11094 Aliases.push_back(Chain);
11097 for (unsigned n = Chain.getNumOperands(); n;)
11098 Chains.push_back(Chain.getOperand(--n));
11103 // For all other instructions we will just have to take what we can get.
11104 Aliases.push_back(Chain);
11110 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11111 /// for a better chain (aliasing node.)
11112 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11113 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11115 // Accumulate all the aliases to this node.
11116 GatherAllAliases(N, OldChain, Aliases);
11118 // If no operands then chain to entry token.
11119 if (Aliases.size() == 0)
11120 return DAG.getEntryNode();
11122 // If a single operand then chain to it. We don't need to revisit it.
11123 if (Aliases.size() == 1)
11126 // Construct a custom tailored token factor.
11127 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11128 &Aliases[0], Aliases.size());
11131 // SelectionDAG::Combine - This is the entry point for the file.
11133 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11134 CodeGenOpt::Level OptLevel) {
11135 /// run - This is the main entry point to this class.
11137 DAGCombiner(*this, AA, OptLevel).Run(Level);