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 // \brief Returns the SDNode if it is a constant BuildVector or constant int.
611 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
612 if (isa<ConstantSDNode>(N))
614 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
615 if(BV && BV->isConstant())
620 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
621 SDValue N0, SDValue N1) {
622 EVT VT = N0.getValueType();
623 if (N0.getOpcode() == Opc) {
624 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
625 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
626 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
627 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
628 if (!OpNode.getNode())
630 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
632 if (N0.hasOneUse()) {
633 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
635 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
636 if (!OpNode.getNode())
638 AddToWorkList(OpNode.getNode());
639 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
644 if (N1.getOpcode() == Opc) {
645 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
646 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
647 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
648 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
649 if (!OpNode.getNode())
651 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
653 if (N1.hasOneUse()) {
654 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
656 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
657 if (!OpNode.getNode())
659 AddToWorkList(OpNode.getNode());
660 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
668 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
670 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
672 DEBUG(dbgs() << "\nReplacing.1 ";
674 dbgs() << "\nWith: ";
675 To[0].getNode()->dump(&DAG);
676 dbgs() << " and " << NumTo-1 << " other values\n";
677 for (unsigned i = 0, e = NumTo; i != e; ++i)
678 assert((!To[i].getNode() ||
679 N->getValueType(i) == To[i].getValueType()) &&
680 "Cannot combine value to value of different type!"));
681 WorkListRemover DeadNodes(*this);
682 DAG.ReplaceAllUsesWith(N, To);
684 // Push the new nodes and any users onto the worklist
685 for (unsigned i = 0, e = NumTo; i != e; ++i) {
686 if (To[i].getNode()) {
687 AddToWorkList(To[i].getNode());
688 AddUsersToWorkList(To[i].getNode());
693 // Finally, if the node is now dead, remove it from the graph. The node
694 // may not be dead if the replacement process recursively simplified to
695 // something else needing this node.
696 if (N->use_empty()) {
697 // Nodes can be reintroduced into the worklist. Make sure we do not
698 // process a node that has been replaced.
699 removeFromWorkList(N);
701 // Finally, since the node is now dead, remove it from the graph.
704 return SDValue(N, 0);
708 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
709 // Replace all uses. If any nodes become isomorphic to other nodes and
710 // are deleted, make sure to remove them from our worklist.
711 WorkListRemover DeadNodes(*this);
712 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
714 // Push the new node and any (possibly new) users onto the worklist.
715 AddToWorkList(TLO.New.getNode());
716 AddUsersToWorkList(TLO.New.getNode());
718 // Finally, if the node is now dead, remove it from the graph. The node
719 // may not be dead if the replacement process recursively simplified to
720 // something else needing this node.
721 if (TLO.Old.getNode()->use_empty()) {
722 removeFromWorkList(TLO.Old.getNode());
724 // If the operands of this node are only used by the node, they will now
725 // be dead. Make sure to visit them first to delete dead nodes early.
726 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
727 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
728 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
730 DAG.DeleteNode(TLO.Old.getNode());
734 /// SimplifyDemandedBits - Check the specified integer node value to see if
735 /// it can be simplified or if things it uses can be simplified by bit
736 /// propagation. If so, return true.
737 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
738 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
739 APInt KnownZero, KnownOne;
740 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
744 AddToWorkList(Op.getNode());
746 // Replace the old value with the new one.
748 DEBUG(dbgs() << "\nReplacing.2 ";
749 TLO.Old.getNode()->dump(&DAG);
750 dbgs() << "\nWith: ";
751 TLO.New.getNode()->dump(&DAG);
754 CommitTargetLoweringOpt(TLO);
758 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
760 EVT VT = Load->getValueType(0);
761 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
763 DEBUG(dbgs() << "\nReplacing.9 ";
765 dbgs() << "\nWith: ";
766 Trunc.getNode()->dump(&DAG);
768 WorkListRemover DeadNodes(*this);
769 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
770 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
771 removeFromWorkList(Load);
772 DAG.DeleteNode(Load);
773 AddToWorkList(Trunc.getNode());
776 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
779 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
780 EVT MemVT = LD->getMemoryVT();
781 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
782 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
784 : LD->getExtensionType();
786 return DAG.getExtLoad(ExtType, dl, PVT,
787 LD->getChain(), LD->getBasePtr(),
788 MemVT, LD->getMemOperand());
791 unsigned Opc = Op.getOpcode();
794 case ISD::AssertSext:
795 return DAG.getNode(ISD::AssertSext, dl, PVT,
796 SExtPromoteOperand(Op.getOperand(0), PVT),
798 case ISD::AssertZext:
799 return DAG.getNode(ISD::AssertZext, dl, PVT,
800 ZExtPromoteOperand(Op.getOperand(0), PVT),
802 case ISD::Constant: {
804 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
805 return DAG.getNode(ExtOpc, dl, PVT, Op);
809 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
811 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
814 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
815 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
817 EVT OldVT = Op.getValueType();
819 bool Replace = false;
820 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
821 if (NewOp.getNode() == 0)
823 AddToWorkList(NewOp.getNode());
826 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
827 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
828 DAG.getValueType(OldVT));
831 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
832 EVT OldVT = Op.getValueType();
834 bool Replace = false;
835 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
836 if (NewOp.getNode() == 0)
838 AddToWorkList(NewOp.getNode());
841 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
842 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
845 /// PromoteIntBinOp - Promote the specified integer binary operation if the
846 /// target indicates it is beneficial. e.g. On x86, it's usually better to
847 /// promote i16 operations to i32 since i16 instructions are longer.
848 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
849 if (!LegalOperations)
852 EVT VT = Op.getValueType();
853 if (VT.isVector() || !VT.isInteger())
856 // If operation type is 'undesirable', e.g. i16 on x86, consider
858 unsigned Opc = Op.getOpcode();
859 if (TLI.isTypeDesirableForOp(Opc, VT))
863 // Consult target whether it is a good idea to promote this operation and
864 // what's the right type to promote it to.
865 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
866 assert(PVT != VT && "Don't know what type to promote to!");
868 bool Replace0 = false;
869 SDValue N0 = Op.getOperand(0);
870 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
871 if (NN0.getNode() == 0)
874 bool Replace1 = false;
875 SDValue N1 = Op.getOperand(1);
880 NN1 = PromoteOperand(N1, PVT, Replace1);
881 if (NN1.getNode() == 0)
885 AddToWorkList(NN0.getNode());
887 AddToWorkList(NN1.getNode());
890 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
892 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
894 DEBUG(dbgs() << "\nPromoting ";
895 Op.getNode()->dump(&DAG));
897 return DAG.getNode(ISD::TRUNCATE, dl, VT,
898 DAG.getNode(Opc, dl, PVT, NN0, NN1));
903 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
904 /// target indicates it is beneficial. e.g. On x86, it's usually better to
905 /// promote i16 operations to i32 since i16 instructions are longer.
906 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
907 if (!LegalOperations)
910 EVT VT = Op.getValueType();
911 if (VT.isVector() || !VT.isInteger())
914 // If operation type is 'undesirable', e.g. i16 on x86, consider
916 unsigned Opc = Op.getOpcode();
917 if (TLI.isTypeDesirableForOp(Opc, VT))
921 // Consult target whether it is a good idea to promote this operation and
922 // what's the right type to promote it to.
923 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
924 assert(PVT != VT && "Don't know what type to promote to!");
926 bool Replace = false;
927 SDValue N0 = Op.getOperand(0);
929 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
930 else if (Opc == ISD::SRL)
931 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
933 N0 = PromoteOperand(N0, PVT, Replace);
934 if (N0.getNode() == 0)
937 AddToWorkList(N0.getNode());
939 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
941 DEBUG(dbgs() << "\nPromoting ";
942 Op.getNode()->dump(&DAG));
944 return DAG.getNode(ISD::TRUNCATE, dl, VT,
945 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
950 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
951 if (!LegalOperations)
954 EVT VT = Op.getValueType();
955 if (VT.isVector() || !VT.isInteger())
958 // If operation type is 'undesirable', e.g. i16 on x86, consider
960 unsigned Opc = Op.getOpcode();
961 if (TLI.isTypeDesirableForOp(Opc, VT))
965 // Consult target whether it is a good idea to promote this operation and
966 // what's the right type to promote it to.
967 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
968 assert(PVT != VT && "Don't know what type to promote to!");
969 // fold (aext (aext x)) -> (aext x)
970 // fold (aext (zext x)) -> (zext x)
971 // fold (aext (sext x)) -> (sext x)
972 DEBUG(dbgs() << "\nPromoting ";
973 Op.getNode()->dump(&DAG));
974 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
979 bool DAGCombiner::PromoteLoad(SDValue Op) {
980 if (!LegalOperations)
983 EVT VT = Op.getValueType();
984 if (VT.isVector() || !VT.isInteger())
987 // If operation type is 'undesirable', e.g. i16 on x86, consider
989 unsigned Opc = Op.getOpcode();
990 if (TLI.isTypeDesirableForOp(Opc, VT))
994 // Consult target whether it is a good idea to promote this operation and
995 // what's the right type to promote it to.
996 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
997 assert(PVT != VT && "Don't know what type to promote to!");
1000 SDNode *N = Op.getNode();
1001 LoadSDNode *LD = cast<LoadSDNode>(N);
1002 EVT MemVT = LD->getMemoryVT();
1003 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1004 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1006 : LD->getExtensionType();
1007 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1008 LD->getChain(), LD->getBasePtr(),
1009 MemVT, LD->getMemOperand());
1010 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1012 DEBUG(dbgs() << "\nPromoting ";
1015 Result.getNode()->dump(&DAG);
1017 WorkListRemover DeadNodes(*this);
1018 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1019 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1020 removeFromWorkList(N);
1022 AddToWorkList(Result.getNode());
1029 //===----------------------------------------------------------------------===//
1030 // Main DAG Combiner implementation
1031 //===----------------------------------------------------------------------===//
1033 void DAGCombiner::Run(CombineLevel AtLevel) {
1034 // set the instance variables, so that the various visit routines may use it.
1036 LegalOperations = Level >= AfterLegalizeVectorOps;
1037 LegalTypes = Level >= AfterLegalizeTypes;
1039 // Add all the dag nodes to the worklist.
1040 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1041 E = DAG.allnodes_end(); I != E; ++I)
1044 // Create a dummy node (which is not added to allnodes), that adds a reference
1045 // to the root node, preventing it from being deleted, and tracking any
1046 // changes of the root.
1047 HandleSDNode Dummy(DAG.getRoot());
1049 // The root of the dag may dangle to deleted nodes until the dag combiner is
1050 // done. Set it to null to avoid confusion.
1051 DAG.setRoot(SDValue());
1053 // while the worklist isn't empty, find a node and
1054 // try and combine it.
1055 while (!WorkListContents.empty()) {
1057 // The WorkListOrder holds the SDNodes in order, but it may contain
1059 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1060 // worklist *should* contain, and check the node we want to visit is should
1061 // actually be visited.
1063 N = WorkListOrder.pop_back_val();
1064 } while (!WorkListContents.erase(N));
1066 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1067 // N is deleted from the DAG, since they too may now be dead or may have a
1068 // reduced number of uses, allowing other xforms.
1069 if (N->use_empty() && N != &Dummy) {
1070 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1071 AddToWorkList(N->getOperand(i).getNode());
1077 SDValue RV = combine(N);
1079 if (RV.getNode() == 0)
1084 // If we get back the same node we passed in, rather than a new node or
1085 // zero, we know that the node must have defined multiple values and
1086 // CombineTo was used. Since CombineTo takes care of the worklist
1087 // mechanics for us, we have no work to do in this case.
1088 if (RV.getNode() == N)
1091 assert(N->getOpcode() != ISD::DELETED_NODE &&
1092 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1093 "Node was deleted but visit returned new node!");
1095 DEBUG(dbgs() << "\nReplacing.3 ";
1097 dbgs() << "\nWith: ";
1098 RV.getNode()->dump(&DAG);
1101 // Transfer debug value.
1102 DAG.TransferDbgValues(SDValue(N, 0), RV);
1103 WorkListRemover DeadNodes(*this);
1104 if (N->getNumValues() == RV.getNode()->getNumValues())
1105 DAG.ReplaceAllUsesWith(N, RV.getNode());
1107 assert(N->getValueType(0) == RV.getValueType() &&
1108 N->getNumValues() == 1 && "Type mismatch");
1110 DAG.ReplaceAllUsesWith(N, &OpV);
1113 // Push the new node and any users onto the worklist
1114 AddToWorkList(RV.getNode());
1115 AddUsersToWorkList(RV.getNode());
1117 // Add any uses of the old node to the worklist in case this node is the
1118 // last one that uses them. They may become dead after this node is
1120 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1121 AddToWorkList(N->getOperand(i).getNode());
1123 // Finally, if the node is now dead, remove it from the graph. The node
1124 // may not be dead if the replacement process recursively simplified to
1125 // something else needing this node.
1126 if (N->use_empty()) {
1127 // Nodes can be reintroduced into the worklist. Make sure we do not
1128 // process a node that has been replaced.
1129 removeFromWorkList(N);
1131 // Finally, since the node is now dead, remove it from the graph.
1136 // If the root changed (e.g. it was a dead load, update the root).
1137 DAG.setRoot(Dummy.getValue());
1138 DAG.RemoveDeadNodes();
1141 SDValue DAGCombiner::visit(SDNode *N) {
1142 switch (N->getOpcode()) {
1144 case ISD::TokenFactor: return visitTokenFactor(N);
1145 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1146 case ISD::ADD: return visitADD(N);
1147 case ISD::SUB: return visitSUB(N);
1148 case ISD::ADDC: return visitADDC(N);
1149 case ISD::SUBC: return visitSUBC(N);
1150 case ISD::ADDE: return visitADDE(N);
1151 case ISD::SUBE: return visitSUBE(N);
1152 case ISD::MUL: return visitMUL(N);
1153 case ISD::SDIV: return visitSDIV(N);
1154 case ISD::UDIV: return visitUDIV(N);
1155 case ISD::SREM: return visitSREM(N);
1156 case ISD::UREM: return visitUREM(N);
1157 case ISD::MULHU: return visitMULHU(N);
1158 case ISD::MULHS: return visitMULHS(N);
1159 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1160 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1161 case ISD::SMULO: return visitSMULO(N);
1162 case ISD::UMULO: return visitUMULO(N);
1163 case ISD::SDIVREM: return visitSDIVREM(N);
1164 case ISD::UDIVREM: return visitUDIVREM(N);
1165 case ISD::AND: return visitAND(N);
1166 case ISD::OR: return visitOR(N);
1167 case ISD::XOR: return visitXOR(N);
1168 case ISD::SHL: return visitSHL(N);
1169 case ISD::SRA: return visitSRA(N);
1170 case ISD::SRL: return visitSRL(N);
1171 case ISD::CTLZ: return visitCTLZ(N);
1172 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1173 case ISD::CTTZ: return visitCTTZ(N);
1174 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1175 case ISD::CTPOP: return visitCTPOP(N);
1176 case ISD::SELECT: return visitSELECT(N);
1177 case ISD::VSELECT: return visitVSELECT(N);
1178 case ISD::SELECT_CC: return visitSELECT_CC(N);
1179 case ISD::SETCC: return visitSETCC(N);
1180 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1181 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1182 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1183 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1184 case ISD::TRUNCATE: return visitTRUNCATE(N);
1185 case ISD::BITCAST: return visitBITCAST(N);
1186 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1187 case ISD::FADD: return visitFADD(N);
1188 case ISD::FSUB: return visitFSUB(N);
1189 case ISD::FMUL: return visitFMUL(N);
1190 case ISD::FMA: return visitFMA(N);
1191 case ISD::FDIV: return visitFDIV(N);
1192 case ISD::FREM: return visitFREM(N);
1193 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1194 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1195 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1196 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1197 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1198 case ISD::FP_ROUND: return visitFP_ROUND(N);
1199 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1200 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1201 case ISD::FNEG: return visitFNEG(N);
1202 case ISD::FABS: return visitFABS(N);
1203 case ISD::FFLOOR: return visitFFLOOR(N);
1204 case ISD::FCEIL: return visitFCEIL(N);
1205 case ISD::FTRUNC: return visitFTRUNC(N);
1206 case ISD::BRCOND: return visitBRCOND(N);
1207 case ISD::BR_CC: return visitBR_CC(N);
1208 case ISD::LOAD: return visitLOAD(N);
1209 case ISD::STORE: return visitSTORE(N);
1210 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1211 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1212 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1213 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1214 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1215 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1220 SDValue DAGCombiner::combine(SDNode *N) {
1221 SDValue RV = visit(N);
1223 // If nothing happened, try a target-specific DAG combine.
1224 if (RV.getNode() == 0) {
1225 assert(N->getOpcode() != ISD::DELETED_NODE &&
1226 "Node was deleted but visit returned NULL!");
1228 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1229 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1231 // Expose the DAG combiner to the target combiner impls.
1232 TargetLowering::DAGCombinerInfo
1233 DagCombineInfo(DAG, Level, false, this);
1235 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1239 // If nothing happened still, try promoting the operation.
1240 if (RV.getNode() == 0) {
1241 switch (N->getOpcode()) {
1249 RV = PromoteIntBinOp(SDValue(N, 0));
1254 RV = PromoteIntShiftOp(SDValue(N, 0));
1256 case ISD::SIGN_EXTEND:
1257 case ISD::ZERO_EXTEND:
1258 case ISD::ANY_EXTEND:
1259 RV = PromoteExtend(SDValue(N, 0));
1262 if (PromoteLoad(SDValue(N, 0)))
1268 // If N is a commutative binary node, try commuting it to enable more
1270 if (RV.getNode() == 0 &&
1271 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1272 N->getNumValues() == 1) {
1273 SDValue N0 = N->getOperand(0);
1274 SDValue N1 = N->getOperand(1);
1276 // Constant operands are canonicalized to RHS.
1277 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1278 SDValue Ops[] = { N1, N0 };
1279 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1282 return SDValue(CSENode, 0);
1289 /// getInputChainForNode - Given a node, return its input chain if it has one,
1290 /// otherwise return a null sd operand.
1291 static SDValue getInputChainForNode(SDNode *N) {
1292 if (unsigned NumOps = N->getNumOperands()) {
1293 if (N->getOperand(0).getValueType() == MVT::Other)
1294 return N->getOperand(0);
1295 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1296 return N->getOperand(NumOps-1);
1297 for (unsigned i = 1; i < NumOps-1; ++i)
1298 if (N->getOperand(i).getValueType() == MVT::Other)
1299 return N->getOperand(i);
1304 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1305 // If N has two operands, where one has an input chain equal to the other,
1306 // the 'other' chain is redundant.
1307 if (N->getNumOperands() == 2) {
1308 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1309 return N->getOperand(0);
1310 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1311 return N->getOperand(1);
1314 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1315 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1316 SmallPtrSet<SDNode*, 16> SeenOps;
1317 bool Changed = false; // If we should replace this token factor.
1319 // Start out with this token factor.
1322 // Iterate through token factors. The TFs grows when new token factors are
1324 for (unsigned i = 0; i < TFs.size(); ++i) {
1325 SDNode *TF = TFs[i];
1327 // Check each of the operands.
1328 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1329 SDValue Op = TF->getOperand(i);
1331 switch (Op.getOpcode()) {
1332 case ISD::EntryToken:
1333 // Entry tokens don't need to be added to the list. They are
1338 case ISD::TokenFactor:
1339 if (Op.hasOneUse() &&
1340 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1341 // Queue up for processing.
1342 TFs.push_back(Op.getNode());
1343 // Clean up in case the token factor is removed.
1344 AddToWorkList(Op.getNode());
1351 // Only add if it isn't already in the list.
1352 if (SeenOps.insert(Op.getNode()))
1363 // If we've change things around then replace token factor.
1366 // The entry token is the only possible outcome.
1367 Result = DAG.getEntryNode();
1369 // New and improved token factor.
1370 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1371 MVT::Other, &Ops[0], Ops.size());
1374 // Don't add users to work list.
1375 return CombineTo(N, Result, false);
1381 /// MERGE_VALUES can always be eliminated.
1382 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1383 WorkListRemover DeadNodes(*this);
1384 // Replacing results may cause a different MERGE_VALUES to suddenly
1385 // be CSE'd with N, and carry its uses with it. Iterate until no
1386 // uses remain, to ensure that the node can be safely deleted.
1387 // First add the users of this node to the work list so that they
1388 // can be tried again once they have new operands.
1389 AddUsersToWorkList(N);
1391 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1392 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1393 } while (!N->use_empty());
1394 removeFromWorkList(N);
1396 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1400 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1401 SelectionDAG &DAG) {
1402 EVT VT = N0.getValueType();
1403 SDValue N00 = N0.getOperand(0);
1404 SDValue N01 = N0.getOperand(1);
1405 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1407 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1408 isa<ConstantSDNode>(N00.getOperand(1))) {
1409 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1410 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1411 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1412 N00.getOperand(0), N01),
1413 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1414 N00.getOperand(1), N01));
1415 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1421 SDValue DAGCombiner::visitADD(SDNode *N) {
1422 SDValue N0 = N->getOperand(0);
1423 SDValue N1 = N->getOperand(1);
1424 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1425 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1426 EVT VT = N0.getValueType();
1429 if (VT.isVector()) {
1430 SDValue FoldedVOp = SimplifyVBinOp(N);
1431 if (FoldedVOp.getNode()) return FoldedVOp;
1433 // fold (add x, 0) -> x, vector edition
1434 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1436 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1440 // fold (add x, undef) -> undef
1441 if (N0.getOpcode() == ISD::UNDEF)
1443 if (N1.getOpcode() == ISD::UNDEF)
1445 // fold (add c1, c2) -> c1+c2
1447 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1448 // canonicalize constant to RHS
1450 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1451 // fold (add x, 0) -> x
1452 if (N1C && N1C->isNullValue())
1454 // fold (add Sym, c) -> Sym+c
1455 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1456 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1457 GA->getOpcode() == ISD::GlobalAddress)
1458 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1460 (uint64_t)N1C->getSExtValue());
1461 // fold ((c1-A)+c2) -> (c1+c2)-A
1462 if (N1C && N0.getOpcode() == ISD::SUB)
1463 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1464 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1465 DAG.getConstant(N1C->getAPIntValue()+
1466 N0C->getAPIntValue(), VT),
1469 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1470 if (RADD.getNode() != 0)
1472 // fold ((0-A) + B) -> B-A
1473 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1474 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1475 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1476 // fold (A + (0-B)) -> A-B
1477 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1478 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1479 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1480 // fold (A+(B-A)) -> B
1481 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1482 return N1.getOperand(0);
1483 // fold ((B-A)+A) -> B
1484 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1485 return N0.getOperand(0);
1486 // fold (A+(B-(A+C))) to (B-C)
1487 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1488 N0 == N1.getOperand(1).getOperand(0))
1489 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1490 N1.getOperand(1).getOperand(1));
1491 // fold (A+(B-(C+A))) to (B-C)
1492 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1493 N0 == N1.getOperand(1).getOperand(1))
1494 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1495 N1.getOperand(1).getOperand(0));
1496 // fold (A+((B-A)+or-C)) to (B+or-C)
1497 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1498 N1.getOperand(0).getOpcode() == ISD::SUB &&
1499 N0 == N1.getOperand(0).getOperand(1))
1500 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1501 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1503 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1504 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1505 SDValue N00 = N0.getOperand(0);
1506 SDValue N01 = N0.getOperand(1);
1507 SDValue N10 = N1.getOperand(0);
1508 SDValue N11 = N1.getOperand(1);
1510 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1511 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1512 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1513 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1516 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1517 return SDValue(N, 0);
1519 // fold (a+b) -> (a|b) iff a and b share no bits.
1520 if (VT.isInteger() && !VT.isVector()) {
1521 APInt LHSZero, LHSOne;
1522 APInt RHSZero, RHSOne;
1523 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1525 if (LHSZero.getBoolValue()) {
1526 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1528 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1529 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1530 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1531 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1535 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1536 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1537 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1538 if (Result.getNode()) return Result;
1540 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1541 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1542 if (Result.getNode()) return Result;
1545 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1546 if (N1.getOpcode() == ISD::SHL &&
1547 N1.getOperand(0).getOpcode() == ISD::SUB)
1548 if (ConstantSDNode *C =
1549 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1550 if (C->getAPIntValue() == 0)
1551 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1552 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1553 N1.getOperand(0).getOperand(1),
1555 if (N0.getOpcode() == ISD::SHL &&
1556 N0.getOperand(0).getOpcode() == ISD::SUB)
1557 if (ConstantSDNode *C =
1558 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1559 if (C->getAPIntValue() == 0)
1560 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1561 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1562 N0.getOperand(0).getOperand(1),
1565 if (N1.getOpcode() == ISD::AND) {
1566 SDValue AndOp0 = N1.getOperand(0);
1567 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1568 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1569 unsigned DestBits = VT.getScalarType().getSizeInBits();
1571 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1572 // and similar xforms where the inner op is either ~0 or 0.
1573 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1575 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1579 // add (sext i1), X -> sub X, (zext i1)
1580 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1581 N0.getOperand(0).getValueType() == MVT::i1 &&
1582 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1584 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1585 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1591 SDValue DAGCombiner::visitADDC(SDNode *N) {
1592 SDValue N0 = N->getOperand(0);
1593 SDValue N1 = N->getOperand(1);
1594 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1595 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1596 EVT VT = N0.getValueType();
1598 // If the flag result is dead, turn this into an ADD.
1599 if (!N->hasAnyUseOfValue(1))
1600 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1601 DAG.getNode(ISD::CARRY_FALSE,
1602 SDLoc(N), MVT::Glue));
1604 // canonicalize constant to RHS.
1606 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1608 // fold (addc x, 0) -> x + no carry out
1609 if (N1C && N1C->isNullValue())
1610 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1611 SDLoc(N), MVT::Glue));
1613 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1614 APInt LHSZero, LHSOne;
1615 APInt RHSZero, RHSOne;
1616 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1618 if (LHSZero.getBoolValue()) {
1619 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1621 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1622 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1623 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1624 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1625 DAG.getNode(ISD::CARRY_FALSE,
1626 SDLoc(N), MVT::Glue));
1632 SDValue DAGCombiner::visitADDE(SDNode *N) {
1633 SDValue N0 = N->getOperand(0);
1634 SDValue N1 = N->getOperand(1);
1635 SDValue CarryIn = N->getOperand(2);
1636 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1637 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1639 // canonicalize constant to RHS
1641 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1644 // fold (adde x, y, false) -> (addc x, y)
1645 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1646 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1651 // Since it may not be valid to emit a fold to zero for vector initializers
1652 // check if we can before folding.
1653 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1655 bool LegalOperations, bool LegalTypes) {
1657 return DAG.getConstant(0, VT);
1658 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1659 return DAG.getConstant(0, VT);
1663 SDValue DAGCombiner::visitSUB(SDNode *N) {
1664 SDValue N0 = N->getOperand(0);
1665 SDValue N1 = N->getOperand(1);
1666 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1667 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1668 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1669 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1670 EVT VT = N0.getValueType();
1673 if (VT.isVector()) {
1674 SDValue FoldedVOp = SimplifyVBinOp(N);
1675 if (FoldedVOp.getNode()) return FoldedVOp;
1677 // fold (sub x, 0) -> x, vector edition
1678 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1682 // fold (sub x, x) -> 0
1683 // FIXME: Refactor this and xor and other similar operations together.
1685 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1686 // fold (sub c1, c2) -> c1-c2
1688 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1689 // fold (sub x, c) -> (add x, -c)
1691 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1692 DAG.getConstant(-N1C->getAPIntValue(), VT));
1693 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1694 if (N0C && N0C->isAllOnesValue())
1695 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1696 // fold A-(A-B) -> B
1697 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1698 return N1.getOperand(1);
1699 // fold (A+B)-A -> B
1700 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1701 return N0.getOperand(1);
1702 // fold (A+B)-B -> A
1703 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1704 return N0.getOperand(0);
1705 // fold C2-(A+C1) -> (C2-C1)-A
1706 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1707 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1709 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1712 // fold ((A+(B+or-C))-B) -> A+or-C
1713 if (N0.getOpcode() == ISD::ADD &&
1714 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1715 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1716 N0.getOperand(1).getOperand(0) == N1)
1717 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1718 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1719 // fold ((A+(C+B))-B) -> A+C
1720 if (N0.getOpcode() == ISD::ADD &&
1721 N0.getOperand(1).getOpcode() == ISD::ADD &&
1722 N0.getOperand(1).getOperand(1) == N1)
1723 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1724 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1725 // fold ((A-(B-C))-C) -> A-B
1726 if (N0.getOpcode() == ISD::SUB &&
1727 N0.getOperand(1).getOpcode() == ISD::SUB &&
1728 N0.getOperand(1).getOperand(1) == N1)
1729 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1730 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1732 // If either operand of a sub is undef, the result is undef
1733 if (N0.getOpcode() == ISD::UNDEF)
1735 if (N1.getOpcode() == ISD::UNDEF)
1738 // If the relocation model supports it, consider symbol offsets.
1739 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1740 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1741 // fold (sub Sym, c) -> Sym-c
1742 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1743 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1745 (uint64_t)N1C->getSExtValue());
1746 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1747 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1748 if (GA->getGlobal() == GB->getGlobal())
1749 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1756 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1757 SDValue N0 = N->getOperand(0);
1758 SDValue N1 = N->getOperand(1);
1759 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1760 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1761 EVT VT = N0.getValueType();
1763 // If the flag result is dead, turn this into an SUB.
1764 if (!N->hasAnyUseOfValue(1))
1765 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1766 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1769 // fold (subc x, x) -> 0 + no borrow
1771 return CombineTo(N, DAG.getConstant(0, VT),
1772 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1775 // fold (subc x, 0) -> x + no borrow
1776 if (N1C && N1C->isNullValue())
1777 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1780 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1781 if (N0C && N0C->isAllOnesValue())
1782 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1783 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1789 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1790 SDValue N0 = N->getOperand(0);
1791 SDValue N1 = N->getOperand(1);
1792 SDValue CarryIn = N->getOperand(2);
1794 // fold (sube x, y, false) -> (subc x, y)
1795 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1796 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1801 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1802 /// elements are all the same constant or undefined.
1803 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1804 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1809 unsigned SplatBitSize;
1811 EVT EltVT = N->getValueType(0).getVectorElementType();
1812 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1814 EltVT.getSizeInBits() >= SplatBitSize);
1817 SDValue DAGCombiner::visitMUL(SDNode *N) {
1818 SDValue N0 = N->getOperand(0);
1819 SDValue N1 = N->getOperand(1);
1820 EVT VT = N0.getValueType();
1822 // fold (mul x, undef) -> 0
1823 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1824 return DAG.getConstant(0, VT);
1826 bool N0IsConst = false;
1827 bool N1IsConst = false;
1828 APInt ConstValue0, ConstValue1;
1830 if (VT.isVector()) {
1831 SDValue FoldedVOp = SimplifyVBinOp(N);
1832 if (FoldedVOp.getNode()) return FoldedVOp;
1834 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1835 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1837 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1838 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1840 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1841 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1845 // fold (mul c1, c2) -> c1*c2
1846 if (N0IsConst && N1IsConst)
1847 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1849 // canonicalize constant to RHS
1850 if (N0IsConst && !N1IsConst)
1851 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1852 // fold (mul x, 0) -> 0
1853 if (N1IsConst && ConstValue1 == 0)
1855 // We require a splat of the entire scalar bit width for non-contiguous
1858 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1859 // fold (mul x, 1) -> x
1860 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1862 // fold (mul x, -1) -> 0-x
1863 if (N1IsConst && ConstValue1.isAllOnesValue())
1864 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1865 DAG.getConstant(0, VT), N0);
1866 // fold (mul x, (1 << c)) -> x << c
1867 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1868 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1869 DAG.getConstant(ConstValue1.logBase2(),
1870 getShiftAmountTy(N0.getValueType())));
1871 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1872 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1873 unsigned Log2Val = (-ConstValue1).logBase2();
1874 // FIXME: If the input is something that is easily negated (e.g. a
1875 // single-use add), we should put the negate there.
1876 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1877 DAG.getConstant(0, VT),
1878 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1879 DAG.getConstant(Log2Val,
1880 getShiftAmountTy(N0.getValueType()))));
1884 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1885 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1886 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1887 isa<ConstantSDNode>(N0.getOperand(1)))) {
1888 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1889 N1, N0.getOperand(1));
1890 AddToWorkList(C3.getNode());
1891 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1892 N0.getOperand(0), C3);
1895 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1898 SDValue Sh(0,0), Y(0,0);
1899 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1900 if (N0.getOpcode() == ISD::SHL &&
1901 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1902 isa<ConstantSDNode>(N0.getOperand(1))) &&
1903 N0.getNode()->hasOneUse()) {
1905 } else if (N1.getOpcode() == ISD::SHL &&
1906 isa<ConstantSDNode>(N1.getOperand(1)) &&
1907 N1.getNode()->hasOneUse()) {
1912 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1913 Sh.getOperand(0), Y);
1914 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1915 Mul, Sh.getOperand(1));
1919 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1920 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1921 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1922 isa<ConstantSDNode>(N0.getOperand(1))))
1923 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1924 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1925 N0.getOperand(0), N1),
1926 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1927 N0.getOperand(1), N1));
1930 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1931 if (RMUL.getNode() != 0)
1937 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1938 SDValue N0 = N->getOperand(0);
1939 SDValue N1 = N->getOperand(1);
1940 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1941 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1942 EVT VT = N->getValueType(0);
1945 if (VT.isVector()) {
1946 SDValue FoldedVOp = SimplifyVBinOp(N);
1947 if (FoldedVOp.getNode()) return FoldedVOp;
1950 // fold (sdiv c1, c2) -> c1/c2
1951 if (N0C && N1C && !N1C->isNullValue())
1952 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1953 // fold (sdiv X, 1) -> X
1954 if (N1C && N1C->getAPIntValue() == 1LL)
1956 // fold (sdiv X, -1) -> 0-X
1957 if (N1C && N1C->isAllOnesValue())
1958 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1959 DAG.getConstant(0, VT), N0);
1960 // If we know the sign bits of both operands are zero, strength reduce to a
1961 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1962 if (!VT.isVector()) {
1963 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1964 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1967 // fold (sdiv X, pow2) -> simple ops after legalize
1968 if (N1C && !N1C->isNullValue() &&
1969 (N1C->getAPIntValue().isPowerOf2() ||
1970 (-N1C->getAPIntValue()).isPowerOf2())) {
1971 // If dividing by powers of two is cheap, then don't perform the following
1973 if (TLI.isPow2DivCheap())
1976 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1978 // Splat the sign bit into the register
1979 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1980 DAG.getConstant(VT.getSizeInBits()-1,
1981 getShiftAmountTy(N0.getValueType())));
1982 AddToWorkList(SGN.getNode());
1984 // Add (N0 < 0) ? abs2 - 1 : 0;
1985 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1986 DAG.getConstant(VT.getSizeInBits() - lg2,
1987 getShiftAmountTy(SGN.getValueType())));
1988 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1989 AddToWorkList(SRL.getNode());
1990 AddToWorkList(ADD.getNode()); // Divide by pow2
1991 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1992 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1994 // If we're dividing by a positive value, we're done. Otherwise, we must
1995 // negate the result.
1996 if (N1C->getAPIntValue().isNonNegative())
1999 AddToWorkList(SRA.getNode());
2000 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2001 DAG.getConstant(0, VT), SRA);
2004 // if integer divide is expensive and we satisfy the requirements, emit an
2005 // alternate sequence.
2006 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2007 SDValue Op = BuildSDIV(N);
2008 if (Op.getNode()) return Op;
2012 if (N0.getOpcode() == ISD::UNDEF)
2013 return DAG.getConstant(0, VT);
2014 // X / undef -> undef
2015 if (N1.getOpcode() == ISD::UNDEF)
2021 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2022 SDValue N0 = N->getOperand(0);
2023 SDValue N1 = N->getOperand(1);
2024 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2025 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2026 EVT VT = N->getValueType(0);
2029 if (VT.isVector()) {
2030 SDValue FoldedVOp = SimplifyVBinOp(N);
2031 if (FoldedVOp.getNode()) return FoldedVOp;
2034 // fold (udiv c1, c2) -> c1/c2
2035 if (N0C && N1C && !N1C->isNullValue())
2036 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2037 // fold (udiv x, (1 << c)) -> x >>u c
2038 if (N1C && N1C->getAPIntValue().isPowerOf2())
2039 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2040 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2041 getShiftAmountTy(N0.getValueType())));
2042 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2043 if (N1.getOpcode() == ISD::SHL) {
2044 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2045 if (SHC->getAPIntValue().isPowerOf2()) {
2046 EVT ADDVT = N1.getOperand(1).getValueType();
2047 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2049 DAG.getConstant(SHC->getAPIntValue()
2052 AddToWorkList(Add.getNode());
2053 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2057 // fold (udiv x, c) -> alternate
2058 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2059 SDValue Op = BuildUDIV(N);
2060 if (Op.getNode()) return Op;
2064 if (N0.getOpcode() == ISD::UNDEF)
2065 return DAG.getConstant(0, VT);
2066 // X / undef -> undef
2067 if (N1.getOpcode() == ISD::UNDEF)
2073 SDValue DAGCombiner::visitSREM(SDNode *N) {
2074 SDValue N0 = N->getOperand(0);
2075 SDValue N1 = N->getOperand(1);
2076 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2077 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2078 EVT VT = N->getValueType(0);
2080 // fold (srem c1, c2) -> c1%c2
2081 if (N0C && N1C && !N1C->isNullValue())
2082 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2083 // If we know the sign bits of both operands are zero, strength reduce to a
2084 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2085 if (!VT.isVector()) {
2086 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2087 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2090 // If X/C can be simplified by the division-by-constant logic, lower
2091 // X%C to the equivalent of X-X/C*C.
2092 if (N1C && !N1C->isNullValue()) {
2093 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2094 AddToWorkList(Div.getNode());
2095 SDValue OptimizedDiv = combine(Div.getNode());
2096 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2097 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2099 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2100 AddToWorkList(Mul.getNode());
2106 if (N0.getOpcode() == ISD::UNDEF)
2107 return DAG.getConstant(0, VT);
2108 // X % undef -> undef
2109 if (N1.getOpcode() == ISD::UNDEF)
2115 SDValue DAGCombiner::visitUREM(SDNode *N) {
2116 SDValue N0 = N->getOperand(0);
2117 SDValue N1 = N->getOperand(1);
2118 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2119 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2120 EVT VT = N->getValueType(0);
2122 // fold (urem c1, c2) -> c1%c2
2123 if (N0C && N1C && !N1C->isNullValue())
2124 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2125 // fold (urem x, pow2) -> (and x, pow2-1)
2126 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2127 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2128 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2129 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2130 if (N1.getOpcode() == ISD::SHL) {
2131 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2132 if (SHC->getAPIntValue().isPowerOf2()) {
2134 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2135 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2137 AddToWorkList(Add.getNode());
2138 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2143 // If X/C can be simplified by the division-by-constant logic, lower
2144 // X%C to the equivalent of X-X/C*C.
2145 if (N1C && !N1C->isNullValue()) {
2146 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2147 AddToWorkList(Div.getNode());
2148 SDValue OptimizedDiv = combine(Div.getNode());
2149 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2150 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2152 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2153 AddToWorkList(Mul.getNode());
2159 if (N0.getOpcode() == ISD::UNDEF)
2160 return DAG.getConstant(0, VT);
2161 // X % undef -> undef
2162 if (N1.getOpcode() == ISD::UNDEF)
2168 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2169 SDValue N0 = N->getOperand(0);
2170 SDValue N1 = N->getOperand(1);
2171 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2172 EVT VT = N->getValueType(0);
2175 // fold (mulhs x, 0) -> 0
2176 if (N1C && N1C->isNullValue())
2178 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2179 if (N1C && N1C->getAPIntValue() == 1)
2180 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2181 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2182 getShiftAmountTy(N0.getValueType())));
2183 // fold (mulhs x, undef) -> 0
2184 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2185 return DAG.getConstant(0, VT);
2187 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2189 if (VT.isSimple() && !VT.isVector()) {
2190 MVT Simple = VT.getSimpleVT();
2191 unsigned SimpleSize = Simple.getSizeInBits();
2192 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2193 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2194 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2195 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2196 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2197 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2198 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2199 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2206 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2207 SDValue N0 = N->getOperand(0);
2208 SDValue N1 = N->getOperand(1);
2209 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2210 EVT VT = N->getValueType(0);
2213 // fold (mulhu x, 0) -> 0
2214 if (N1C && N1C->isNullValue())
2216 // fold (mulhu x, 1) -> 0
2217 if (N1C && N1C->getAPIntValue() == 1)
2218 return DAG.getConstant(0, N0.getValueType());
2219 // fold (mulhu x, undef) -> 0
2220 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2221 return DAG.getConstant(0, VT);
2223 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2225 if (VT.isSimple() && !VT.isVector()) {
2226 MVT Simple = VT.getSimpleVT();
2227 unsigned SimpleSize = Simple.getSizeInBits();
2228 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2229 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2230 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2231 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2232 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2233 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2234 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2235 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2242 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2243 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2244 /// that are being performed. Return true if a simplification was made.
2246 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2248 // If the high half is not needed, just compute the low half.
2249 bool HiExists = N->hasAnyUseOfValue(1);
2251 (!LegalOperations ||
2252 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2253 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2254 N->op_begin(), N->getNumOperands());
2255 return CombineTo(N, Res, Res);
2258 // If the low half is not needed, just compute the high half.
2259 bool LoExists = N->hasAnyUseOfValue(0);
2261 (!LegalOperations ||
2262 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2263 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2264 N->op_begin(), N->getNumOperands());
2265 return CombineTo(N, Res, Res);
2268 // If both halves are used, return as it is.
2269 if (LoExists && HiExists)
2272 // If the two computed results can be simplified separately, separate them.
2274 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2275 N->op_begin(), N->getNumOperands());
2276 AddToWorkList(Lo.getNode());
2277 SDValue LoOpt = combine(Lo.getNode());
2278 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2279 (!LegalOperations ||
2280 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2281 return CombineTo(N, LoOpt, LoOpt);
2285 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2286 N->op_begin(), N->getNumOperands());
2287 AddToWorkList(Hi.getNode());
2288 SDValue HiOpt = combine(Hi.getNode());
2289 if (HiOpt.getNode() && HiOpt != Hi &&
2290 (!LegalOperations ||
2291 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2292 return CombineTo(N, HiOpt, HiOpt);
2298 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2299 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2300 if (Res.getNode()) return Res;
2302 EVT VT = N->getValueType(0);
2305 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2307 if (VT.isSimple() && !VT.isVector()) {
2308 MVT Simple = VT.getSimpleVT();
2309 unsigned SimpleSize = Simple.getSizeInBits();
2310 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2311 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2312 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2313 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2314 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2315 // Compute the high part as N1.
2316 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2317 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2318 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2319 // Compute the low part as N0.
2320 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2321 return CombineTo(N, Lo, Hi);
2328 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2329 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2330 if (Res.getNode()) return Res;
2332 EVT VT = N->getValueType(0);
2335 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2337 if (VT.isSimple() && !VT.isVector()) {
2338 MVT Simple = VT.getSimpleVT();
2339 unsigned SimpleSize = Simple.getSizeInBits();
2340 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2341 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2342 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2343 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2344 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2345 // Compute the high part as N1.
2346 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2347 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2348 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2349 // Compute the low part as N0.
2350 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2351 return CombineTo(N, Lo, Hi);
2358 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2359 // (smulo x, 2) -> (saddo x, x)
2360 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2361 if (C2->getAPIntValue() == 2)
2362 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2363 N->getOperand(0), N->getOperand(0));
2368 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2369 // (umulo x, 2) -> (uaddo x, x)
2370 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2371 if (C2->getAPIntValue() == 2)
2372 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2373 N->getOperand(0), N->getOperand(0));
2378 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2379 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2380 if (Res.getNode()) return Res;
2385 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2386 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2387 if (Res.getNode()) return Res;
2392 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2393 /// two operands of the same opcode, try to simplify it.
2394 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2395 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2396 EVT VT = N0.getValueType();
2397 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2399 // Bail early if none of these transforms apply.
2400 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2402 // For each of OP in AND/OR/XOR:
2403 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2404 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2405 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2406 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2408 // do not sink logical op inside of a vector extend, since it may combine
2410 EVT Op0VT = N0.getOperand(0).getValueType();
2411 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2412 N0.getOpcode() == ISD::SIGN_EXTEND ||
2413 // Avoid infinite looping with PromoteIntBinOp.
2414 (N0.getOpcode() == ISD::ANY_EXTEND &&
2415 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2416 (N0.getOpcode() == ISD::TRUNCATE &&
2417 (!TLI.isZExtFree(VT, Op0VT) ||
2418 !TLI.isTruncateFree(Op0VT, VT)) &&
2419 TLI.isTypeLegal(Op0VT))) &&
2421 Op0VT == N1.getOperand(0).getValueType() &&
2422 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2423 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2424 N0.getOperand(0).getValueType(),
2425 N0.getOperand(0), N1.getOperand(0));
2426 AddToWorkList(ORNode.getNode());
2427 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2430 // For each of OP in SHL/SRL/SRA/AND...
2431 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2432 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2433 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2434 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2435 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2436 N0.getOperand(1) == N1.getOperand(1)) {
2437 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2438 N0.getOperand(0).getValueType(),
2439 N0.getOperand(0), N1.getOperand(0));
2440 AddToWorkList(ORNode.getNode());
2441 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2442 ORNode, N0.getOperand(1));
2445 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2446 // Only perform this optimization after type legalization and before
2447 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2448 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2449 // we don't want to undo this promotion.
2450 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2452 if ((N0.getOpcode() == ISD::BITCAST ||
2453 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2454 Level == AfterLegalizeTypes) {
2455 SDValue In0 = N0.getOperand(0);
2456 SDValue In1 = N1.getOperand(0);
2457 EVT In0Ty = In0.getValueType();
2458 EVT In1Ty = In1.getValueType();
2460 // If both incoming values are integers, and the original types are the
2462 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2463 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2464 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2465 AddToWorkList(Op.getNode());
2470 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2471 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2472 // If both shuffles use the same mask, and both shuffle within a single
2473 // vector, then it is worthwhile to move the swizzle after the operation.
2474 // The type-legalizer generates this pattern when loading illegal
2475 // vector types from memory. In many cases this allows additional shuffle
2477 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2478 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2479 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2480 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2481 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2483 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2484 "Inputs to shuffles are not the same type");
2486 unsigned NumElts = VT.getVectorNumElements();
2488 // Check that both shuffles use the same mask. The masks are known to be of
2489 // the same length because the result vector type is the same.
2490 bool SameMask = true;
2491 for (unsigned i = 0; i != NumElts; ++i) {
2492 int Idx0 = SVN0->getMaskElt(i);
2493 int Idx1 = SVN1->getMaskElt(i);
2501 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2502 N0.getOperand(0), N1.getOperand(0));
2503 AddToWorkList(Op.getNode());
2504 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2505 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2512 SDValue DAGCombiner::visitAND(SDNode *N) {
2513 SDValue N0 = N->getOperand(0);
2514 SDValue N1 = N->getOperand(1);
2515 SDValue LL, LR, RL, RR, CC0, CC1;
2516 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2517 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2518 EVT VT = N1.getValueType();
2519 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2522 if (VT.isVector()) {
2523 SDValue FoldedVOp = SimplifyVBinOp(N);
2524 if (FoldedVOp.getNode()) return FoldedVOp;
2526 // fold (and x, 0) -> 0, vector edition
2527 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2529 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2532 // fold (and x, -1) -> x, vector edition
2533 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2535 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2539 // fold (and x, undef) -> 0
2540 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2541 return DAG.getConstant(0, VT);
2542 // fold (and c1, c2) -> c1&c2
2544 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2545 // canonicalize constant to RHS
2547 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2548 // fold (and x, -1) -> x
2549 if (N1C && N1C->isAllOnesValue())
2551 // if (and x, c) is known to be zero, return 0
2552 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2553 APInt::getAllOnesValue(BitWidth)))
2554 return DAG.getConstant(0, VT);
2556 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2557 if (RAND.getNode() != 0)
2559 // fold (and (or x, C), D) -> D if (C & D) == D
2560 if (N1C && N0.getOpcode() == ISD::OR)
2561 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2562 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2564 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2565 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2566 SDValue N0Op0 = N0.getOperand(0);
2567 APInt Mask = ~N1C->getAPIntValue();
2568 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2569 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2570 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2571 N0.getValueType(), N0Op0);
2573 // Replace uses of the AND with uses of the Zero extend node.
2576 // We actually want to replace all uses of the any_extend with the
2577 // zero_extend, to avoid duplicating things. This will later cause this
2578 // AND to be folded.
2579 CombineTo(N0.getNode(), Zext);
2580 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2583 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2584 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2585 // already be zero by virtue of the width of the base type of the load.
2587 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2589 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2590 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2591 N0.getOpcode() == ISD::LOAD) {
2592 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2593 N0 : N0.getOperand(0) );
2595 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2596 // This can be a pure constant or a vector splat, in which case we treat the
2597 // vector as a scalar and use the splat value.
2598 APInt Constant = APInt::getNullValue(1);
2599 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2600 Constant = C->getAPIntValue();
2601 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2602 APInt SplatValue, SplatUndef;
2603 unsigned SplatBitSize;
2605 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2606 SplatBitSize, HasAnyUndefs);
2608 // Undef bits can contribute to a possible optimisation if set, so
2610 SplatValue |= SplatUndef;
2612 // The splat value may be something like "0x00FFFFFF", which means 0 for
2613 // the first vector value and FF for the rest, repeating. We need a mask
2614 // that will apply equally to all members of the vector, so AND all the
2615 // lanes of the constant together.
2616 EVT VT = Vector->getValueType(0);
2617 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2619 // If the splat value has been compressed to a bitlength lower
2620 // than the size of the vector lane, we need to re-expand it to
2622 if (BitWidth > SplatBitSize)
2623 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2624 SplatBitSize < BitWidth;
2625 SplatBitSize = SplatBitSize * 2)
2626 SplatValue |= SplatValue.shl(SplatBitSize);
2628 Constant = APInt::getAllOnesValue(BitWidth);
2629 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2630 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2634 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2635 // actually legal and isn't going to get expanded, else this is a false
2637 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2638 Load->getMemoryVT());
2640 // Resize the constant to the same size as the original memory access before
2641 // extension. If it is still the AllOnesValue then this AND is completely
2644 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2647 switch (Load->getExtensionType()) {
2648 default: B = false; break;
2649 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2651 case ISD::NON_EXTLOAD: B = true; break;
2654 if (B && Constant.isAllOnesValue()) {
2655 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2656 // preserve semantics once we get rid of the AND.
2657 SDValue NewLoad(Load, 0);
2658 if (Load->getExtensionType() == ISD::EXTLOAD) {
2659 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2660 Load->getValueType(0), SDLoc(Load),
2661 Load->getChain(), Load->getBasePtr(),
2662 Load->getOffset(), Load->getMemoryVT(),
2663 Load->getMemOperand());
2664 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2665 if (Load->getNumValues() == 3) {
2666 // PRE/POST_INC loads have 3 values.
2667 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2668 NewLoad.getValue(2) };
2669 CombineTo(Load, To, 3, true);
2671 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2675 // Fold the AND away, taking care not to fold to the old load node if we
2677 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2679 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2682 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2683 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2684 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2685 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2687 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2688 LL.getValueType().isInteger()) {
2689 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2690 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2691 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2692 LR.getValueType(), LL, RL);
2693 AddToWorkList(ORNode.getNode());
2694 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2696 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2697 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2698 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2699 LR.getValueType(), LL, RL);
2700 AddToWorkList(ANDNode.getNode());
2701 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2703 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2704 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2705 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2706 LR.getValueType(), LL, RL);
2707 AddToWorkList(ORNode.getNode());
2708 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2711 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2712 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2713 Op0 == Op1 && LL.getValueType().isInteger() &&
2714 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2715 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2716 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2717 cast<ConstantSDNode>(RR)->isNullValue()))) {
2718 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2719 LL, DAG.getConstant(1, LL.getValueType()));
2720 AddToWorkList(ADDNode.getNode());
2721 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2722 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2724 // canonicalize equivalent to ll == rl
2725 if (LL == RR && LR == RL) {
2726 Op1 = ISD::getSetCCSwappedOperands(Op1);
2729 if (LL == RL && LR == RR) {
2730 bool isInteger = LL.getValueType().isInteger();
2731 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2732 if (Result != ISD::SETCC_INVALID &&
2733 (!LegalOperations ||
2734 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2735 TLI.isOperationLegal(ISD::SETCC,
2736 getSetCCResultType(N0.getSimpleValueType())))))
2737 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2742 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2743 if (N0.getOpcode() == N1.getOpcode()) {
2744 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2745 if (Tmp.getNode()) return Tmp;
2748 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2749 // fold (and (sra)) -> (and (srl)) when possible.
2750 if (!VT.isVector() &&
2751 SimplifyDemandedBits(SDValue(N, 0)))
2752 return SDValue(N, 0);
2754 // fold (zext_inreg (extload x)) -> (zextload x)
2755 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2756 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2757 EVT MemVT = LN0->getMemoryVT();
2758 // If we zero all the possible extended bits, then we can turn this into
2759 // a zextload if we are running before legalize or the operation is legal.
2760 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2761 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2762 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2763 ((!LegalOperations && !LN0->isVolatile()) ||
2764 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2765 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2766 LN0->getChain(), LN0->getBasePtr(),
2767 MemVT, LN0->getMemOperand());
2769 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2770 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2773 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2774 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2776 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2777 EVT MemVT = LN0->getMemoryVT();
2778 // If we zero all the possible extended bits, then we can turn this into
2779 // a zextload if we are running before legalize or the operation is legal.
2780 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2781 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2782 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2783 ((!LegalOperations && !LN0->isVolatile()) ||
2784 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2785 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2786 LN0->getChain(), LN0->getBasePtr(),
2787 MemVT, LN0->getMemOperand());
2789 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2790 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2794 // fold (and (load x), 255) -> (zextload x, i8)
2795 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2796 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2797 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2798 (N0.getOpcode() == ISD::ANY_EXTEND &&
2799 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2800 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2801 LoadSDNode *LN0 = HasAnyExt
2802 ? cast<LoadSDNode>(N0.getOperand(0))
2803 : cast<LoadSDNode>(N0);
2804 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2805 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2806 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2807 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2808 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2809 EVT LoadedVT = LN0->getMemoryVT();
2811 if (ExtVT == LoadedVT &&
2812 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2813 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2816 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2817 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2818 LN0->getMemOperand());
2820 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2821 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2824 // Do not change the width of a volatile load.
2825 // Do not generate loads of non-round integer types since these can
2826 // be expensive (and would be wrong if the type is not byte sized).
2827 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2828 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2829 EVT PtrType = LN0->getOperand(1).getValueType();
2831 unsigned Alignment = LN0->getAlignment();
2832 SDValue NewPtr = LN0->getBasePtr();
2834 // For big endian targets, we need to add an offset to the pointer
2835 // to load the correct bytes. For little endian systems, we merely
2836 // need to read fewer bytes from the same pointer.
2837 if (TLI.isBigEndian()) {
2838 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2839 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2840 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2841 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2842 NewPtr, DAG.getConstant(PtrOff, PtrType));
2843 Alignment = MinAlign(Alignment, PtrOff);
2846 AddToWorkList(NewPtr.getNode());
2848 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2850 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2851 LN0->getChain(), NewPtr,
2852 LN0->getPointerInfo(),
2853 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2854 Alignment, LN0->getTBAAInfo());
2856 CombineTo(LN0, Load, Load.getValue(1));
2857 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2863 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2864 VT.getSizeInBits() <= 64) {
2865 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2866 APInt ADDC = ADDI->getAPIntValue();
2867 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2868 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2869 // immediate for an add, but it is legal if its top c2 bits are set,
2870 // transform the ADD so the immediate doesn't need to be materialized
2872 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2873 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2874 SRLI->getZExtValue());
2875 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2877 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2879 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2880 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2881 CombineTo(N0.getNode(), NewAdd);
2882 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2890 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2891 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2892 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2893 N0.getOperand(1), false);
2894 if (BSwap.getNode())
2901 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2903 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2904 bool DemandHighBits) {
2905 if (!LegalOperations)
2908 EVT VT = N->getValueType(0);
2909 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2911 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2914 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2915 bool LookPassAnd0 = false;
2916 bool LookPassAnd1 = false;
2917 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2919 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2921 if (N0.getOpcode() == ISD::AND) {
2922 if (!N0.getNode()->hasOneUse())
2924 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2925 if (!N01C || N01C->getZExtValue() != 0xFF00)
2927 N0 = N0.getOperand(0);
2928 LookPassAnd0 = true;
2931 if (N1.getOpcode() == ISD::AND) {
2932 if (!N1.getNode()->hasOneUse())
2934 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2935 if (!N11C || N11C->getZExtValue() != 0xFF)
2937 N1 = N1.getOperand(0);
2938 LookPassAnd1 = true;
2941 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2943 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2945 if (!N0.getNode()->hasOneUse() ||
2946 !N1.getNode()->hasOneUse())
2949 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2950 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2953 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2956 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2957 SDValue N00 = N0->getOperand(0);
2958 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2959 if (!N00.getNode()->hasOneUse())
2961 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2962 if (!N001C || N001C->getZExtValue() != 0xFF)
2964 N00 = N00.getOperand(0);
2965 LookPassAnd0 = true;
2968 SDValue N10 = N1->getOperand(0);
2969 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2970 if (!N10.getNode()->hasOneUse())
2972 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2973 if (!N101C || N101C->getZExtValue() != 0xFF00)
2975 N10 = N10.getOperand(0);
2976 LookPassAnd1 = true;
2982 // Make sure everything beyond the low halfword gets set to zero since the SRL
2983 // 16 will clear the top bits.
2984 unsigned OpSizeInBits = VT.getSizeInBits();
2985 if (DemandHighBits && OpSizeInBits > 16) {
2986 // If the left-shift isn't masked out then the only way this is a bswap is
2987 // if all bits beyond the low 8 are 0. In that case the entire pattern
2988 // reduces to a left shift anyway: leave it for other parts of the combiner.
2992 // However, if the right shift isn't masked out then it might be because
2993 // it's not needed. See if we can spot that too.
2994 if (!LookPassAnd1 &&
2995 !DAG.MaskedValueIsZero(
2996 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3000 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3001 if (OpSizeInBits > 16)
3002 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3003 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3007 /// isBSwapHWordElement - Return true if the specified node is an element
3008 /// that makes up a 32-bit packed halfword byteswap. i.e.
3009 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3010 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3011 if (!N.getNode()->hasOneUse())
3014 unsigned Opc = N.getOpcode();
3015 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3018 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3023 switch (N1C->getZExtValue()) {
3026 case 0xFF: Num = 0; break;
3027 case 0xFF00: Num = 1; break;
3028 case 0xFF0000: Num = 2; break;
3029 case 0xFF000000: Num = 3; break;
3032 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3033 SDValue N0 = N.getOperand(0);
3034 if (Opc == ISD::AND) {
3035 if (Num == 0 || Num == 2) {
3037 // (x >> 8) & 0xff0000
3038 if (N0.getOpcode() != ISD::SRL)
3040 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3041 if (!C || C->getZExtValue() != 8)
3044 // (x << 8) & 0xff00
3045 // (x << 8) & 0xff000000
3046 if (N0.getOpcode() != ISD::SHL)
3048 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3049 if (!C || C->getZExtValue() != 8)
3052 } else if (Opc == ISD::SHL) {
3054 // (x & 0xff0000) << 8
3055 if (Num != 0 && Num != 2)
3057 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3058 if (!C || C->getZExtValue() != 8)
3060 } else { // Opc == ISD::SRL
3061 // (x & 0xff00) >> 8
3062 // (x & 0xff000000) >> 8
3063 if (Num != 1 && Num != 3)
3065 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3066 if (!C || C->getZExtValue() != 8)
3073 Parts[Num] = N0.getOperand(0).getNode();
3077 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3078 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3079 /// => (rotl (bswap x), 16)
3080 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3081 if (!LegalOperations)
3084 EVT VT = N->getValueType(0);
3087 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3090 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3092 // (or (or (and), (and)), (or (and), (and)))
3093 // (or (or (or (and), (and)), (and)), (and))
3094 if (N0.getOpcode() != ISD::OR)
3096 SDValue N00 = N0.getOperand(0);
3097 SDValue N01 = N0.getOperand(1);
3099 if (N1.getOpcode() == ISD::OR &&
3100 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3101 // (or (or (and), (and)), (or (and), (and)))
3102 SDValue N000 = N00.getOperand(0);
3103 if (!isBSwapHWordElement(N000, Parts))
3106 SDValue N001 = N00.getOperand(1);
3107 if (!isBSwapHWordElement(N001, Parts))
3109 SDValue N010 = N01.getOperand(0);
3110 if (!isBSwapHWordElement(N010, Parts))
3112 SDValue N011 = N01.getOperand(1);
3113 if (!isBSwapHWordElement(N011, Parts))
3116 // (or (or (or (and), (and)), (and)), (and))
3117 if (!isBSwapHWordElement(N1, Parts))
3119 if (!isBSwapHWordElement(N01, Parts))
3121 if (N00.getOpcode() != ISD::OR)
3123 SDValue N000 = N00.getOperand(0);
3124 if (!isBSwapHWordElement(N000, Parts))
3126 SDValue N001 = N00.getOperand(1);
3127 if (!isBSwapHWordElement(N001, Parts))
3131 // Make sure the parts are all coming from the same node.
3132 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3135 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3136 SDValue(Parts[0],0));
3138 // Result of the bswap should be rotated by 16. If it's not legal, then
3139 // do (x << 16) | (x >> 16).
3140 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3141 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3142 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3143 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3144 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3145 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3146 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3147 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3150 SDValue DAGCombiner::visitOR(SDNode *N) {
3151 SDValue N0 = N->getOperand(0);
3152 SDValue N1 = N->getOperand(1);
3153 SDValue LL, LR, RL, RR, CC0, CC1;
3154 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3155 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3156 EVT VT = N1.getValueType();
3159 if (VT.isVector()) {
3160 SDValue FoldedVOp = SimplifyVBinOp(N);
3161 if (FoldedVOp.getNode()) return FoldedVOp;
3163 // fold (or x, 0) -> x, vector edition
3164 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3166 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3169 // fold (or x, -1) -> -1, vector edition
3170 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3172 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3176 // fold (or x, undef) -> -1
3177 if (!LegalOperations &&
3178 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3179 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3180 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3182 // fold (or c1, c2) -> c1|c2
3184 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3185 // canonicalize constant to RHS
3187 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3188 // fold (or x, 0) -> x
3189 if (N1C && N1C->isNullValue())
3191 // fold (or x, -1) -> -1
3192 if (N1C && N1C->isAllOnesValue())
3194 // fold (or x, c) -> c iff (x & ~c) == 0
3195 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3198 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3199 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3200 if (BSwap.getNode() != 0)
3202 BSwap = MatchBSwapHWordLow(N, N0, N1);
3203 if (BSwap.getNode() != 0)
3207 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3208 if (ROR.getNode() != 0)
3210 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3211 // iff (c1 & c2) == 0.
3212 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3213 isa<ConstantSDNode>(N0.getOperand(1))) {
3214 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3215 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3216 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3217 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3218 N0.getOperand(0), N1),
3219 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3221 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3222 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3223 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3224 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3226 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3227 LL.getValueType().isInteger()) {
3228 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3229 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3230 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3231 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3232 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3233 LR.getValueType(), LL, RL);
3234 AddToWorkList(ORNode.getNode());
3235 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3237 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3238 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3239 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3240 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3241 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3242 LR.getValueType(), LL, RL);
3243 AddToWorkList(ANDNode.getNode());
3244 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3247 // canonicalize equivalent to ll == rl
3248 if (LL == RR && LR == RL) {
3249 Op1 = ISD::getSetCCSwappedOperands(Op1);
3252 if (LL == RL && LR == RR) {
3253 bool isInteger = LL.getValueType().isInteger();
3254 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3255 if (Result != ISD::SETCC_INVALID &&
3256 (!LegalOperations ||
3257 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3258 TLI.isOperationLegal(ISD::SETCC,
3259 getSetCCResultType(N0.getValueType())))))
3260 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3265 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3266 if (N0.getOpcode() == N1.getOpcode()) {
3267 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3268 if (Tmp.getNode()) return Tmp;
3271 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3272 if (N0.getOpcode() == ISD::AND &&
3273 N1.getOpcode() == ISD::AND &&
3274 N0.getOperand(1).getOpcode() == ISD::Constant &&
3275 N1.getOperand(1).getOpcode() == ISD::Constant &&
3276 // Don't increase # computations.
3277 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3278 // We can only do this xform if we know that bits from X that are set in C2
3279 // but not in C1 are already zero. Likewise for Y.
3280 const APInt &LHSMask =
3281 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3282 const APInt &RHSMask =
3283 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3285 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3286 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3287 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3288 N0.getOperand(0), N1.getOperand(0));
3289 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3290 DAG.getConstant(LHSMask | RHSMask, VT));
3294 // See if this is some rotate idiom.
3295 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3296 return SDValue(Rot, 0);
3298 // Simplify the operands using demanded-bits information.
3299 if (!VT.isVector() &&
3300 SimplifyDemandedBits(SDValue(N, 0)))
3301 return SDValue(N, 0);
3306 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3307 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3308 if (Op.getOpcode() == ISD::AND) {
3309 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3310 Mask = Op.getOperand(1);
3311 Op = Op.getOperand(0);
3317 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3325 // Return true if we can prove that, whenever Neg and Pos are both in the
3326 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3327 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3329 // (or (shift1 X, Neg), (shift2 X, Pos))
3331 // reduces to a rotate in direction shift2 by Pos and a rotate in direction
3332 // shift1 by Neg. The range [0, OpSize) means that we only need to consider
3333 // shift amounts with defined behavior.
3334 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3335 // If OpSize is a power of 2 then:
3337 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3338 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3340 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3341 // for the stronger condition:
3343 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3345 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3346 // we can just replace Neg with Neg' for the rest of the function.
3348 // In other cases we check for the even stronger condition:
3350 // Neg == OpSize - Pos [B]
3352 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3353 // behavior if Pos == 0 (and consequently Neg == OpSize).
3355 // We could actually use [A] whenever OpSize is a power of 2, but the
3356 // only extra cases that it would match are those uninteresting ones
3357 // where Neg and Pos are never in range at the same time. E.g. for
3358 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3359 // as well as (sub 32, Pos), but:
3361 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3363 // always invokes undefined behavior for 32-bit X.
3365 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3366 unsigned LoBits = 0;
3367 if (Neg.getOpcode() == ISD::AND &&
3368 isPowerOf2_64(OpSize) &&
3369 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3370 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3371 Neg = Neg.getOperand(0);
3372 LoBits = Log2_64(OpSize);
3375 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3376 if (Neg.getOpcode() != ISD::SUB)
3378 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3381 SDValue NegOp1 = Neg.getOperand(1);
3383 // The condition we need is now:
3385 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3387 // If NegOp1 == Pos then we need:
3389 // OpSize & Mask == NegC & Mask
3391 // (because "x & Mask" is a truncation and distributes through subtraction).
3394 Width = NegC->getAPIntValue();
3395 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3396 // Then the condition we want to prove becomes:
3398 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3400 // which, again because "x & Mask" is a truncation, becomes:
3402 // NegC & Mask == (OpSize - PosC) & Mask
3403 // OpSize & Mask == (NegC + PosC) & Mask
3404 else if (Pos.getOpcode() == ISD::ADD &&
3405 Pos.getOperand(0) == NegOp1 &&
3406 Pos.getOperand(1).getOpcode() == ISD::Constant)
3407 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3408 NegC->getAPIntValue());
3412 // Now we just need to check that OpSize & Mask == Width & Mask.
3414 return Width.getLoBits(LoBits) == 0;
3415 return Width == OpSize;
3418 // A subroutine of MatchRotate used once we have found an OR of two opposite
3419 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3420 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3421 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3422 // Neg with outer conversions stripped away.
3423 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3424 SDValue Neg, SDValue InnerPos,
3425 SDValue InnerNeg, unsigned PosOpcode,
3426 unsigned NegOpcode, SDLoc DL) {
3427 // fold (or (shl x, (*ext y)),
3428 // (srl x, (*ext (sub 32, y)))) ->
3429 // (rotl x, y) or (rotr x, (sub 32, y))
3431 // fold (or (shl x, (*ext (sub 32, y))),
3432 // (srl x, (*ext y))) ->
3433 // (rotr x, y) or (rotl x, (sub 32, y))
3434 EVT VT = Shifted.getValueType();
3435 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3436 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3437 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3438 HasPos ? Pos : Neg).getNode();
3441 // fold (or (shl (*ext x), (*ext y)),
3442 // (srl (*ext x), (*ext (sub 32, y)))) ->
3443 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3445 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3446 // (srl (*ext x), (*ext y))) ->
3447 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3448 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3449 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3450 SDValue InnerShifted = Shifted.getOperand(0);
3451 EVT InnerVT = InnerShifted.getValueType();
3452 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3453 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3454 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3455 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3456 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3457 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3465 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3466 // idioms for rotate, and if the target supports rotation instructions, generate
3468 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3469 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3470 EVT VT = LHS.getValueType();
3471 if (!TLI.isTypeLegal(VT)) return 0;
3473 // The target must have at least one rotate flavor.
3474 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3475 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3476 if (!HasROTL && !HasROTR) return 0;
3478 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3479 SDValue LHSShift; // The shift.
3480 SDValue LHSMask; // AND value if any.
3481 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3482 return 0; // Not part of a rotate.
3484 SDValue RHSShift; // The shift.
3485 SDValue RHSMask; // AND value if any.
3486 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3487 return 0; // Not part of a rotate.
3489 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3490 return 0; // Not shifting the same value.
3492 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3493 return 0; // Shifts must disagree.
3495 // Canonicalize shl to left side in a shl/srl pair.
3496 if (RHSShift.getOpcode() == ISD::SHL) {
3497 std::swap(LHS, RHS);
3498 std::swap(LHSShift, RHSShift);
3499 std::swap(LHSMask , RHSMask );
3502 unsigned OpSizeInBits = VT.getSizeInBits();
3503 SDValue LHSShiftArg = LHSShift.getOperand(0);
3504 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3505 SDValue RHSShiftArg = RHSShift.getOperand(0);
3506 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3508 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3509 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3510 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3511 RHSShiftAmt.getOpcode() == ISD::Constant) {
3512 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3513 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3514 if ((LShVal + RShVal) != OpSizeInBits)
3517 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3518 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3520 // If there is an AND of either shifted operand, apply it to the result.
3521 if (LHSMask.getNode() || RHSMask.getNode()) {
3522 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3524 if (LHSMask.getNode()) {
3525 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3526 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3528 if (RHSMask.getNode()) {
3529 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3530 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3533 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3536 return Rot.getNode();
3539 // If there is a mask here, and we have a variable shift, we can't be sure
3540 // that we're masking out the right stuff.
3541 if (LHSMask.getNode() || RHSMask.getNode())
3544 // If the shift amount is sign/zext/any-extended just peel it off.
3545 SDValue LExtOp0 = LHSShiftAmt;
3546 SDValue RExtOp0 = RHSShiftAmt;
3547 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3548 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3549 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3550 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3551 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3552 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3553 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3554 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3555 LExtOp0 = LHSShiftAmt.getOperand(0);
3556 RExtOp0 = RHSShiftAmt.getOperand(0);
3559 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3560 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3564 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3565 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3572 SDValue DAGCombiner::visitXOR(SDNode *N) {
3573 SDValue N0 = N->getOperand(0);
3574 SDValue N1 = N->getOperand(1);
3575 SDValue LHS, RHS, CC;
3576 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3577 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3578 EVT VT = N0.getValueType();
3581 if (VT.isVector()) {
3582 SDValue FoldedVOp = SimplifyVBinOp(N);
3583 if (FoldedVOp.getNode()) return FoldedVOp;
3585 // fold (xor x, 0) -> x, vector edition
3586 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3588 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3592 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3593 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3594 return DAG.getConstant(0, VT);
3595 // fold (xor x, undef) -> undef
3596 if (N0.getOpcode() == ISD::UNDEF)
3598 if (N1.getOpcode() == ISD::UNDEF)
3600 // fold (xor c1, c2) -> c1^c2
3602 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3603 // canonicalize constant to RHS
3605 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3606 // fold (xor x, 0) -> x
3607 if (N1C && N1C->isNullValue())
3610 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3611 if (RXOR.getNode() != 0)
3614 // fold !(x cc y) -> (x !cc y)
3615 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3616 bool isInt = LHS.getValueType().isInteger();
3617 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3620 if (!LegalOperations ||
3621 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3622 switch (N0.getOpcode()) {
3624 llvm_unreachable("Unhandled SetCC Equivalent!");
3626 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3627 case ISD::SELECT_CC:
3628 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3629 N0.getOperand(3), NotCC);
3634 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3635 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3636 N0.getNode()->hasOneUse() &&
3637 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3638 SDValue V = N0.getOperand(0);
3639 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3640 DAG.getConstant(1, V.getValueType()));
3641 AddToWorkList(V.getNode());
3642 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3645 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3646 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3647 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3648 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3649 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3650 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3651 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3652 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3653 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3654 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3657 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3658 if (N1C && N1C->isAllOnesValue() &&
3659 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3660 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3661 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3662 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3663 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3664 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3665 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3666 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3669 // fold (xor (and x, y), y) -> (and (not x), y)
3670 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3671 N0->getOperand(1) == N1) {
3672 SDValue X = N0->getOperand(0);
3673 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3674 AddToWorkList(NotX.getNode());
3675 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3677 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3678 if (N1C && N0.getOpcode() == ISD::XOR) {
3679 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3680 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3682 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3683 DAG.getConstant(N1C->getAPIntValue() ^
3684 N00C->getAPIntValue(), VT));
3686 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3687 DAG.getConstant(N1C->getAPIntValue() ^
3688 N01C->getAPIntValue(), VT));
3690 // fold (xor x, x) -> 0
3692 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3694 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3695 if (N0.getOpcode() == N1.getOpcode()) {
3696 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3697 if (Tmp.getNode()) return Tmp;
3700 // Simplify the expression using non-local knowledge.
3701 if (!VT.isVector() &&
3702 SimplifyDemandedBits(SDValue(N, 0)))
3703 return SDValue(N, 0);
3708 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3709 /// the shift amount is a constant.
3710 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3711 SDNode *LHS = N->getOperand(0).getNode();
3712 if (!LHS->hasOneUse()) return SDValue();
3714 // We want to pull some binops through shifts, so that we have (and (shift))
3715 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3716 // thing happens with address calculations, so it's important to canonicalize
3718 bool HighBitSet = false; // Can we transform this if the high bit is set?
3720 switch (LHS->getOpcode()) {
3721 default: return SDValue();
3724 HighBitSet = false; // We can only transform sra if the high bit is clear.
3727 HighBitSet = true; // We can only transform sra if the high bit is set.
3730 if (N->getOpcode() != ISD::SHL)
3731 return SDValue(); // only shl(add) not sr[al](add).
3732 HighBitSet = false; // We can only transform sra if the high bit is clear.
3736 // We require the RHS of the binop to be a constant as well.
3737 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3738 if (!BinOpCst) return SDValue();
3740 // FIXME: disable this unless the input to the binop is a shift by a constant.
3741 // If it is not a shift, it pessimizes some common cases like:
3743 // void foo(int *X, int i) { X[i & 1235] = 1; }
3744 // int bar(int *X, int i) { return X[i & 255]; }
3745 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3746 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3747 BinOpLHSVal->getOpcode() != ISD::SRA &&
3748 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3749 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3752 EVT VT = N->getValueType(0);
3754 // If this is a signed shift right, and the high bit is modified by the
3755 // logical operation, do not perform the transformation. The highBitSet
3756 // boolean indicates the value of the high bit of the constant which would
3757 // cause it to be modified for this operation.
3758 if (N->getOpcode() == ISD::SRA) {
3759 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3760 if (BinOpRHSSignSet != HighBitSet)
3764 // Fold the constants, shifting the binop RHS by the shift amount.
3765 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3767 LHS->getOperand(1), N->getOperand(1));
3769 // Create the new shift.
3770 SDValue NewShift = DAG.getNode(N->getOpcode(),
3771 SDLoc(LHS->getOperand(0)),
3772 VT, LHS->getOperand(0), N->getOperand(1));
3774 // Create the new binop.
3775 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3778 SDValue DAGCombiner::visitSHL(SDNode *N) {
3779 SDValue N0 = N->getOperand(0);
3780 SDValue N1 = N->getOperand(1);
3781 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3782 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3783 EVT VT = N0.getValueType();
3784 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3787 if (VT.isVector()) {
3788 SDValue FoldedVOp = SimplifyVBinOp(N);
3789 if (FoldedVOp.getNode()) return FoldedVOp;
3792 // fold (shl c1, c2) -> c1<<c2
3794 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3795 // fold (shl 0, x) -> 0
3796 if (N0C && N0C->isNullValue())
3798 // fold (shl x, c >= size(x)) -> undef
3799 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3800 return DAG.getUNDEF(VT);
3801 // fold (shl x, 0) -> x
3802 if (N1C && N1C->isNullValue())
3804 // fold (shl undef, x) -> 0
3805 if (N0.getOpcode() == ISD::UNDEF)
3806 return DAG.getConstant(0, VT);
3807 // if (shl x, c) is known to be zero, return 0
3808 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3809 APInt::getAllOnesValue(OpSizeInBits)))
3810 return DAG.getConstant(0, VT);
3811 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3812 if (N1.getOpcode() == ISD::TRUNCATE &&
3813 N1.getOperand(0).getOpcode() == ISD::AND &&
3814 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3815 SDValue N101 = N1.getOperand(0).getOperand(1);
3816 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3817 EVT TruncVT = N1.getValueType();
3818 SDValue N100 = N1.getOperand(0).getOperand(0);
3819 APInt TruncC = N101C->getAPIntValue();
3820 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3821 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3822 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3823 DAG.getNode(ISD::TRUNCATE,
3826 DAG.getConstant(TruncC, TruncVT)));
3830 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3831 return SDValue(N, 0);
3833 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3834 if (N1C && N0.getOpcode() == ISD::SHL &&
3835 N0.getOperand(1).getOpcode() == ISD::Constant) {
3836 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3837 uint64_t c2 = N1C->getZExtValue();
3838 if (c1 + c2 >= OpSizeInBits)
3839 return DAG.getConstant(0, VT);
3840 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3841 DAG.getConstant(c1 + c2, N1.getValueType()));
3844 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3845 // For this to be valid, the second form must not preserve any of the bits
3846 // that are shifted out by the inner shift in the first form. This means
3847 // the outer shift size must be >= the number of bits added by the ext.
3848 // As a corollary, we don't care what kind of ext it is.
3849 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3850 N0.getOpcode() == ISD::ANY_EXTEND ||
3851 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3852 N0.getOperand(0).getOpcode() == ISD::SHL &&
3853 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3855 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3856 uint64_t c2 = N1C->getZExtValue();
3857 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3858 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3859 if (c2 >= OpSizeInBits - InnerShiftSize) {
3860 if (c1 + c2 >= OpSizeInBits)
3861 return DAG.getConstant(0, VT);
3862 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3863 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3864 N0.getOperand(0)->getOperand(0)),
3865 DAG.getConstant(c1 + c2, N1.getValueType()));
3869 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3870 // Only fold this if the inner zext has no other uses to avoid increasing
3871 // the total number of instructions.
3872 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3873 N0.getOperand(0).getOpcode() == ISD::SRL &&
3874 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3876 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3877 if (c1 < VT.getSizeInBits()) {
3878 uint64_t c2 = N1C->getZExtValue();
3880 SDValue NewOp0 = N0.getOperand(0);
3881 EVT CountVT = NewOp0.getOperand(1).getValueType();
3882 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3883 NewOp0, DAG.getConstant(c2, CountVT));
3884 AddToWorkList(NewSHL.getNode());
3885 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3890 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3891 // (and (srl x, (sub c1, c2), MASK)
3892 // Only fold this if the inner shift has no other uses -- if it does, folding
3893 // this will increase the total number of instructions.
3894 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3895 N0.getOperand(1).getOpcode() == ISD::Constant) {
3896 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3897 if (c1 < VT.getSizeInBits()) {
3898 uint64_t c2 = N1C->getZExtValue();
3899 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3900 VT.getSizeInBits() - c1);
3903 Mask = Mask.shl(c2-c1);
3904 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3905 DAG.getConstant(c2-c1, N1.getValueType()));
3907 Mask = Mask.lshr(c1-c2);
3908 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3909 DAG.getConstant(c1-c2, N1.getValueType()));
3911 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3912 DAG.getConstant(Mask, VT));
3915 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3916 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3917 SDValue HiBitsMask =
3918 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3919 VT.getSizeInBits() -
3920 N1C->getZExtValue()),
3922 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3927 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3928 if (NewSHL.getNode())
3935 SDValue DAGCombiner::visitSRA(SDNode *N) {
3936 SDValue N0 = N->getOperand(0);
3937 SDValue N1 = N->getOperand(1);
3938 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3939 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3940 EVT VT = N0.getValueType();
3941 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3944 if (VT.isVector()) {
3945 SDValue FoldedVOp = SimplifyVBinOp(N);
3946 if (FoldedVOp.getNode()) return FoldedVOp;
3949 // fold (sra c1, c2) -> (sra c1, c2)
3951 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3952 // fold (sra 0, x) -> 0
3953 if (N0C && N0C->isNullValue())
3955 // fold (sra -1, x) -> -1
3956 if (N0C && N0C->isAllOnesValue())
3958 // fold (sra x, (setge c, size(x))) -> undef
3959 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3960 return DAG.getUNDEF(VT);
3961 // fold (sra x, 0) -> x
3962 if (N1C && N1C->isNullValue())
3964 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3966 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3967 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3968 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3970 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3971 ExtVT, VT.getVectorNumElements());
3972 if ((!LegalOperations ||
3973 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3974 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3975 N0.getOperand(0), DAG.getValueType(ExtVT));
3978 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3979 if (N1C && N0.getOpcode() == ISD::SRA) {
3980 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3981 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3982 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3983 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3984 DAG.getConstant(Sum, N1C->getValueType(0)));
3988 // fold (sra (shl X, m), (sub result_size, n))
3989 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3990 // result_size - n != m.
3991 // If truncate is free for the target sext(shl) is likely to result in better
3993 if (N0.getOpcode() == ISD::SHL) {
3994 // Get the two constanst of the shifts, CN0 = m, CN = n.
3995 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3997 // Determine what the truncate's result bitsize and type would be.
3999 EVT::getIntegerVT(*DAG.getContext(),
4000 OpSizeInBits - N1C->getZExtValue());
4001 // Determine the residual right-shift amount.
4002 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4004 // If the shift is not a no-op (in which case this should be just a sign
4005 // extend already), the truncated to type is legal, sign_extend is legal
4006 // on that type, and the truncate to that type is both legal and free,
4007 // perform the transform.
4008 if ((ShiftAmt > 0) &&
4009 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4010 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4011 TLI.isTruncateFree(VT, TruncVT)) {
4013 SDValue Amt = DAG.getConstant(ShiftAmt,
4014 getShiftAmountTy(N0.getOperand(0).getValueType()));
4015 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4016 N0.getOperand(0), Amt);
4017 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4019 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4020 N->getValueType(0), Trunc);
4025 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4026 if (N1.getOpcode() == ISD::TRUNCATE &&
4027 N1.getOperand(0).getOpcode() == ISD::AND &&
4028 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4029 SDValue N101 = N1.getOperand(0).getOperand(1);
4030 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4031 EVT TruncVT = N1.getValueType();
4032 SDValue N100 = N1.getOperand(0).getOperand(0);
4033 APInt TruncC = N101C->getAPIntValue();
4034 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
4035 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
4036 DAG.getNode(ISD::AND, SDLoc(N),
4038 DAG.getNode(ISD::TRUNCATE,
4041 DAG.getConstant(TruncC, TruncVT)));
4045 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4046 // if c1 is equal to the number of bits the trunc removes
4047 if (N0.getOpcode() == ISD::TRUNCATE &&
4048 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4049 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4050 N0.getOperand(0).hasOneUse() &&
4051 N0.getOperand(0).getOperand(1).hasOneUse() &&
4052 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4053 EVT LargeVT = N0.getOperand(0).getValueType();
4054 ConstantSDNode *LargeShiftAmt =
4055 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4057 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4058 LargeShiftAmt->getZExtValue()) {
4060 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
4061 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
4062 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4063 N0.getOperand(0).getOperand(0), Amt);
4064 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4068 // Simplify, based on bits shifted out of the LHS.
4069 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4070 return SDValue(N, 0);
4073 // If the sign bit is known to be zero, switch this to a SRL.
4074 if (DAG.SignBitIsZero(N0))
4075 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4078 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4079 if (NewSRA.getNode())
4086 SDValue DAGCombiner::visitSRL(SDNode *N) {
4087 SDValue N0 = N->getOperand(0);
4088 SDValue N1 = N->getOperand(1);
4089 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4090 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4091 EVT VT = N0.getValueType();
4092 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4095 if (VT.isVector()) {
4096 SDValue FoldedVOp = SimplifyVBinOp(N);
4097 if (FoldedVOp.getNode()) return FoldedVOp;
4100 // fold (srl c1, c2) -> c1 >>u c2
4102 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4103 // fold (srl 0, x) -> 0
4104 if (N0C && N0C->isNullValue())
4106 // fold (srl x, c >= size(x)) -> undef
4107 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4108 return DAG.getUNDEF(VT);
4109 // fold (srl x, 0) -> x
4110 if (N1C && N1C->isNullValue())
4112 // if (srl x, c) is known to be zero, return 0
4113 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4114 APInt::getAllOnesValue(OpSizeInBits)))
4115 return DAG.getConstant(0, VT);
4117 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4118 if (N1C && N0.getOpcode() == ISD::SRL &&
4119 N0.getOperand(1).getOpcode() == ISD::Constant) {
4120 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4121 uint64_t c2 = N1C->getZExtValue();
4122 if (c1 + c2 >= OpSizeInBits)
4123 return DAG.getConstant(0, VT);
4124 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4125 DAG.getConstant(c1 + c2, N1.getValueType()));
4128 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4129 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4130 N0.getOperand(0).getOpcode() == ISD::SRL &&
4131 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4133 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4134 uint64_t c2 = N1C->getZExtValue();
4135 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4136 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4137 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4138 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4139 if (c1 + OpSizeInBits == InnerShiftSize) {
4140 if (c1 + c2 >= InnerShiftSize)
4141 return DAG.getConstant(0, VT);
4142 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4143 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4144 N0.getOperand(0)->getOperand(0),
4145 DAG.getConstant(c1 + c2, ShiftCountVT)));
4149 // fold (srl (shl x, c), c) -> (and x, cst2)
4150 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4151 N0.getValueSizeInBits() <= 64) {
4152 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4153 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4154 DAG.getConstant(~0ULL >> ShAmt, VT));
4157 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4158 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4159 // Shifting in all undef bits?
4160 EVT SmallVT = N0.getOperand(0).getValueType();
4161 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4162 return DAG.getUNDEF(VT);
4164 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4165 uint64_t ShiftAmt = N1C->getZExtValue();
4166 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4168 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4169 AddToWorkList(SmallShift.getNode());
4170 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4171 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4172 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4173 DAG.getConstant(Mask, VT));
4177 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4178 // bit, which is unmodified by sra.
4179 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4180 if (N0.getOpcode() == ISD::SRA)
4181 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4184 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4185 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4186 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4187 APInt KnownZero, KnownOne;
4188 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4190 // If any of the input bits are KnownOne, then the input couldn't be all
4191 // zeros, thus the result of the srl will always be zero.
4192 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4194 // If all of the bits input the to ctlz node are known to be zero, then
4195 // the result of the ctlz is "32" and the result of the shift is one.
4196 APInt UnknownBits = ~KnownZero;
4197 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4199 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4200 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4201 // Okay, we know that only that the single bit specified by UnknownBits
4202 // could be set on input to the CTLZ node. If this bit is set, the SRL
4203 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4204 // to an SRL/XOR pair, which is likely to simplify more.
4205 unsigned ShAmt = UnknownBits.countTrailingZeros();
4206 SDValue Op = N0.getOperand(0);
4209 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4210 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4211 AddToWorkList(Op.getNode());
4214 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4215 Op, DAG.getConstant(1, VT));
4219 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4220 if (N1.getOpcode() == ISD::TRUNCATE &&
4221 N1.getOperand(0).getOpcode() == ISD::AND &&
4222 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4223 SDValue N101 = N1.getOperand(0).getOperand(1);
4224 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4225 EVT TruncVT = N1.getValueType();
4226 SDValue N100 = N1.getOperand(0).getOperand(0);
4227 APInt TruncC = N101C->getAPIntValue();
4228 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4229 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4230 DAG.getNode(ISD::AND, SDLoc(N),
4232 DAG.getNode(ISD::TRUNCATE,
4235 DAG.getConstant(TruncC, TruncVT)));
4239 // fold operands of srl based on knowledge that the low bits are not
4241 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4242 return SDValue(N, 0);
4245 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4246 if (NewSRL.getNode())
4250 // Attempt to convert a srl of a load into a narrower zero-extending load.
4251 SDValue NarrowLoad = ReduceLoadWidth(N);
4252 if (NarrowLoad.getNode())
4255 // Here is a common situation. We want to optimize:
4258 // %b = and i32 %a, 2
4259 // %c = srl i32 %b, 1
4260 // brcond i32 %c ...
4266 // %c = setcc eq %b, 0
4269 // However when after the source operand of SRL is optimized into AND, the SRL
4270 // itself may not be optimized further. Look for it and add the BRCOND into
4272 if (N->hasOneUse()) {
4273 SDNode *Use = *N->use_begin();
4274 if (Use->getOpcode() == ISD::BRCOND)
4276 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4277 // Also look pass the truncate.
4278 Use = *Use->use_begin();
4279 if (Use->getOpcode() == ISD::BRCOND)
4287 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4288 SDValue N0 = N->getOperand(0);
4289 EVT VT = N->getValueType(0);
4291 // fold (ctlz c1) -> c2
4292 if (isa<ConstantSDNode>(N0))
4293 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4297 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4298 SDValue N0 = N->getOperand(0);
4299 EVT VT = N->getValueType(0);
4301 // fold (ctlz_zero_undef c1) -> c2
4302 if (isa<ConstantSDNode>(N0))
4303 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4307 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4308 SDValue N0 = N->getOperand(0);
4309 EVT VT = N->getValueType(0);
4311 // fold (cttz c1) -> c2
4312 if (isa<ConstantSDNode>(N0))
4313 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4317 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4318 SDValue N0 = N->getOperand(0);
4319 EVT VT = N->getValueType(0);
4321 // fold (cttz_zero_undef c1) -> c2
4322 if (isa<ConstantSDNode>(N0))
4323 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4327 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4328 SDValue N0 = N->getOperand(0);
4329 EVT VT = N->getValueType(0);
4331 // fold (ctpop c1) -> c2
4332 if (isa<ConstantSDNode>(N0))
4333 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4337 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4338 SDValue N0 = N->getOperand(0);
4339 SDValue N1 = N->getOperand(1);
4340 SDValue N2 = N->getOperand(2);
4341 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4342 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4343 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4344 EVT VT = N->getValueType(0);
4345 EVT VT0 = N0.getValueType();
4347 // fold (select C, X, X) -> X
4350 // fold (select true, X, Y) -> X
4351 if (N0C && !N0C->isNullValue())
4353 // fold (select false, X, Y) -> Y
4354 if (N0C && N0C->isNullValue())
4356 // fold (select C, 1, X) -> (or C, X)
4357 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4358 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4359 // fold (select C, 0, 1) -> (xor C, 1)
4360 if (VT.isInteger() &&
4363 TLI.getBooleanContents(false) ==
4364 TargetLowering::ZeroOrOneBooleanContent)) &&
4365 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4368 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4369 N0, DAG.getConstant(1, VT0));
4370 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4371 N0, DAG.getConstant(1, VT0));
4372 AddToWorkList(XORNode.getNode());
4374 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4375 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4377 // fold (select C, 0, X) -> (and (not C), X)
4378 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4379 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4380 AddToWorkList(NOTNode.getNode());
4381 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4383 // fold (select C, X, 1) -> (or (not C), X)
4384 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4385 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4386 AddToWorkList(NOTNode.getNode());
4387 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4389 // fold (select C, X, 0) -> (and C, X)
4390 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4391 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4392 // fold (select X, X, Y) -> (or X, Y)
4393 // fold (select X, 1, Y) -> (or X, Y)
4394 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4395 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4396 // fold (select X, Y, X) -> (and X, Y)
4397 // fold (select X, Y, 0) -> (and X, Y)
4398 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4399 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4401 // If we can fold this based on the true/false value, do so.
4402 if (SimplifySelectOps(N, N1, N2))
4403 return SDValue(N, 0); // Don't revisit N.
4405 // fold selects based on a setcc into other things, such as min/max/abs
4406 if (N0.getOpcode() == ISD::SETCC) {
4408 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4409 // having to say they don't support SELECT_CC on every type the DAG knows
4410 // about, since there is no way to mark an opcode illegal at all value types
4411 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4412 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4413 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4414 N0.getOperand(0), N0.getOperand(1),
4415 N1, N2, N0.getOperand(2));
4416 return SimplifySelect(SDLoc(N), N0, N1, N2);
4423 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4426 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4428 // Split the inputs.
4429 SDValue Lo, Hi, LL, LH, RL, RH;
4430 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4431 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4433 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4434 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4436 return std::make_pair(Lo, Hi);
4439 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4440 SDValue N0 = N->getOperand(0);
4441 SDValue N1 = N->getOperand(1);
4442 SDValue N2 = N->getOperand(2);
4445 // Canonicalize integer abs.
4446 // vselect (setg[te] X, 0), X, -X ->
4447 // vselect (setgt X, -1), X, -X ->
4448 // vselect (setl[te] X, 0), -X, X ->
4449 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4450 if (N0.getOpcode() == ISD::SETCC) {
4451 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4452 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4454 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4456 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4457 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4458 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4459 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4460 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4461 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4462 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4465 EVT VT = LHS.getValueType();
4466 SDValue Shift = DAG.getNode(
4467 ISD::SRA, DL, VT, LHS,
4468 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4469 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4470 AddToWorkList(Shift.getNode());
4471 AddToWorkList(Add.getNode());
4472 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4476 // If the VSELECT result requires splitting and the mask is provided by a
4477 // SETCC, then split both nodes and its operands before legalization. This
4478 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4479 // and enables future optimizations (e.g. min/max pattern matching on X86).
4480 if (N0.getOpcode() == ISD::SETCC) {
4481 EVT VT = N->getValueType(0);
4483 // Check if any splitting is required.
4484 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4485 TargetLowering::TypeSplitVector)
4488 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4489 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4490 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4491 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4493 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4494 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4496 // Add the new VSELECT nodes to the work list in case they need to be split
4498 AddToWorkList(Lo.getNode());
4499 AddToWorkList(Hi.getNode());
4501 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4504 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4505 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4507 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4508 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4514 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4515 SDValue N0 = N->getOperand(0);
4516 SDValue N1 = N->getOperand(1);
4517 SDValue N2 = N->getOperand(2);
4518 SDValue N3 = N->getOperand(3);
4519 SDValue N4 = N->getOperand(4);
4520 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4522 // fold select_cc lhs, rhs, x, x, cc -> x
4526 // Determine if the condition we're dealing with is constant
4527 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4528 N0, N1, CC, SDLoc(N), false);
4529 if (SCC.getNode()) {
4530 AddToWorkList(SCC.getNode());
4532 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4533 if (!SCCC->isNullValue())
4534 return N2; // cond always true -> true val
4536 return N3; // cond always false -> false val
4539 // Fold to a simpler select_cc
4540 if (SCC.getOpcode() == ISD::SETCC)
4541 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4542 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4546 // If we can fold this based on the true/false value, do so.
4547 if (SimplifySelectOps(N, N2, N3))
4548 return SDValue(N, 0); // Don't revisit N.
4550 // fold select_cc into other things, such as min/max/abs
4551 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4554 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4555 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4556 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4560 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4561 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4562 // transformation. Returns true if extension are possible and the above
4563 // mentioned transformation is profitable.
4564 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4566 SmallVectorImpl<SDNode *> &ExtendNodes,
4567 const TargetLowering &TLI) {
4568 bool HasCopyToRegUses = false;
4569 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4570 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4571 UE = N0.getNode()->use_end();
4576 if (UI.getUse().getResNo() != N0.getResNo())
4578 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4579 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4580 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4581 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4582 // Sign bits will be lost after a zext.
4585 for (unsigned i = 0; i != 2; ++i) {
4586 SDValue UseOp = User->getOperand(i);
4589 if (!isa<ConstantSDNode>(UseOp))
4594 ExtendNodes.push_back(User);
4597 // If truncates aren't free and there are users we can't
4598 // extend, it isn't worthwhile.
4601 // Remember if this value is live-out.
4602 if (User->getOpcode() == ISD::CopyToReg)
4603 HasCopyToRegUses = true;
4606 if (HasCopyToRegUses) {
4607 bool BothLiveOut = false;
4608 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4610 SDUse &Use = UI.getUse();
4611 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4617 // Both unextended and extended values are live out. There had better be
4618 // a good reason for the transformation.
4619 return ExtendNodes.size();
4624 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4625 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4626 ISD::NodeType ExtType) {
4627 // Extend SetCC uses if necessary.
4628 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4629 SDNode *SetCC = SetCCs[i];
4630 SmallVector<SDValue, 4> Ops;
4632 for (unsigned j = 0; j != 2; ++j) {
4633 SDValue SOp = SetCC->getOperand(j);
4635 Ops.push_back(ExtLoad);
4637 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4640 Ops.push_back(SetCC->getOperand(2));
4641 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4642 &Ops[0], Ops.size()));
4646 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4647 SDValue N0 = N->getOperand(0);
4648 EVT VT = N->getValueType(0);
4650 // fold (sext c1) -> c1
4651 if (isa<ConstantSDNode>(N0))
4652 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4654 // fold (sext (sext x)) -> (sext x)
4655 // fold (sext (aext x)) -> (sext x)
4656 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4657 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4660 if (N0.getOpcode() == ISD::TRUNCATE) {
4661 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4662 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4663 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4664 if (NarrowLoad.getNode()) {
4665 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4666 if (NarrowLoad.getNode() != N0.getNode()) {
4667 CombineTo(N0.getNode(), NarrowLoad);
4668 // CombineTo deleted the truncate, if needed, but not what's under it.
4671 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4674 // See if the value being truncated is already sign extended. If so, just
4675 // eliminate the trunc/sext pair.
4676 SDValue Op = N0.getOperand(0);
4677 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4678 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4679 unsigned DestBits = VT.getScalarType().getSizeInBits();
4680 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4682 if (OpBits == DestBits) {
4683 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4684 // bits, it is already ready.
4685 if (NumSignBits > DestBits-MidBits)
4687 } else if (OpBits < DestBits) {
4688 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4689 // bits, just sext from i32.
4690 if (NumSignBits > OpBits-MidBits)
4691 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4693 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4694 // bits, just truncate to i32.
4695 if (NumSignBits > OpBits-MidBits)
4696 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4699 // fold (sext (truncate x)) -> (sextinreg x).
4700 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4701 N0.getValueType())) {
4702 if (OpBits < DestBits)
4703 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4704 else if (OpBits > DestBits)
4705 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4706 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4707 DAG.getValueType(N0.getValueType()));
4711 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4712 // None of the supported targets knows how to perform load and sign extend
4713 // on vectors in one instruction. We only perform this transformation on
4715 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4716 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4717 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4718 bool DoXform = true;
4719 SmallVector<SDNode*, 4> SetCCs;
4720 if (!N0.hasOneUse())
4721 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4723 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4724 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4726 LN0->getBasePtr(), N0.getValueType(),
4727 LN0->getMemOperand());
4728 CombineTo(N, ExtLoad);
4729 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4730 N0.getValueType(), ExtLoad);
4731 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4732 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4734 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4738 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4739 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4740 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4741 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4742 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4743 EVT MemVT = LN0->getMemoryVT();
4744 if ((!LegalOperations && !LN0->isVolatile()) ||
4745 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4746 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4748 LN0->getBasePtr(), MemVT,
4749 LN0->getMemOperand());
4750 CombineTo(N, ExtLoad);
4751 CombineTo(N0.getNode(),
4752 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4753 N0.getValueType(), ExtLoad),
4754 ExtLoad.getValue(1));
4755 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4759 // fold (sext (and/or/xor (load x), cst)) ->
4760 // (and/or/xor (sextload x), (sext cst))
4761 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4762 N0.getOpcode() == ISD::XOR) &&
4763 isa<LoadSDNode>(N0.getOperand(0)) &&
4764 N0.getOperand(1).getOpcode() == ISD::Constant &&
4765 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4766 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4767 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4768 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4769 bool DoXform = true;
4770 SmallVector<SDNode*, 4> SetCCs;
4771 if (!N0.hasOneUse())
4772 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4775 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4776 LN0->getChain(), LN0->getBasePtr(),
4778 LN0->getMemOperand());
4779 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4780 Mask = Mask.sext(VT.getSizeInBits());
4781 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4782 ExtLoad, DAG.getConstant(Mask, VT));
4783 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4784 SDLoc(N0.getOperand(0)),
4785 N0.getOperand(0).getValueType(), ExtLoad);
4787 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4788 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4790 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4795 if (N0.getOpcode() == ISD::SETCC) {
4796 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4797 // Only do this before legalize for now.
4798 if (VT.isVector() && !LegalOperations &&
4799 TLI.getBooleanContents(true) ==
4800 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4801 EVT N0VT = N0.getOperand(0).getValueType();
4802 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4803 // of the same size as the compared operands. Only optimize sext(setcc())
4804 // if this is the case.
4805 EVT SVT = getSetCCResultType(N0VT);
4807 // We know that the # elements of the results is the same as the
4808 // # elements of the compare (and the # elements of the compare result
4809 // for that matter). Check to see that they are the same size. If so,
4810 // we know that the element size of the sext'd result matches the
4811 // element size of the compare operands.
4812 if (VT.getSizeInBits() == SVT.getSizeInBits())
4813 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4815 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4817 // If the desired elements are smaller or larger than the source
4818 // elements we can use a matching integer vector type and then
4819 // truncate/sign extend
4820 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4821 if (SVT == MatchingVectorType) {
4822 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4823 N0.getOperand(0), N0.getOperand(1),
4824 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4825 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4829 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4830 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4832 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4834 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4835 NegOne, DAG.getConstant(0, VT),
4836 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4837 if (SCC.getNode()) return SCC;
4838 if (!VT.isVector() &&
4839 (!LegalOperations ||
4840 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4841 return DAG.getSelect(SDLoc(N), VT,
4842 DAG.getSetCC(SDLoc(N),
4843 getSetCCResultType(VT),
4844 N0.getOperand(0), N0.getOperand(1),
4845 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4846 NegOne, DAG.getConstant(0, VT));
4850 // fold (sext x) -> (zext x) if the sign bit is known zero.
4851 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4852 DAG.SignBitIsZero(N0))
4853 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4858 // isTruncateOf - If N is a truncate of some other value, return true, record
4859 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4860 // This function computes KnownZero to avoid a duplicated call to
4861 // ComputeMaskedBits in the caller.
4862 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4865 if (N->getOpcode() == ISD::TRUNCATE) {
4866 Op = N->getOperand(0);
4867 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4871 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4872 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4875 SDValue Op0 = N->getOperand(0);
4876 SDValue Op1 = N->getOperand(1);
4877 assert(Op0.getValueType() == Op1.getValueType());
4879 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4880 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4881 if (COp0 && COp0->isNullValue())
4883 else if (COp1 && COp1->isNullValue())
4888 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4890 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4896 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4897 SDValue N0 = N->getOperand(0);
4898 EVT VT = N->getValueType(0);
4900 // fold (zext c1) -> c1
4901 if (isa<ConstantSDNode>(N0))
4902 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4903 // fold (zext (zext x)) -> (zext x)
4904 // fold (zext (aext x)) -> (zext x)
4905 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4906 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4909 // fold (zext (truncate x)) -> (zext x) or
4910 // (zext (truncate x)) -> (truncate x)
4911 // This is valid when the truncated bits of x are already zero.
4912 // FIXME: We should extend this to work for vectors too.
4915 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4916 APInt TruncatedBits =
4917 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4918 APInt(Op.getValueSizeInBits(), 0) :
4919 APInt::getBitsSet(Op.getValueSizeInBits(),
4920 N0.getValueSizeInBits(),
4921 std::min(Op.getValueSizeInBits(),
4922 VT.getSizeInBits()));
4923 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4924 if (VT.bitsGT(Op.getValueType()))
4925 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4926 if (VT.bitsLT(Op.getValueType()))
4927 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4933 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4934 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4935 if (N0.getOpcode() == ISD::TRUNCATE) {
4936 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4937 if (NarrowLoad.getNode()) {
4938 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4939 if (NarrowLoad.getNode() != N0.getNode()) {
4940 CombineTo(N0.getNode(), NarrowLoad);
4941 // CombineTo deleted the truncate, if needed, but not what's under it.
4944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4948 // fold (zext (truncate x)) -> (and x, mask)
4949 if (N0.getOpcode() == ISD::TRUNCATE &&
4950 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4952 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4953 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4954 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4955 if (NarrowLoad.getNode()) {
4956 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4957 if (NarrowLoad.getNode() != N0.getNode()) {
4958 CombineTo(N0.getNode(), NarrowLoad);
4959 // CombineTo deleted the truncate, if needed, but not what's under it.
4962 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4965 SDValue Op = N0.getOperand(0);
4966 if (Op.getValueType().bitsLT(VT)) {
4967 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4968 AddToWorkList(Op.getNode());
4969 } else if (Op.getValueType().bitsGT(VT)) {
4970 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4971 AddToWorkList(Op.getNode());
4973 return DAG.getZeroExtendInReg(Op, SDLoc(N),
4974 N0.getValueType().getScalarType());
4977 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4978 // if either of the casts is not free.
4979 if (N0.getOpcode() == ISD::AND &&
4980 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4981 N0.getOperand(1).getOpcode() == ISD::Constant &&
4982 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4983 N0.getValueType()) ||
4984 !TLI.isZExtFree(N0.getValueType(), VT))) {
4985 SDValue X = N0.getOperand(0).getOperand(0);
4986 if (X.getValueType().bitsLT(VT)) {
4987 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4988 } else if (X.getValueType().bitsGT(VT)) {
4989 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4991 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4992 Mask = Mask.zext(VT.getSizeInBits());
4993 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4994 X, DAG.getConstant(Mask, VT));
4997 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4998 // None of the supported targets knows how to perform load and vector_zext
4999 // on vectors in one instruction. We only perform this transformation on
5001 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5002 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5003 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5004 bool DoXform = true;
5005 SmallVector<SDNode*, 4> SetCCs;
5006 if (!N0.hasOneUse())
5007 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5009 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5010 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5012 LN0->getBasePtr(), N0.getValueType(),
5013 LN0->getMemOperand());
5014 CombineTo(N, ExtLoad);
5015 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5016 N0.getValueType(), ExtLoad);
5017 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5019 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5021 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5025 // fold (zext (and/or/xor (load x), cst)) ->
5026 // (and/or/xor (zextload x), (zext cst))
5027 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5028 N0.getOpcode() == ISD::XOR) &&
5029 isa<LoadSDNode>(N0.getOperand(0)) &&
5030 N0.getOperand(1).getOpcode() == ISD::Constant &&
5031 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5032 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5033 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5034 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5035 bool DoXform = true;
5036 SmallVector<SDNode*, 4> SetCCs;
5037 if (!N0.hasOneUse())
5038 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5041 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5042 LN0->getChain(), LN0->getBasePtr(),
5044 LN0->getMemOperand());
5045 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5046 Mask = Mask.zext(VT.getSizeInBits());
5047 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5048 ExtLoad, DAG.getConstant(Mask, VT));
5049 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5050 SDLoc(N0.getOperand(0)),
5051 N0.getOperand(0).getValueType(), ExtLoad);
5053 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5054 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5056 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5061 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5062 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5063 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5064 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5065 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5066 EVT MemVT = LN0->getMemoryVT();
5067 if ((!LegalOperations && !LN0->isVolatile()) ||
5068 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5069 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5071 LN0->getBasePtr(), MemVT,
5072 LN0->getMemOperand());
5073 CombineTo(N, ExtLoad);
5074 CombineTo(N0.getNode(),
5075 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5077 ExtLoad.getValue(1));
5078 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5082 if (N0.getOpcode() == ISD::SETCC) {
5083 if (!LegalOperations && VT.isVector() &&
5084 N0.getValueType().getVectorElementType() == MVT::i1) {
5085 EVT N0VT = N0.getOperand(0).getValueType();
5086 if (getSetCCResultType(N0VT) == N0.getValueType())
5089 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5090 // Only do this before legalize for now.
5091 EVT EltVT = VT.getVectorElementType();
5092 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5093 DAG.getConstant(1, EltVT));
5094 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5095 // We know that the # elements of the results is the same as the
5096 // # elements of the compare (and the # elements of the compare result
5097 // for that matter). Check to see that they are the same size. If so,
5098 // we know that the element size of the sext'd result matches the
5099 // element size of the compare operands.
5100 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5101 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5103 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5104 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5105 &OneOps[0], OneOps.size()));
5107 // If the desired elements are smaller or larger than the source
5108 // elements we can use a matching integer vector type and then
5109 // truncate/sign extend
5110 EVT MatchingElementType =
5111 EVT::getIntegerVT(*DAG.getContext(),
5112 N0VT.getScalarType().getSizeInBits());
5113 EVT MatchingVectorType =
5114 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5115 N0VT.getVectorNumElements());
5117 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5119 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5120 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5121 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5122 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5123 &OneOps[0], OneOps.size()));
5126 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5128 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5129 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5130 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5131 if (SCC.getNode()) return SCC;
5134 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5135 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5136 isa<ConstantSDNode>(N0.getOperand(1)) &&
5137 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5139 SDValue ShAmt = N0.getOperand(1);
5140 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5141 if (N0.getOpcode() == ISD::SHL) {
5142 SDValue InnerZExt = N0.getOperand(0);
5143 // If the original shl may be shifting out bits, do not perform this
5145 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5146 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5147 if (ShAmtVal > KnownZeroBits)
5153 // Ensure that the shift amount is wide enough for the shifted value.
5154 if (VT.getSizeInBits() >= 256)
5155 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5157 return DAG.getNode(N0.getOpcode(), DL, VT,
5158 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5165 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5166 SDValue N0 = N->getOperand(0);
5167 EVT VT = N->getValueType(0);
5169 // fold (aext c1) -> c1
5170 if (isa<ConstantSDNode>(N0))
5171 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5172 // fold (aext (aext x)) -> (aext x)
5173 // fold (aext (zext x)) -> (zext x)
5174 // fold (aext (sext x)) -> (sext x)
5175 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5176 N0.getOpcode() == ISD::ZERO_EXTEND ||
5177 N0.getOpcode() == ISD::SIGN_EXTEND)
5178 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5180 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5181 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5182 if (N0.getOpcode() == ISD::TRUNCATE) {
5183 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5184 if (NarrowLoad.getNode()) {
5185 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5186 if (NarrowLoad.getNode() != N0.getNode()) {
5187 CombineTo(N0.getNode(), NarrowLoad);
5188 // CombineTo deleted the truncate, if needed, but not what's under it.
5191 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5195 // fold (aext (truncate x))
5196 if (N0.getOpcode() == ISD::TRUNCATE) {
5197 SDValue TruncOp = N0.getOperand(0);
5198 if (TruncOp.getValueType() == VT)
5199 return TruncOp; // x iff x size == zext size.
5200 if (TruncOp.getValueType().bitsGT(VT))
5201 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5202 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5205 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5206 // if the trunc is not free.
5207 if (N0.getOpcode() == ISD::AND &&
5208 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5209 N0.getOperand(1).getOpcode() == ISD::Constant &&
5210 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5211 N0.getValueType())) {
5212 SDValue X = N0.getOperand(0).getOperand(0);
5213 if (X.getValueType().bitsLT(VT)) {
5214 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5215 } else if (X.getValueType().bitsGT(VT)) {
5216 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5218 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5219 Mask = Mask.zext(VT.getSizeInBits());
5220 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5221 X, DAG.getConstant(Mask, VT));
5224 // fold (aext (load x)) -> (aext (truncate (extload x)))
5225 // None of the supported targets knows how to perform load and any_ext
5226 // on vectors in one instruction. We only perform this transformation on
5228 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5229 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5230 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5231 bool DoXform = true;
5232 SmallVector<SDNode*, 4> SetCCs;
5233 if (!N0.hasOneUse())
5234 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5236 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5237 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5239 LN0->getBasePtr(), N0.getValueType(),
5240 LN0->getMemOperand());
5241 CombineTo(N, ExtLoad);
5242 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5243 N0.getValueType(), ExtLoad);
5244 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5245 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5247 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5251 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5252 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5253 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5254 if (N0.getOpcode() == ISD::LOAD &&
5255 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5257 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5258 EVT MemVT = LN0->getMemoryVT();
5259 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5260 VT, LN0->getChain(), LN0->getBasePtr(),
5261 MemVT, LN0->getMemOperand());
5262 CombineTo(N, ExtLoad);
5263 CombineTo(N0.getNode(),
5264 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5265 N0.getValueType(), ExtLoad),
5266 ExtLoad.getValue(1));
5267 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5270 if (N0.getOpcode() == ISD::SETCC) {
5271 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5272 // Only do this before legalize for now.
5273 if (VT.isVector() && !LegalOperations) {
5274 EVT N0VT = N0.getOperand(0).getValueType();
5275 // We know that the # elements of the results is the same as the
5276 // # elements of the compare (and the # elements of the compare result
5277 // for that matter). Check to see that they are the same size. If so,
5278 // we know that the element size of the sext'd result matches the
5279 // element size of the compare operands.
5280 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5281 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5283 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5284 // If the desired elements are smaller or larger than the source
5285 // elements we can use a matching integer vector type and then
5286 // truncate/sign extend
5288 EVT MatchingElementType =
5289 EVT::getIntegerVT(*DAG.getContext(),
5290 N0VT.getScalarType().getSizeInBits());
5291 EVT MatchingVectorType =
5292 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5293 N0VT.getVectorNumElements());
5295 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5297 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5298 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5302 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5304 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5305 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5306 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5314 /// GetDemandedBits - See if the specified operand can be simplified with the
5315 /// knowledge that only the bits specified by Mask are used. If so, return the
5316 /// simpler operand, otherwise return a null SDValue.
5317 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5318 switch (V.getOpcode()) {
5320 case ISD::Constant: {
5321 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5322 assert(CV != 0 && "Const value should be ConstSDNode.");
5323 const APInt &CVal = CV->getAPIntValue();
5324 APInt NewVal = CVal & Mask;
5326 return DAG.getConstant(NewVal, V.getValueType());
5331 // If the LHS or RHS don't contribute bits to the or, drop them.
5332 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5333 return V.getOperand(1);
5334 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5335 return V.getOperand(0);
5338 // Only look at single-use SRLs.
5339 if (!V.getNode()->hasOneUse())
5341 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5342 // See if we can recursively simplify the LHS.
5343 unsigned Amt = RHSC->getZExtValue();
5345 // Watch out for shift count overflow though.
5346 if (Amt >= Mask.getBitWidth()) break;
5347 APInt NewMask = Mask << Amt;
5348 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5349 if (SimplifyLHS.getNode())
5350 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5351 SimplifyLHS, V.getOperand(1));
5357 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5358 /// bits and then truncated to a narrower type and where N is a multiple
5359 /// of number of bits of the narrower type, transform it to a narrower load
5360 /// from address + N / num of bits of new type. If the result is to be
5361 /// extended, also fold the extension to form a extending load.
5362 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5363 unsigned Opc = N->getOpcode();
5365 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5366 SDValue N0 = N->getOperand(0);
5367 EVT VT = N->getValueType(0);
5370 // This transformation isn't valid for vector loads.
5374 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5376 if (Opc == ISD::SIGN_EXTEND_INREG) {
5377 ExtType = ISD::SEXTLOAD;
5378 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5379 } else if (Opc == ISD::SRL) {
5380 // Another special-case: SRL is basically zero-extending a narrower value.
5381 ExtType = ISD::ZEXTLOAD;
5383 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5384 if (!N01) return SDValue();
5385 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5386 VT.getSizeInBits() - N01->getZExtValue());
5388 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5391 unsigned EVTBits = ExtVT.getSizeInBits();
5393 // Do not generate loads of non-round integer types since these can
5394 // be expensive (and would be wrong if the type is not byte sized).
5395 if (!ExtVT.isRound())
5399 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5400 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5401 ShAmt = N01->getZExtValue();
5402 // Is the shift amount a multiple of size of VT?
5403 if ((ShAmt & (EVTBits-1)) == 0) {
5404 N0 = N0.getOperand(0);
5405 // Is the load width a multiple of size of VT?
5406 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5410 // At this point, we must have a load or else we can't do the transform.
5411 if (!isa<LoadSDNode>(N0)) return SDValue();
5413 // Because a SRL must be assumed to *need* to zero-extend the high bits
5414 // (as opposed to anyext the high bits), we can't combine the zextload
5415 // lowering of SRL and an sextload.
5416 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5419 // If the shift amount is larger than the input type then we're not
5420 // accessing any of the loaded bytes. If the load was a zextload/extload
5421 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5422 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5427 // If the load is shifted left (and the result isn't shifted back right),
5428 // we can fold the truncate through the shift.
5429 unsigned ShLeftAmt = 0;
5430 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5431 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5432 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5433 ShLeftAmt = N01->getZExtValue();
5434 N0 = N0.getOperand(0);
5438 // If we haven't found a load, we can't narrow it. Don't transform one with
5439 // multiple uses, this would require adding a new load.
5440 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5443 // Don't change the width of a volatile load.
5444 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5445 if (LN0->isVolatile())
5448 // Verify that we are actually reducing a load width here.
5449 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5452 // For the transform to be legal, the load must produce only two values
5453 // (the value loaded and the chain). Don't transform a pre-increment
5454 // load, for example, which produces an extra value. Otherwise the
5455 // transformation is not equivalent, and the downstream logic to replace
5456 // uses gets things wrong.
5457 if (LN0->getNumValues() > 2)
5460 // If the load that we're shrinking is an extload and we're not just
5461 // discarding the extension we can't simply shrink the load. Bail.
5462 // TODO: It would be possible to merge the extensions in some cases.
5463 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5464 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5467 EVT PtrType = N0.getOperand(1).getValueType();
5469 if (PtrType == MVT::Untyped || PtrType.isExtended())
5470 // It's not possible to generate a constant of extended or untyped type.
5473 // For big endian targets, we need to adjust the offset to the pointer to
5474 // load the correct bytes.
5475 if (TLI.isBigEndian()) {
5476 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5477 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5478 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5481 uint64_t PtrOff = ShAmt / 8;
5482 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5483 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5484 PtrType, LN0->getBasePtr(),
5485 DAG.getConstant(PtrOff, PtrType));
5486 AddToWorkList(NewPtr.getNode());
5489 if (ExtType == ISD::NON_EXTLOAD)
5490 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5491 LN0->getPointerInfo().getWithOffset(PtrOff),
5492 LN0->isVolatile(), LN0->isNonTemporal(),
5493 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5495 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5496 LN0->getPointerInfo().getWithOffset(PtrOff),
5497 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5498 NewAlign, LN0->getTBAAInfo());
5500 // Replace the old load's chain with the new load's chain.
5501 WorkListRemover DeadNodes(*this);
5502 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5504 // Shift the result left, if we've swallowed a left shift.
5505 SDValue Result = Load;
5506 if (ShLeftAmt != 0) {
5507 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5508 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5510 // If the shift amount is as large as the result size (but, presumably,
5511 // no larger than the source) then the useful bits of the result are
5512 // zero; we can't simply return the shortened shift, because the result
5513 // of that operation is undefined.
5514 if (ShLeftAmt >= VT.getSizeInBits())
5515 Result = DAG.getConstant(0, VT);
5517 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5518 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5521 // Return the new loaded value.
5525 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5526 SDValue N0 = N->getOperand(0);
5527 SDValue N1 = N->getOperand(1);
5528 EVT VT = N->getValueType(0);
5529 EVT EVT = cast<VTSDNode>(N1)->getVT();
5530 unsigned VTBits = VT.getScalarType().getSizeInBits();
5531 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5533 // fold (sext_in_reg c1) -> c1
5534 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5535 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5537 // If the input is already sign extended, just drop the extension.
5538 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5541 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5542 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5543 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5544 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5545 N0.getOperand(0), N1);
5547 // fold (sext_in_reg (sext x)) -> (sext x)
5548 // fold (sext_in_reg (aext x)) -> (sext x)
5549 // if x is small enough.
5550 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5551 SDValue N00 = N0.getOperand(0);
5552 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5553 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5554 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5557 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5558 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5559 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5561 // fold operands of sext_in_reg based on knowledge that the top bits are not
5563 if (SimplifyDemandedBits(SDValue(N, 0)))
5564 return SDValue(N, 0);
5566 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5567 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5568 SDValue NarrowLoad = ReduceLoadWidth(N);
5569 if (NarrowLoad.getNode())
5572 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5573 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5574 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5575 if (N0.getOpcode() == ISD::SRL) {
5576 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5577 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5578 // We can turn this into an SRA iff the input to the SRL is already sign
5580 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5581 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5582 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5583 N0.getOperand(0), N0.getOperand(1));
5587 // fold (sext_inreg (extload x)) -> (sextload x)
5588 if (ISD::isEXTLoad(N0.getNode()) &&
5589 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5590 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5591 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5592 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5593 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5594 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5596 LN0->getBasePtr(), EVT,
5597 LN0->getMemOperand());
5598 CombineTo(N, ExtLoad);
5599 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5600 AddToWorkList(ExtLoad.getNode());
5601 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5603 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5604 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5606 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5607 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5608 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5609 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5610 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5612 LN0->getBasePtr(), EVT,
5613 LN0->getMemOperand());
5614 CombineTo(N, ExtLoad);
5615 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5616 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5619 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5620 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5621 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5622 N0.getOperand(1), false);
5623 if (BSwap.getNode() != 0)
5624 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5628 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5629 // into a build_vector.
5630 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5631 SmallVector<SDValue, 8> Elts;
5632 unsigned NumElts = N0->getNumOperands();
5633 unsigned ShAmt = VTBits - EVTBits;
5635 for (unsigned i = 0; i != NumElts; ++i) {
5636 SDValue Op = N0->getOperand(i);
5637 if (Op->getOpcode() == ISD::UNDEF) {
5642 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5643 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5644 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5645 Op.getValueType()));
5648 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5654 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5655 SDValue N0 = N->getOperand(0);
5656 EVT VT = N->getValueType(0);
5657 bool isLE = TLI.isLittleEndian();
5660 if (N0.getValueType() == N->getValueType(0))
5662 // fold (truncate c1) -> c1
5663 if (isa<ConstantSDNode>(N0))
5664 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5665 // fold (truncate (truncate x)) -> (truncate x)
5666 if (N0.getOpcode() == ISD::TRUNCATE)
5667 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5668 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5669 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5670 N0.getOpcode() == ISD::SIGN_EXTEND ||
5671 N0.getOpcode() == ISD::ANY_EXTEND) {
5672 if (N0.getOperand(0).getValueType().bitsLT(VT))
5673 // if the source is smaller than the dest, we still need an extend
5674 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5676 if (N0.getOperand(0).getValueType().bitsGT(VT))
5677 // if the source is larger than the dest, than we just need the truncate
5678 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5679 // if the source and dest are the same type, we can drop both the extend
5680 // and the truncate.
5681 return N0.getOperand(0);
5684 // Fold extract-and-trunc into a narrow extract. For example:
5685 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5686 // i32 y = TRUNCATE(i64 x)
5688 // v16i8 b = BITCAST (v2i64 val)
5689 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5691 // Note: We only run this optimization after type legalization (which often
5692 // creates this pattern) and before operation legalization after which
5693 // we need to be more careful about the vector instructions that we generate.
5694 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5695 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5697 EVT VecTy = N0.getOperand(0).getValueType();
5698 EVT ExTy = N0.getValueType();
5699 EVT TrTy = N->getValueType(0);
5701 unsigned NumElem = VecTy.getVectorNumElements();
5702 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5704 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5705 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5707 SDValue EltNo = N0->getOperand(1);
5708 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5709 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5710 EVT IndexTy = TLI.getVectorIdxTy();
5711 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5713 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5714 NVT, N0.getOperand(0));
5716 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5718 DAG.getConstant(Index, IndexTy));
5722 // Fold a series of buildvector, bitcast, and truncate if possible.
5724 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5725 // (2xi32 (buildvector x, y)).
5726 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5727 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5728 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5729 N0.getOperand(0).hasOneUse()) {
5731 SDValue BuildVect = N0.getOperand(0);
5732 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5733 EVT TruncVecEltTy = VT.getVectorElementType();
5735 // Check that the element types match.
5736 if (BuildVectEltTy == TruncVecEltTy) {
5737 // Now we only need to compute the offset of the truncated elements.
5738 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5739 unsigned TruncVecNumElts = VT.getVectorNumElements();
5740 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5742 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5743 "Invalid number of elements");
5745 SmallVector<SDValue, 8> Opnds;
5746 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5747 Opnds.push_back(BuildVect.getOperand(i));
5749 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5754 // See if we can simplify the input to this truncate through knowledge that
5755 // only the low bits are being used.
5756 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5757 // Currently we only perform this optimization on scalars because vectors
5758 // may have different active low bits.
5759 if (!VT.isVector()) {
5761 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5762 VT.getSizeInBits()));
5763 if (Shorter.getNode())
5764 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5766 // fold (truncate (load x)) -> (smaller load x)
5767 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5768 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5769 SDValue Reduced = ReduceLoadWidth(N);
5770 if (Reduced.getNode())
5772 // Handle the case where the load remains an extending load even
5773 // after truncation.
5774 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5775 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5776 if (!LN0->isVolatile() &&
5777 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5778 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5779 VT, LN0->getChain(), LN0->getBasePtr(),
5781 LN0->getMemOperand());
5782 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5787 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5788 // where ... are all 'undef'.
5789 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5790 SmallVector<EVT, 8> VTs;
5793 unsigned NumDefs = 0;
5795 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5796 SDValue X = N0.getOperand(i);
5797 if (X.getOpcode() != ISD::UNDEF) {
5802 // Stop if more than one members are non-undef.
5805 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5806 VT.getVectorElementType(),
5807 X.getValueType().getVectorNumElements()));
5811 return DAG.getUNDEF(VT);
5814 assert(V.getNode() && "The single defined operand is empty!");
5815 SmallVector<SDValue, 8> Opnds;
5816 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5818 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5821 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5822 AddToWorkList(NV.getNode());
5823 Opnds.push_back(NV);
5825 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5826 &Opnds[0], Opnds.size());
5830 // Simplify the operands using demanded-bits information.
5831 if (!VT.isVector() &&
5832 SimplifyDemandedBits(SDValue(N, 0)))
5833 return SDValue(N, 0);
5838 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5839 SDValue Elt = N->getOperand(i);
5840 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5841 return Elt.getNode();
5842 return Elt.getOperand(Elt.getResNo()).getNode();
5845 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5846 /// if load locations are consecutive.
5847 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5848 assert(N->getOpcode() == ISD::BUILD_PAIR);
5850 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5851 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5852 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5853 LD1->getPointerInfo().getAddrSpace() !=
5854 LD2->getPointerInfo().getAddrSpace())
5856 EVT LD1VT = LD1->getValueType(0);
5858 if (ISD::isNON_EXTLoad(LD2) &&
5860 // If both are volatile this would reduce the number of volatile loads.
5861 // If one is volatile it might be ok, but play conservative and bail out.
5862 !LD1->isVolatile() &&
5863 !LD2->isVolatile() &&
5864 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5865 unsigned Align = LD1->getAlignment();
5866 unsigned NewAlign = TLI.getDataLayout()->
5867 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5869 if (NewAlign <= Align &&
5870 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5871 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5872 LD1->getBasePtr(), LD1->getPointerInfo(),
5873 false, false, false, Align);
5879 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5880 SDValue N0 = N->getOperand(0);
5881 EVT VT = N->getValueType(0);
5883 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5884 // Only do this before legalize, since afterward the target may be depending
5885 // on the bitconvert.
5886 // First check to see if this is all constant.
5888 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5890 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
5892 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5893 assert(!DestEltVT.isVector() &&
5894 "Element type of vector ValueType must not be vector!");
5896 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5899 // If the input is a constant, let getNode fold it.
5900 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5901 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5902 if (Res.getNode() != N) {
5903 if (!LegalOperations ||
5904 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5907 // Folding it resulted in an illegal node, and it's too late to
5908 // do that. Clean up the old node and forego the transformation.
5909 // Ideally this won't happen very often, because instcombine
5910 // and the earlier dagcombine runs (where illegal nodes are
5911 // permitted) should have folded most of them already.
5912 DAG.DeleteNode(Res.getNode());
5916 // (conv (conv x, t1), t2) -> (conv x, t2)
5917 if (N0.getOpcode() == ISD::BITCAST)
5918 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5921 // fold (conv (load x)) -> (load (conv*)x)
5922 // If the resultant load doesn't need a higher alignment than the original!
5923 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5924 // Do not change the width of a volatile load.
5925 !cast<LoadSDNode>(N0)->isVolatile() &&
5926 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5927 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
5928 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5929 unsigned Align = TLI.getDataLayout()->
5930 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5931 unsigned OrigAlign = LN0->getAlignment();
5933 if (Align <= OrigAlign) {
5934 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5935 LN0->getBasePtr(), LN0->getPointerInfo(),
5936 LN0->isVolatile(), LN0->isNonTemporal(),
5937 LN0->isInvariant(), OrigAlign,
5938 LN0->getTBAAInfo());
5940 CombineTo(N0.getNode(),
5941 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5942 N0.getValueType(), Load),
5948 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5949 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5950 // This often reduces constant pool loads.
5951 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5952 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5953 N0.getNode()->hasOneUse() && VT.isInteger() &&
5954 !VT.isVector() && !N0.getValueType().isVector()) {
5955 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5957 AddToWorkList(NewConv.getNode());
5959 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5960 if (N0.getOpcode() == ISD::FNEG)
5961 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5962 NewConv, DAG.getConstant(SignBit, VT));
5963 assert(N0.getOpcode() == ISD::FABS);
5964 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5965 NewConv, DAG.getConstant(~SignBit, VT));
5968 // fold (bitconvert (fcopysign cst, x)) ->
5969 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5970 // Note that we don't handle (copysign x, cst) because this can always be
5971 // folded to an fneg or fabs.
5972 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5973 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5974 VT.isInteger() && !VT.isVector()) {
5975 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5976 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5977 if (isTypeLegal(IntXVT)) {
5978 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5979 IntXVT, N0.getOperand(1));
5980 AddToWorkList(X.getNode());
5982 // If X has a different width than the result/lhs, sext it or truncate it.
5983 unsigned VTWidth = VT.getSizeInBits();
5984 if (OrigXWidth < VTWidth) {
5985 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5986 AddToWorkList(X.getNode());
5987 } else if (OrigXWidth > VTWidth) {
5988 // To get the sign bit in the right place, we have to shift it right
5989 // before truncating.
5990 X = DAG.getNode(ISD::SRL, SDLoc(X),
5991 X.getValueType(), X,
5992 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5993 AddToWorkList(X.getNode());
5994 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5995 AddToWorkList(X.getNode());
5998 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5999 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6000 X, DAG.getConstant(SignBit, VT));
6001 AddToWorkList(X.getNode());
6003 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6004 VT, N0.getOperand(0));
6005 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6006 Cst, DAG.getConstant(~SignBit, VT));
6007 AddToWorkList(Cst.getNode());
6009 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6013 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6014 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6015 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6016 if (CombineLD.getNode())
6023 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6024 EVT VT = N->getValueType(0);
6025 return CombineConsecutiveLoads(N, VT);
6028 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6029 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6030 /// destination element value type.
6031 SDValue DAGCombiner::
6032 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6033 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6035 // If this is already the right type, we're done.
6036 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6038 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6039 unsigned DstBitSize = DstEltVT.getSizeInBits();
6041 // If this is a conversion of N elements of one type to N elements of another
6042 // type, convert each element. This handles FP<->INT cases.
6043 if (SrcBitSize == DstBitSize) {
6044 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6045 BV->getValueType(0).getVectorNumElements());
6047 // Due to the FP element handling below calling this routine recursively,
6048 // we can end up with a scalar-to-vector node here.
6049 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6050 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6051 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6052 DstEltVT, BV->getOperand(0)));
6054 SmallVector<SDValue, 8> Ops;
6055 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6056 SDValue Op = BV->getOperand(i);
6057 // If the vector element type is not legal, the BUILD_VECTOR operands
6058 // are promoted and implicitly truncated. Make that explicit here.
6059 if (Op.getValueType() != SrcEltVT)
6060 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6061 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6063 AddToWorkList(Ops.back().getNode());
6065 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6066 &Ops[0], Ops.size());
6069 // Otherwise, we're growing or shrinking the elements. To avoid having to
6070 // handle annoying details of growing/shrinking FP values, we convert them to
6072 if (SrcEltVT.isFloatingPoint()) {
6073 // Convert the input float vector to a int vector where the elements are the
6075 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6076 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6077 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6081 // Now we know the input is an integer vector. If the output is a FP type,
6082 // convert to integer first, then to FP of the right size.
6083 if (DstEltVT.isFloatingPoint()) {
6084 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6085 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6086 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6088 // Next, convert to FP elements of the same size.
6089 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6092 // Okay, we know the src/dst types are both integers of differing types.
6093 // Handling growing first.
6094 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6095 if (SrcBitSize < DstBitSize) {
6096 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6098 SmallVector<SDValue, 8> Ops;
6099 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6100 i += NumInputsPerOutput) {
6101 bool isLE = TLI.isLittleEndian();
6102 APInt NewBits = APInt(DstBitSize, 0);
6103 bool EltIsUndef = true;
6104 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6105 // Shift the previously computed bits over.
6106 NewBits <<= SrcBitSize;
6107 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6108 if (Op.getOpcode() == ISD::UNDEF) continue;
6111 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6112 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6116 Ops.push_back(DAG.getUNDEF(DstEltVT));
6118 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6121 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6122 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6123 &Ops[0], Ops.size());
6126 // Finally, this must be the case where we are shrinking elements: each input
6127 // turns into multiple outputs.
6128 bool isS2V = ISD::isScalarToVector(BV);
6129 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6130 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6131 NumOutputsPerInput*BV->getNumOperands());
6132 SmallVector<SDValue, 8> Ops;
6134 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6135 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6136 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6137 Ops.push_back(DAG.getUNDEF(DstEltVT));
6141 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6142 getAPIntValue().zextOrTrunc(SrcBitSize);
6144 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6145 APInt ThisVal = OpVal.trunc(DstBitSize);
6146 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6147 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6148 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6149 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6151 OpVal = OpVal.lshr(DstBitSize);
6154 // For big endian targets, swap the order of the pieces of each element.
6155 if (TLI.isBigEndian())
6156 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6159 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6160 &Ops[0], Ops.size());
6163 SDValue DAGCombiner::visitFADD(SDNode *N) {
6164 SDValue N0 = N->getOperand(0);
6165 SDValue N1 = N->getOperand(1);
6166 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6167 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6168 EVT VT = N->getValueType(0);
6171 if (VT.isVector()) {
6172 SDValue FoldedVOp = SimplifyVBinOp(N);
6173 if (FoldedVOp.getNode()) return FoldedVOp;
6176 // fold (fadd c1, c2) -> c1 + c2
6178 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6179 // canonicalize constant to RHS
6180 if (N0CFP && !N1CFP)
6181 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6182 // fold (fadd A, 0) -> A
6183 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6184 N1CFP->getValueAPF().isZero())
6186 // fold (fadd A, (fneg B)) -> (fsub A, B)
6187 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6188 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6189 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6190 GetNegatedExpression(N1, DAG, LegalOperations));
6191 // fold (fadd (fneg A), B) -> (fsub B, A)
6192 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6193 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6194 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6195 GetNegatedExpression(N0, DAG, LegalOperations));
6197 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6198 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6199 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6200 isa<ConstantFPSDNode>(N0.getOperand(1)))
6201 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6202 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6203 N0.getOperand(1), N1));
6205 // No FP constant should be created after legalization as Instruction
6206 // Selection pass has hard time in dealing with FP constant.
6208 // We don't need test this condition for transformation like following, as
6209 // the DAG being transformed implies it is legal to take FP constant as
6212 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6214 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6216 // If allow, fold (fadd (fneg x), x) -> 0.0
6217 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6218 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6219 return DAG.getConstantFP(0.0, VT);
6221 // If allow, fold (fadd x, (fneg x)) -> 0.0
6222 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6223 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6224 return DAG.getConstantFP(0.0, VT);
6226 // In unsafe math mode, we can fold chains of FADD's of the same value
6227 // into multiplications. This transform is not safe in general because
6228 // we are reducing the number of rounding steps.
6229 if (DAG.getTarget().Options.UnsafeFPMath &&
6230 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6232 if (N0.getOpcode() == ISD::FMUL) {
6233 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6234 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6236 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6237 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6238 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6240 DAG.getConstantFP(1.0, VT));
6241 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6245 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6246 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6247 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6249 DAG.getConstantFP(1.0, VT));
6250 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6254 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6255 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6256 N1.getOperand(0) == N1.getOperand(1) &&
6257 N0.getOperand(1) == N1.getOperand(0)) {
6258 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6260 DAG.getConstantFP(2.0, VT));
6261 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6262 N0.getOperand(1), NewCFP);
6265 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6266 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6267 N1.getOperand(0) == N1.getOperand(1) &&
6268 N0.getOperand(0) == N1.getOperand(0)) {
6269 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6271 DAG.getConstantFP(2.0, VT));
6272 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6273 N0.getOperand(0), NewCFP);
6277 if (N1.getOpcode() == ISD::FMUL) {
6278 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6279 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6281 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6282 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6283 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6285 DAG.getConstantFP(1.0, VT));
6286 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6290 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6291 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6292 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6294 DAG.getConstantFP(1.0, VT));
6295 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6300 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6301 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6302 N0.getOperand(0) == N0.getOperand(1) &&
6303 N1.getOperand(1) == N0.getOperand(0)) {
6304 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6306 DAG.getConstantFP(2.0, VT));
6307 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6308 N1.getOperand(1), NewCFP);
6311 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6312 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6313 N0.getOperand(0) == N0.getOperand(1) &&
6314 N1.getOperand(0) == N0.getOperand(0)) {
6315 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6317 DAG.getConstantFP(2.0, VT));
6318 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6319 N1.getOperand(0), NewCFP);
6323 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6324 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6325 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6326 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6327 (N0.getOperand(0) == N1))
6328 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6329 N1, DAG.getConstantFP(3.0, VT));
6332 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6333 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6334 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6335 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6336 N1.getOperand(0) == N0)
6337 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6338 N0, DAG.getConstantFP(3.0, VT));
6341 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6342 if (AllowNewFpConst &&
6343 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6344 N0.getOperand(0) == N0.getOperand(1) &&
6345 N1.getOperand(0) == N1.getOperand(1) &&
6346 N0.getOperand(0) == N1.getOperand(0))
6347 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6349 DAG.getConstantFP(4.0, VT));
6352 // FADD -> FMA combines:
6353 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6354 DAG.getTarget().Options.UnsafeFPMath) &&
6355 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6356 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6358 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6359 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6360 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6361 N0.getOperand(0), N0.getOperand(1), N1);
6363 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6364 // Note: Commutes FADD operands.
6365 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6366 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6367 N1.getOperand(0), N1.getOperand(1), N0);
6373 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6374 SDValue N0 = N->getOperand(0);
6375 SDValue N1 = N->getOperand(1);
6376 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6377 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6378 EVT VT = N->getValueType(0);
6382 if (VT.isVector()) {
6383 SDValue FoldedVOp = SimplifyVBinOp(N);
6384 if (FoldedVOp.getNode()) return FoldedVOp;
6387 // fold (fsub c1, c2) -> c1-c2
6389 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6390 // fold (fsub A, 0) -> A
6391 if (DAG.getTarget().Options.UnsafeFPMath &&
6392 N1CFP && N1CFP->getValueAPF().isZero())
6394 // fold (fsub 0, B) -> -B
6395 if (DAG.getTarget().Options.UnsafeFPMath &&
6396 N0CFP && N0CFP->getValueAPF().isZero()) {
6397 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6398 return GetNegatedExpression(N1, DAG, LegalOperations);
6399 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6400 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6402 // fold (fsub A, (fneg B)) -> (fadd A, B)
6403 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6404 return DAG.getNode(ISD::FADD, dl, VT, N0,
6405 GetNegatedExpression(N1, DAG, LegalOperations));
6407 // If 'unsafe math' is enabled, fold
6408 // (fsub x, x) -> 0.0 &
6409 // (fsub x, (fadd x, y)) -> (fneg y) &
6410 // (fsub x, (fadd y, x)) -> (fneg y)
6411 if (DAG.getTarget().Options.UnsafeFPMath) {
6413 return DAG.getConstantFP(0.0f, VT);
6415 if (N1.getOpcode() == ISD::FADD) {
6416 SDValue N10 = N1->getOperand(0);
6417 SDValue N11 = N1->getOperand(1);
6419 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6420 &DAG.getTarget().Options))
6421 return GetNegatedExpression(N11, DAG, LegalOperations);
6423 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6424 &DAG.getTarget().Options))
6425 return GetNegatedExpression(N10, DAG, LegalOperations);
6429 // FSUB -> FMA combines:
6430 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6431 DAG.getTarget().Options.UnsafeFPMath) &&
6432 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6433 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6435 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6436 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6437 return DAG.getNode(ISD::FMA, dl, VT,
6438 N0.getOperand(0), N0.getOperand(1),
6439 DAG.getNode(ISD::FNEG, dl, VT, N1));
6441 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6442 // Note: Commutes FSUB operands.
6443 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6444 return DAG.getNode(ISD::FMA, dl, VT,
6445 DAG.getNode(ISD::FNEG, dl, VT,
6447 N1.getOperand(1), N0);
6449 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6450 if (N0.getOpcode() == ISD::FNEG &&
6451 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6452 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6453 SDValue N00 = N0.getOperand(0).getOperand(0);
6454 SDValue N01 = N0.getOperand(0).getOperand(1);
6455 return DAG.getNode(ISD::FMA, dl, VT,
6456 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6457 DAG.getNode(ISD::FNEG, dl, VT, N1));
6464 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6465 SDValue N0 = N->getOperand(0);
6466 SDValue N1 = N->getOperand(1);
6467 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6468 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6469 EVT VT = N->getValueType(0);
6470 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6473 if (VT.isVector()) {
6474 SDValue FoldedVOp = SimplifyVBinOp(N);
6475 if (FoldedVOp.getNode()) return FoldedVOp;
6478 // fold (fmul c1, c2) -> c1*c2
6480 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6481 // canonicalize constant to RHS
6482 if (N0CFP && !N1CFP)
6483 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6484 // fold (fmul A, 0) -> 0
6485 if (DAG.getTarget().Options.UnsafeFPMath &&
6486 N1CFP && N1CFP->getValueAPF().isZero())
6488 // fold (fmul A, 0) -> 0, vector edition.
6489 if (DAG.getTarget().Options.UnsafeFPMath &&
6490 ISD::isBuildVectorAllZeros(N1.getNode()))
6492 // fold (fmul A, 1.0) -> A
6493 if (N1CFP && N1CFP->isExactlyValue(1.0))
6495 // fold (fmul X, 2.0) -> (fadd X, X)
6496 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6497 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6498 // fold (fmul X, -1.0) -> (fneg X)
6499 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6500 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6501 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6503 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6504 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6505 &DAG.getTarget().Options)) {
6506 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6507 &DAG.getTarget().Options)) {
6508 // Both can be negated for free, check to see if at least one is cheaper
6510 if (LHSNeg == 2 || RHSNeg == 2)
6511 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6512 GetNegatedExpression(N0, DAG, LegalOperations),
6513 GetNegatedExpression(N1, DAG, LegalOperations));
6517 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6518 if (DAG.getTarget().Options.UnsafeFPMath &&
6519 N1CFP && N0.getOpcode() == ISD::FMUL &&
6520 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6521 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6522 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6523 N0.getOperand(1), N1));
6528 SDValue DAGCombiner::visitFMA(SDNode *N) {
6529 SDValue N0 = N->getOperand(0);
6530 SDValue N1 = N->getOperand(1);
6531 SDValue N2 = N->getOperand(2);
6532 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6533 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6534 EVT VT = N->getValueType(0);
6537 if (DAG.getTarget().Options.UnsafeFPMath) {
6538 if (N0CFP && N0CFP->isZero())
6540 if (N1CFP && N1CFP->isZero())
6543 if (N0CFP && N0CFP->isExactlyValue(1.0))
6544 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6545 if (N1CFP && N1CFP->isExactlyValue(1.0))
6546 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6548 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6549 if (N0CFP && !N1CFP)
6550 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6552 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6553 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6554 N2.getOpcode() == ISD::FMUL &&
6555 N0 == N2.getOperand(0) &&
6556 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6557 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6558 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6562 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6563 if (DAG.getTarget().Options.UnsafeFPMath &&
6564 N0.getOpcode() == ISD::FMUL && N1CFP &&
6565 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6566 return DAG.getNode(ISD::FMA, dl, VT,
6568 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6572 // (fma x, 1, y) -> (fadd x, y)
6573 // (fma x, -1, y) -> (fadd (fneg x), y)
6575 if (N1CFP->isExactlyValue(1.0))
6576 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6578 if (N1CFP->isExactlyValue(-1.0) &&
6579 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6580 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6581 AddToWorkList(RHSNeg.getNode());
6582 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6586 // (fma x, c, x) -> (fmul x, (c+1))
6587 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6588 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6589 DAG.getNode(ISD::FADD, dl, VT,
6590 N1, DAG.getConstantFP(1.0, VT)));
6592 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6593 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6594 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6595 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6596 DAG.getNode(ISD::FADD, dl, VT,
6597 N1, DAG.getConstantFP(-1.0, VT)));
6603 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6604 SDValue N0 = N->getOperand(0);
6605 SDValue N1 = N->getOperand(1);
6606 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6607 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6608 EVT VT = N->getValueType(0);
6609 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6612 if (VT.isVector()) {
6613 SDValue FoldedVOp = SimplifyVBinOp(N);
6614 if (FoldedVOp.getNode()) return FoldedVOp;
6617 // fold (fdiv c1, c2) -> c1/c2
6619 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6621 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6622 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6623 // Compute the reciprocal 1.0 / c2.
6624 APFloat N1APF = N1CFP->getValueAPF();
6625 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6626 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6627 // Only do the transform if the reciprocal is a legal fp immediate that
6628 // isn't too nasty (eg NaN, denormal, ...).
6629 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6630 (!LegalOperations ||
6631 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6632 // backend)... we should handle this gracefully after Legalize.
6633 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6634 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6635 TLI.isFPImmLegal(Recip, VT)))
6636 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6637 DAG.getConstantFP(Recip, VT));
6640 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6641 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6642 &DAG.getTarget().Options)) {
6643 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6644 &DAG.getTarget().Options)) {
6645 // Both can be negated for free, check to see if at least one is cheaper
6647 if (LHSNeg == 2 || RHSNeg == 2)
6648 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6649 GetNegatedExpression(N0, DAG, LegalOperations),
6650 GetNegatedExpression(N1, DAG, LegalOperations));
6657 SDValue DAGCombiner::visitFREM(SDNode *N) {
6658 SDValue N0 = N->getOperand(0);
6659 SDValue N1 = N->getOperand(1);
6660 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6661 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6662 EVT VT = N->getValueType(0);
6664 // fold (frem c1, c2) -> fmod(c1,c2)
6666 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6671 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6672 SDValue N0 = N->getOperand(0);
6673 SDValue N1 = N->getOperand(1);
6674 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6675 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6676 EVT VT = N->getValueType(0);
6678 if (N0CFP && N1CFP) // Constant fold
6679 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6682 const APFloat& V = N1CFP->getValueAPF();
6683 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6684 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6685 if (!V.isNegative()) {
6686 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6687 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6689 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6690 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6691 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6695 // copysign(fabs(x), y) -> copysign(x, y)
6696 // copysign(fneg(x), y) -> copysign(x, y)
6697 // copysign(copysign(x,z), y) -> copysign(x, y)
6698 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6699 N0.getOpcode() == ISD::FCOPYSIGN)
6700 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6701 N0.getOperand(0), N1);
6703 // copysign(x, abs(y)) -> abs(x)
6704 if (N1.getOpcode() == ISD::FABS)
6705 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6707 // copysign(x, copysign(y,z)) -> copysign(x, z)
6708 if (N1.getOpcode() == ISD::FCOPYSIGN)
6709 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6710 N0, N1.getOperand(1));
6712 // copysign(x, fp_extend(y)) -> copysign(x, y)
6713 // copysign(x, fp_round(y)) -> copysign(x, y)
6714 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6715 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6716 N0, N1.getOperand(0));
6721 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6722 SDValue N0 = N->getOperand(0);
6723 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6724 EVT VT = N->getValueType(0);
6725 EVT OpVT = N0.getValueType();
6727 // fold (sint_to_fp c1) -> c1fp
6729 // ...but only if the target supports immediate floating-point values
6730 (!LegalOperations ||
6731 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6732 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6734 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6735 // but UINT_TO_FP is legal on this target, try to convert.
6736 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6737 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6738 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6739 if (DAG.SignBitIsZero(N0))
6740 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6743 // The next optimizations are desirable only if SELECT_CC can be lowered.
6744 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6745 // having to say they don't support SELECT_CC on every type the DAG knows
6746 // about, since there is no way to mark an opcode illegal at all value types
6747 // (See also visitSELECT)
6748 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6749 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6750 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6752 (!LegalOperations ||
6753 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6755 { N0.getOperand(0), N0.getOperand(1),
6756 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6758 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6761 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6762 // (select_cc x, y, 1.0, 0.0,, cc)
6763 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6764 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6765 (!LegalOperations ||
6766 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6768 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6769 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6770 N0.getOperand(0).getOperand(2) };
6771 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6778 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6779 SDValue N0 = N->getOperand(0);
6780 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6781 EVT VT = N->getValueType(0);
6782 EVT OpVT = N0.getValueType();
6784 // fold (uint_to_fp c1) -> c1fp
6786 // ...but only if the target supports immediate floating-point values
6787 (!LegalOperations ||
6788 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6789 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6791 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6792 // but SINT_TO_FP is legal on this target, try to convert.
6793 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6794 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6795 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6796 if (DAG.SignBitIsZero(N0))
6797 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6800 // The next optimizations are desirable only if SELECT_CC can be lowered.
6801 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6802 // having to say they don't support SELECT_CC on every type the DAG knows
6803 // about, since there is no way to mark an opcode illegal at all value types
6804 // (See also visitSELECT)
6805 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6806 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6808 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6809 (!LegalOperations ||
6810 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6812 { N0.getOperand(0), N0.getOperand(1),
6813 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6815 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6822 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6823 SDValue N0 = N->getOperand(0);
6824 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6825 EVT VT = N->getValueType(0);
6827 // fold (fp_to_sint c1fp) -> c1
6829 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6834 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6835 SDValue N0 = N->getOperand(0);
6836 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6837 EVT VT = N->getValueType(0);
6839 // fold (fp_to_uint c1fp) -> c1
6841 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6846 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6847 SDValue N0 = N->getOperand(0);
6848 SDValue N1 = N->getOperand(1);
6849 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6850 EVT VT = N->getValueType(0);
6852 // fold (fp_round c1fp) -> c1fp
6854 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6856 // fold (fp_round (fp_extend x)) -> x
6857 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6858 return N0.getOperand(0);
6860 // fold (fp_round (fp_round x)) -> (fp_round x)
6861 if (N0.getOpcode() == ISD::FP_ROUND) {
6862 // This is a value preserving truncation if both round's are.
6863 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6864 N0.getNode()->getConstantOperandVal(1) == 1;
6865 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6866 DAG.getIntPtrConstant(IsTrunc));
6869 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6870 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6871 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6872 N0.getOperand(0), N1);
6873 AddToWorkList(Tmp.getNode());
6874 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6875 Tmp, N0.getOperand(1));
6881 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6882 SDValue N0 = N->getOperand(0);
6883 EVT VT = N->getValueType(0);
6884 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6885 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6887 // fold (fp_round_inreg c1fp) -> c1fp
6888 if (N0CFP && isTypeLegal(EVT)) {
6889 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6890 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6896 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6897 SDValue N0 = N->getOperand(0);
6898 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6899 EVT VT = N->getValueType(0);
6901 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6902 if (N->hasOneUse() &&
6903 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6906 // fold (fp_extend c1fp) -> c1fp
6908 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6910 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6912 if (N0.getOpcode() == ISD::FP_ROUND
6913 && N0.getNode()->getConstantOperandVal(1) == 1) {
6914 SDValue In = N0.getOperand(0);
6915 if (In.getValueType() == VT) return In;
6916 if (VT.bitsLT(In.getValueType()))
6917 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6918 In, N0.getOperand(1));
6919 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6922 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6923 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6924 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6925 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6926 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6927 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6929 LN0->getBasePtr(), N0.getValueType(),
6930 LN0->getMemOperand());
6931 CombineTo(N, ExtLoad);
6932 CombineTo(N0.getNode(),
6933 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6934 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6935 ExtLoad.getValue(1));
6936 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6942 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6943 SDValue N0 = N->getOperand(0);
6944 EVT VT = N->getValueType(0);
6946 if (VT.isVector()) {
6947 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6948 if (FoldedVOp.getNode()) return FoldedVOp;
6951 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6952 &DAG.getTarget().Options))
6953 return GetNegatedExpression(N0, DAG, LegalOperations);
6955 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6956 // constant pool values.
6957 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6959 N0.getNode()->hasOneUse() &&
6960 N0.getOperand(0).getValueType().isInteger()) {
6961 SDValue Int = N0.getOperand(0);
6962 EVT IntVT = Int.getValueType();
6963 if (IntVT.isInteger() && !IntVT.isVector()) {
6964 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6965 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6966 AddToWorkList(Int.getNode());
6967 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6972 // (fneg (fmul c, x)) -> (fmul -c, x)
6973 if (N0.getOpcode() == ISD::FMUL) {
6974 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6976 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6978 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6985 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6986 SDValue N0 = N->getOperand(0);
6987 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6988 EVT VT = N->getValueType(0);
6990 // fold (fceil c1) -> fceil(c1)
6992 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6997 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6998 SDValue N0 = N->getOperand(0);
6999 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7000 EVT VT = N->getValueType(0);
7002 // fold (ftrunc c1) -> ftrunc(c1)
7004 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7009 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7010 SDValue N0 = N->getOperand(0);
7011 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7012 EVT VT = N->getValueType(0);
7014 // fold (ffloor c1) -> ffloor(c1)
7016 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7021 SDValue DAGCombiner::visitFABS(SDNode *N) {
7022 SDValue N0 = N->getOperand(0);
7023 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7024 EVT VT = N->getValueType(0);
7026 if (VT.isVector()) {
7027 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7028 if (FoldedVOp.getNode()) return FoldedVOp;
7031 // fold (fabs c1) -> fabs(c1)
7033 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7034 // fold (fabs (fabs x)) -> (fabs x)
7035 if (N0.getOpcode() == ISD::FABS)
7036 return N->getOperand(0);
7037 // fold (fabs (fneg x)) -> (fabs x)
7038 // fold (fabs (fcopysign x, y)) -> (fabs x)
7039 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7040 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7042 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7043 // constant pool values.
7044 if (!TLI.isFAbsFree(VT) &&
7045 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7046 N0.getOperand(0).getValueType().isInteger() &&
7047 !N0.getOperand(0).getValueType().isVector()) {
7048 SDValue Int = N0.getOperand(0);
7049 EVT IntVT = Int.getValueType();
7050 if (IntVT.isInteger() && !IntVT.isVector()) {
7051 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7052 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7053 AddToWorkList(Int.getNode());
7054 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7055 N->getValueType(0), Int);
7062 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7063 SDValue Chain = N->getOperand(0);
7064 SDValue N1 = N->getOperand(1);
7065 SDValue N2 = N->getOperand(2);
7067 // If N is a constant we could fold this into a fallthrough or unconditional
7068 // branch. However that doesn't happen very often in normal code, because
7069 // Instcombine/SimplifyCFG should have handled the available opportunities.
7070 // If we did this folding here, it would be necessary to update the
7071 // MachineBasicBlock CFG, which is awkward.
7073 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7075 if (N1.getOpcode() == ISD::SETCC &&
7076 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7077 N1.getOperand(0).getValueType())) {
7078 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7079 Chain, N1.getOperand(2),
7080 N1.getOperand(0), N1.getOperand(1), N2);
7083 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7084 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7085 (N1.getOperand(0).hasOneUse() &&
7086 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7088 if (N1.getOpcode() == ISD::TRUNCATE) {
7089 // Look pass the truncate.
7090 Trunc = N1.getNode();
7091 N1 = N1.getOperand(0);
7094 // Match this pattern so that we can generate simpler code:
7097 // %b = and i32 %a, 2
7098 // %c = srl i32 %b, 1
7099 // brcond i32 %c ...
7104 // %b = and i32 %a, 2
7105 // %c = setcc eq %b, 0
7108 // This applies only when the AND constant value has one bit set and the
7109 // SRL constant is equal to the log2 of the AND constant. The back-end is
7110 // smart enough to convert the result into a TEST/JMP sequence.
7111 SDValue Op0 = N1.getOperand(0);
7112 SDValue Op1 = N1.getOperand(1);
7114 if (Op0.getOpcode() == ISD::AND &&
7115 Op1.getOpcode() == ISD::Constant) {
7116 SDValue AndOp1 = Op0.getOperand(1);
7118 if (AndOp1.getOpcode() == ISD::Constant) {
7119 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7121 if (AndConst.isPowerOf2() &&
7122 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7124 DAG.getSetCC(SDLoc(N),
7125 getSetCCResultType(Op0.getValueType()),
7126 Op0, DAG.getConstant(0, Op0.getValueType()),
7129 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7130 MVT::Other, Chain, SetCC, N2);
7131 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7132 // will convert it back to (X & C1) >> C2.
7133 CombineTo(N, NewBRCond, false);
7134 // Truncate is dead.
7136 removeFromWorkList(Trunc);
7137 DAG.DeleteNode(Trunc);
7139 // Replace the uses of SRL with SETCC
7140 WorkListRemover DeadNodes(*this);
7141 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7142 removeFromWorkList(N1.getNode());
7143 DAG.DeleteNode(N1.getNode());
7144 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7150 // Restore N1 if the above transformation doesn't match.
7151 N1 = N->getOperand(1);
7154 // Transform br(xor(x, y)) -> br(x != y)
7155 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7156 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7157 SDNode *TheXor = N1.getNode();
7158 SDValue Op0 = TheXor->getOperand(0);
7159 SDValue Op1 = TheXor->getOperand(1);
7160 if (Op0.getOpcode() == Op1.getOpcode()) {
7161 // Avoid missing important xor optimizations.
7162 SDValue Tmp = visitXOR(TheXor);
7163 if (Tmp.getNode()) {
7164 if (Tmp.getNode() != TheXor) {
7165 DEBUG(dbgs() << "\nReplacing.8 ";
7167 dbgs() << "\nWith: ";
7168 Tmp.getNode()->dump(&DAG);
7170 WorkListRemover DeadNodes(*this);
7171 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7172 removeFromWorkList(TheXor);
7173 DAG.DeleteNode(TheXor);
7174 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7175 MVT::Other, Chain, Tmp, N2);
7178 // visitXOR has changed XOR's operands or replaced the XOR completely,
7180 return SDValue(N, 0);
7184 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7186 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7187 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7188 Op0.getOpcode() == ISD::XOR) {
7189 TheXor = Op0.getNode();
7193 EVT SetCCVT = N1.getValueType();
7195 SetCCVT = getSetCCResultType(SetCCVT);
7196 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7199 Equal ? ISD::SETEQ : ISD::SETNE);
7200 // Replace the uses of XOR with SETCC
7201 WorkListRemover DeadNodes(*this);
7202 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7203 removeFromWorkList(N1.getNode());
7204 DAG.DeleteNode(N1.getNode());
7205 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7206 MVT::Other, Chain, SetCC, N2);
7213 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7215 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7216 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7217 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7219 // If N is a constant we could fold this into a fallthrough or unconditional
7220 // branch. However that doesn't happen very often in normal code, because
7221 // Instcombine/SimplifyCFG should have handled the available opportunities.
7222 // If we did this folding here, it would be necessary to update the
7223 // MachineBasicBlock CFG, which is awkward.
7225 // Use SimplifySetCC to simplify SETCC's.
7226 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7227 CondLHS, CondRHS, CC->get(), SDLoc(N),
7229 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7231 // fold to a simpler setcc
7232 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7233 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7234 N->getOperand(0), Simp.getOperand(2),
7235 Simp.getOperand(0), Simp.getOperand(1),
7241 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7242 /// uses N as its base pointer and that N may be folded in the load / store
7243 /// addressing mode.
7244 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7246 const TargetLowering &TLI) {
7248 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7249 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7251 VT = Use->getValueType(0);
7252 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7253 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7255 VT = ST->getValue().getValueType();
7259 TargetLowering::AddrMode AM;
7260 if (N->getOpcode() == ISD::ADD) {
7261 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7264 AM.BaseOffs = Offset->getSExtValue();
7268 } else if (N->getOpcode() == ISD::SUB) {
7269 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7272 AM.BaseOffs = -Offset->getSExtValue();
7279 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7282 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7283 /// pre-indexed load / store when the base pointer is an add or subtract
7284 /// and it has other uses besides the load / store. After the
7285 /// transformation, the new indexed load / store has effectively folded
7286 /// the add / subtract in and all of its other uses are redirected to the
7287 /// new load / store.
7288 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7289 if (Level < AfterLegalizeDAG)
7295 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7296 if (LD->isIndexed())
7298 VT = LD->getMemoryVT();
7299 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7300 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7302 Ptr = LD->getBasePtr();
7303 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7304 if (ST->isIndexed())
7306 VT = ST->getMemoryVT();
7307 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7308 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7310 Ptr = ST->getBasePtr();
7316 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7317 // out. There is no reason to make this a preinc/predec.
7318 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7319 Ptr.getNode()->hasOneUse())
7322 // Ask the target to do addressing mode selection.
7325 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7326 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7329 // Backends without true r+i pre-indexed forms may need to pass a
7330 // constant base with a variable offset so that constant coercion
7331 // will work with the patterns in canonical form.
7332 bool Swapped = false;
7333 if (isa<ConstantSDNode>(BasePtr)) {
7334 std::swap(BasePtr, Offset);
7338 // Don't create a indexed load / store with zero offset.
7339 if (isa<ConstantSDNode>(Offset) &&
7340 cast<ConstantSDNode>(Offset)->isNullValue())
7343 // Try turning it into a pre-indexed load / store except when:
7344 // 1) The new base ptr is a frame index.
7345 // 2) If N is a store and the new base ptr is either the same as or is a
7346 // predecessor of the value being stored.
7347 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7348 // that would create a cycle.
7349 // 4) All uses are load / store ops that use it as old base ptr.
7351 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7352 // (plus the implicit offset) to a register to preinc anyway.
7353 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7358 SDValue Val = cast<StoreSDNode>(N)->getValue();
7359 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7363 // If the offset is a constant, there may be other adds of constants that
7364 // can be folded with this one. We should do this to avoid having to keep
7365 // a copy of the original base pointer.
7366 SmallVector<SDNode *, 16> OtherUses;
7367 if (isa<ConstantSDNode>(Offset))
7368 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7369 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7371 if (Use == Ptr.getNode())
7374 if (Use->isPredecessorOf(N))
7377 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7382 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7383 if (Op1.getNode() == BasePtr.getNode())
7384 std::swap(Op0, Op1);
7385 assert(Op0.getNode() == BasePtr.getNode() &&
7386 "Use of ADD/SUB but not an operand");
7388 if (!isa<ConstantSDNode>(Op1)) {
7393 // FIXME: In some cases, we can be smarter about this.
7394 if (Op1.getValueType() != Offset.getValueType()) {
7399 OtherUses.push_back(Use);
7403 std::swap(BasePtr, Offset);
7405 // Now check for #3 and #4.
7406 bool RealUse = false;
7408 // Caches for hasPredecessorHelper
7409 SmallPtrSet<const SDNode *, 32> Visited;
7410 SmallVector<const SDNode *, 16> Worklist;
7412 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7413 E = Ptr.getNode()->use_end(); I != E; ++I) {
7417 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7420 // If Ptr may be folded in addressing mode of other use, then it's
7421 // not profitable to do this transformation.
7422 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7431 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7432 BasePtr, Offset, AM);
7434 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7435 BasePtr, Offset, AM);
7438 DEBUG(dbgs() << "\nReplacing.4 ";
7440 dbgs() << "\nWith: ";
7441 Result.getNode()->dump(&DAG);
7443 WorkListRemover DeadNodes(*this);
7445 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7446 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7448 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7451 // Finally, since the node is now dead, remove it from the graph.
7455 std::swap(BasePtr, Offset);
7457 // Replace other uses of BasePtr that can be updated to use Ptr
7458 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7459 unsigned OffsetIdx = 1;
7460 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7462 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7463 BasePtr.getNode() && "Expected BasePtr operand");
7465 // We need to replace ptr0 in the following expression:
7466 // x0 * offset0 + y0 * ptr0 = t0
7468 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7470 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7471 // indexed load/store and the expresion that needs to be re-written.
7473 // Therefore, we have:
7474 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7476 ConstantSDNode *CN =
7477 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7479 APInt Offset0 = CN->getAPIntValue();
7480 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7482 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7483 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7484 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7485 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7487 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7489 APInt CNV = Offset0;
7490 if (X0 < 0) CNV = -CNV;
7491 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7492 else CNV = CNV - Offset1;
7494 // We can now generate the new expression.
7495 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7496 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7498 SDValue NewUse = DAG.getNode(Opcode,
7499 SDLoc(OtherUses[i]),
7500 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7501 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7502 removeFromWorkList(OtherUses[i]);
7503 DAG.DeleteNode(OtherUses[i]);
7506 // Replace the uses of Ptr with uses of the updated base value.
7507 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7508 removeFromWorkList(Ptr.getNode());
7509 DAG.DeleteNode(Ptr.getNode());
7514 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7515 /// add / sub of the base pointer node into a post-indexed load / store.
7516 /// The transformation folded the add / subtract into the new indexed
7517 /// load / store effectively and all of its uses are redirected to the
7518 /// new load / store.
7519 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7520 if (Level < AfterLegalizeDAG)
7526 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7527 if (LD->isIndexed())
7529 VT = LD->getMemoryVT();
7530 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7531 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7533 Ptr = LD->getBasePtr();
7534 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7535 if (ST->isIndexed())
7537 VT = ST->getMemoryVT();
7538 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7539 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7541 Ptr = ST->getBasePtr();
7547 if (Ptr.getNode()->hasOneUse())
7550 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7551 E = Ptr.getNode()->use_end(); I != E; ++I) {
7554 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7559 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7560 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7561 // Don't create a indexed load / store with zero offset.
7562 if (isa<ConstantSDNode>(Offset) &&
7563 cast<ConstantSDNode>(Offset)->isNullValue())
7566 // Try turning it into a post-indexed load / store except when
7567 // 1) All uses are load / store ops that use it as base ptr (and
7568 // it may be folded as addressing mmode).
7569 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7570 // nor a successor of N. Otherwise, if Op is folded that would
7573 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7577 bool TryNext = false;
7578 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7579 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7581 if (Use == Ptr.getNode())
7584 // If all the uses are load / store addresses, then don't do the
7586 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7587 bool RealUse = false;
7588 for (SDNode::use_iterator III = Use->use_begin(),
7589 EEE = Use->use_end(); III != EEE; ++III) {
7590 SDNode *UseUse = *III;
7591 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7606 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7607 SDValue Result = isLoad
7608 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7609 BasePtr, Offset, AM)
7610 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7611 BasePtr, Offset, AM);
7614 DEBUG(dbgs() << "\nReplacing.5 ";
7616 dbgs() << "\nWith: ";
7617 Result.getNode()->dump(&DAG);
7619 WorkListRemover DeadNodes(*this);
7621 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7622 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7624 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7627 // Finally, since the node is now dead, remove it from the graph.
7630 // Replace the uses of Use with uses of the updated base value.
7631 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7632 Result.getValue(isLoad ? 1 : 0));
7633 removeFromWorkList(Op);
7643 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7644 LoadSDNode *LD = cast<LoadSDNode>(N);
7645 SDValue Chain = LD->getChain();
7646 SDValue Ptr = LD->getBasePtr();
7648 // If load is not volatile and there are no uses of the loaded value (and
7649 // the updated indexed value in case of indexed loads), change uses of the
7650 // chain value into uses of the chain input (i.e. delete the dead load).
7651 if (!LD->isVolatile()) {
7652 if (N->getValueType(1) == MVT::Other) {
7654 if (!N->hasAnyUseOfValue(0)) {
7655 // It's not safe to use the two value CombineTo variant here. e.g.
7656 // v1, chain2 = load chain1, loc
7657 // v2, chain3 = load chain2, loc
7659 // Now we replace use of chain2 with chain1. This makes the second load
7660 // isomorphic to the one we are deleting, and thus makes this load live.
7661 DEBUG(dbgs() << "\nReplacing.6 ";
7663 dbgs() << "\nWith chain: ";
7664 Chain.getNode()->dump(&DAG);
7666 WorkListRemover DeadNodes(*this);
7667 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7669 if (N->use_empty()) {
7670 removeFromWorkList(N);
7674 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7678 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7679 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7680 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7681 DEBUG(dbgs() << "\nReplacing.7 ";
7683 dbgs() << "\nWith: ";
7684 Undef.getNode()->dump(&DAG);
7685 dbgs() << " and 2 other values\n");
7686 WorkListRemover DeadNodes(*this);
7687 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7688 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7689 DAG.getUNDEF(N->getValueType(1)));
7690 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7691 removeFromWorkList(N);
7693 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7698 // If this load is directly stored, replace the load value with the stored
7700 // TODO: Handle store large -> read small portion.
7701 // TODO: Handle TRUNCSTORE/LOADEXT
7702 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7703 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7704 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7705 if (PrevST->getBasePtr() == Ptr &&
7706 PrevST->getValue().getValueType() == N->getValueType(0))
7707 return CombineTo(N, Chain.getOperand(1), Chain);
7711 // Try to infer better alignment information than the load already has.
7712 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7713 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7714 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7716 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7717 LD->getValueType(0),
7718 Chain, Ptr, LD->getPointerInfo(),
7720 LD->isVolatile(), LD->isNonTemporal(), Align,
7722 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7727 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7728 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7729 if (UseAA && LD->isUnindexed()) {
7730 // Walk up chain skipping non-aliasing memory nodes.
7731 SDValue BetterChain = FindBetterChain(N, Chain);
7733 // If there is a better chain.
7734 if (Chain != BetterChain) {
7737 // Replace the chain to void dependency.
7738 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7739 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7740 BetterChain, Ptr, LD->getMemOperand());
7742 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7743 LD->getValueType(0),
7744 BetterChain, Ptr, LD->getMemoryVT(),
7745 LD->getMemOperand());
7748 // Create token factor to keep old chain connected.
7749 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7750 MVT::Other, Chain, ReplLoad.getValue(1));
7752 // Make sure the new and old chains are cleaned up.
7753 AddToWorkList(Token.getNode());
7755 // Replace uses with load result and token factor. Don't add users
7757 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7761 // Try transforming N to an indexed load.
7762 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7763 return SDValue(N, 0);
7765 // Try to slice up N to more direct loads if the slices are mapped to
7766 // different register banks or pairing can take place.
7768 return SDValue(N, 0);
7774 /// \brief Helper structure used to slice a load in smaller loads.
7775 /// Basically a slice is obtained from the following sequence:
7776 /// Origin = load Ty1, Base
7777 /// Shift = srl Ty1 Origin, CstTy Amount
7778 /// Inst = trunc Shift to Ty2
7780 /// Then, it will be rewriten into:
7781 /// Slice = load SliceTy, Base + SliceOffset
7782 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7784 /// SliceTy is deduced from the number of bits that are actually used to
7786 struct LoadedSlice {
7787 /// \brief Helper structure used to compute the cost of a slice.
7789 /// Are we optimizing for code size.
7794 unsigned CrossRegisterBanksCopies;
7798 Cost(bool ForCodeSize = false)
7799 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7800 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7802 /// \brief Get the cost of one isolated slice.
7803 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7804 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7805 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7806 EVT TruncType = LS.Inst->getValueType(0);
7807 EVT LoadedType = LS.getLoadedType();
7808 if (TruncType != LoadedType &&
7809 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7813 /// \brief Account for slicing gain in the current cost.
7814 /// Slicing provide a few gains like removing a shift or a
7815 /// truncate. This method allows to grow the cost of the original
7816 /// load with the gain from this slice.
7817 void addSliceGain(const LoadedSlice &LS) {
7818 // Each slice saves a truncate.
7819 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7820 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7821 LS.Inst->getOperand(0).getValueType()))
7823 // If there is a shift amount, this slice gets rid of it.
7826 // If this slice can merge a cross register bank copy, account for it.
7827 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7828 ++CrossRegisterBanksCopies;
7831 Cost &operator+=(const Cost &RHS) {
7833 Truncates += RHS.Truncates;
7834 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7840 bool operator==(const Cost &RHS) const {
7841 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7842 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7843 ZExts == RHS.ZExts && Shift == RHS.Shift;
7846 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7848 bool operator<(const Cost &RHS) const {
7849 // Assume cross register banks copies are as expensive as loads.
7850 // FIXME: Do we want some more target hooks?
7851 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7852 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7853 // Unless we are optimizing for code size, consider the
7854 // expensive operation first.
7855 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7856 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7857 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7858 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7861 bool operator>(const Cost &RHS) const { return RHS < *this; }
7863 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7865 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7867 // The last instruction that represent the slice. This should be a
7868 // truncate instruction.
7870 // The original load instruction.
7872 // The right shift amount in bits from the original load.
7874 // The DAG from which Origin came from.
7875 // This is used to get some contextual information about legal types, etc.
7878 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7879 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7880 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7882 LoadedSlice(const LoadedSlice &LS)
7883 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7885 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7886 /// \return Result is \p BitWidth and has used bits set to 1 and
7887 /// not used bits set to 0.
7888 APInt getUsedBits() const {
7889 // Reproduce the trunc(lshr) sequence:
7890 // - Start from the truncated value.
7891 // - Zero extend to the desired bit width.
7893 assert(Origin && "No original load to compare against.");
7894 unsigned BitWidth = Origin->getValueSizeInBits(0);
7895 assert(Inst && "This slice is not bound to an instruction");
7896 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7897 "Extracted slice is bigger than the whole type!");
7898 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7899 UsedBits.setAllBits();
7900 UsedBits = UsedBits.zext(BitWidth);
7905 /// \brief Get the size of the slice to be loaded in bytes.
7906 unsigned getLoadedSize() const {
7907 unsigned SliceSize = getUsedBits().countPopulation();
7908 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7909 return SliceSize / 8;
7912 /// \brief Get the type that will be loaded for this slice.
7913 /// Note: This may not be the final type for the slice.
7914 EVT getLoadedType() const {
7915 assert(DAG && "Missing context");
7916 LLVMContext &Ctxt = *DAG->getContext();
7917 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7920 /// \brief Get the alignment of the load used for this slice.
7921 unsigned getAlignment() const {
7922 unsigned Alignment = Origin->getAlignment();
7923 unsigned Offset = getOffsetFromBase();
7925 Alignment = MinAlign(Alignment, Alignment + Offset);
7929 /// \brief Check if this slice can be rewritten with legal operations.
7930 bool isLegal() const {
7931 // An invalid slice is not legal.
7932 if (!Origin || !Inst || !DAG)
7935 // Offsets are for indexed load only, we do not handle that.
7936 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7939 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7941 // Check that the type is legal.
7942 EVT SliceType = getLoadedType();
7943 if (!TLI.isTypeLegal(SliceType))
7946 // Check that the load is legal for this type.
7947 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7950 // Check that the offset can be computed.
7951 // 1. Check its type.
7952 EVT PtrType = Origin->getBasePtr().getValueType();
7953 if (PtrType == MVT::Untyped || PtrType.isExtended())
7956 // 2. Check that it fits in the immediate.
7957 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7960 // 3. Check that the computation is legal.
7961 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7964 // Check that the zext is legal if it needs one.
7965 EVT TruncateType = Inst->getValueType(0);
7966 if (TruncateType != SliceType &&
7967 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7973 /// \brief Get the offset in bytes of this slice in the original chunk of
7975 /// \pre DAG != NULL.
7976 uint64_t getOffsetFromBase() const {
7977 assert(DAG && "Missing context.");
7979 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7980 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7981 uint64_t Offset = Shift / 8;
7982 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7983 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7984 "The size of the original loaded type is not a multiple of a"
7986 // If Offset is bigger than TySizeInBytes, it means we are loading all
7987 // zeros. This should have been optimized before in the process.
7988 assert(TySizeInBytes > Offset &&
7989 "Invalid shift amount for given loaded size");
7991 Offset = TySizeInBytes - Offset - getLoadedSize();
7995 /// \brief Generate the sequence of instructions to load the slice
7996 /// represented by this object and redirect the uses of this slice to
7997 /// this new sequence of instructions.
7998 /// \pre this->Inst && this->Origin are valid Instructions and this
7999 /// object passed the legal check: LoadedSlice::isLegal returned true.
8000 /// \return The last instruction of the sequence used to load the slice.
8001 SDValue loadSlice() const {
8002 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8003 const SDValue &OldBaseAddr = Origin->getBasePtr();
8004 SDValue BaseAddr = OldBaseAddr;
8005 // Get the offset in that chunk of bytes w.r.t. the endianess.
8006 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8007 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8009 // BaseAddr = BaseAddr + Offset.
8010 EVT ArithType = BaseAddr.getValueType();
8011 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8012 DAG->getConstant(Offset, ArithType));
8015 // Create the type of the loaded slice according to its size.
8016 EVT SliceType = getLoadedType();
8018 // Create the load for the slice.
8019 SDValue LastInst = DAG->getLoad(
8020 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8021 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8022 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8023 // If the final type is not the same as the loaded type, this means that
8024 // we have to pad with zero. Create a zero extend for that.
8025 EVT FinalType = Inst->getValueType(0);
8026 if (SliceType != FinalType)
8028 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8032 /// \brief Check if this slice can be merged with an expensive cross register
8033 /// bank copy. E.g.,
8035 /// f = bitcast i32 i to float
8036 bool canMergeExpensiveCrossRegisterBankCopy() const {
8037 if (!Inst || !Inst->hasOneUse())
8039 SDNode *Use = *Inst->use_begin();
8040 if (Use->getOpcode() != ISD::BITCAST)
8042 assert(DAG && "Missing context");
8043 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8044 EVT ResVT = Use->getValueType(0);
8045 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8046 const TargetRegisterClass *ArgRC =
8047 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8048 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8051 // At this point, we know that we perform a cross-register-bank copy.
8052 // Check if it is expensive.
8053 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8054 // Assume bitcasts are cheap, unless both register classes do not
8055 // explicitly share a common sub class.
8056 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8059 // Check if it will be merged with the load.
8060 // 1. Check the alignment constraint.
8061 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8062 ResVT.getTypeForEVT(*DAG->getContext()));
8064 if (RequiredAlignment > getAlignment())
8067 // 2. Check that the load is a legal operation for that type.
8068 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8071 // 3. Check that we do not have a zext in the way.
8072 if (Inst->getValueType(0) != getLoadedType())
8080 /// \brief Sorts LoadedSlice according to their offset.
8081 struct LoadedSliceSorter {
8082 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
8083 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8084 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8088 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8089 /// \p UsedBits looks like 0..0 1..1 0..0.
8090 static bool areUsedBitsDense(const APInt &UsedBits) {
8091 // If all the bits are one, this is dense!
8092 if (UsedBits.isAllOnesValue())
8095 // Get rid of the unused bits on the right.
8096 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8097 // Get rid of the unused bits on the left.
8098 if (NarrowedUsedBits.countLeadingZeros())
8099 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8100 // Check that the chunk of bits is completely used.
8101 return NarrowedUsedBits.isAllOnesValue();
8104 /// \brief Check whether or not \p First and \p Second are next to each other
8105 /// in memory. This means that there is no hole between the bits loaded
8106 /// by \p First and the bits loaded by \p Second.
8107 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8108 const LoadedSlice &Second) {
8109 assert(First.Origin == Second.Origin && First.Origin &&
8110 "Unable to match different memory origins.");
8111 APInt UsedBits = First.getUsedBits();
8112 assert((UsedBits & Second.getUsedBits()) == 0 &&
8113 "Slices are not supposed to overlap.");
8114 UsedBits |= Second.getUsedBits();
8115 return areUsedBitsDense(UsedBits);
8118 /// \brief Adjust the \p GlobalLSCost according to the target
8119 /// paring capabilities and the layout of the slices.
8120 /// \pre \p GlobalLSCost should account for at least as many loads as
8121 /// there is in the slices in \p LoadedSlices.
8122 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8123 LoadedSlice::Cost &GlobalLSCost) {
8124 unsigned NumberOfSlices = LoadedSlices.size();
8125 // If there is less than 2 elements, no pairing is possible.
8126 if (NumberOfSlices < 2)
8129 // Sort the slices so that elements that are likely to be next to each
8130 // other in memory are next to each other in the list.
8131 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8132 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8133 // First (resp. Second) is the first (resp. Second) potentially candidate
8134 // to be placed in a paired load.
8135 const LoadedSlice *First = NULL;
8136 const LoadedSlice *Second = NULL;
8137 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8138 // Set the beginning of the pair.
8141 Second = &LoadedSlices[CurrSlice];
8143 // If First is NULL, it means we start a new pair.
8144 // Get to the next slice.
8148 EVT LoadedType = First->getLoadedType();
8150 // If the types of the slices are different, we cannot pair them.
8151 if (LoadedType != Second->getLoadedType())
8154 // Check if the target supplies paired loads for this type.
8155 unsigned RequiredAlignment = 0;
8156 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8157 // move to the next pair, this type is hopeless.
8161 // Check if we meet the alignment requirement.
8162 if (RequiredAlignment > First->getAlignment())
8165 // Check that both loads are next to each other in memory.
8166 if (!areSlicesNextToEachOther(*First, *Second))
8169 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8170 --GlobalLSCost.Loads;
8171 // Move to the next pair.
8176 /// \brief Check the profitability of all involved LoadedSlice.
8177 /// Currently, it is considered profitable if there is exactly two
8178 /// involved slices (1) which are (2) next to each other in memory, and
8179 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8181 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8182 /// the elements themselves.
8184 /// FIXME: When the cost model will be mature enough, we can relax
8185 /// constraints (1) and (2).
8186 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8187 const APInt &UsedBits, bool ForCodeSize) {
8188 unsigned NumberOfSlices = LoadedSlices.size();
8189 if (StressLoadSlicing)
8190 return NumberOfSlices > 1;
8193 if (NumberOfSlices != 2)
8197 if (!areUsedBitsDense(UsedBits))
8201 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8202 // The original code has one big load.
8204 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8205 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8206 // Accumulate the cost of all the slices.
8207 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8208 GlobalSlicingCost += SliceCost;
8210 // Account as cost in the original configuration the gain obtained
8211 // with the current slices.
8212 OrigCost.addSliceGain(LS);
8215 // If the target supports paired load, adjust the cost accordingly.
8216 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8217 return OrigCost > GlobalSlicingCost;
8220 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8221 /// operations, split it in the various pieces being extracted.
8223 /// This sort of thing is introduced by SROA.
8224 /// This slicing takes care not to insert overlapping loads.
8225 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8226 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8227 if (Level < AfterLegalizeDAG)
8230 LoadSDNode *LD = cast<LoadSDNode>(N);
8231 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8232 !LD->getValueType(0).isInteger())
8235 // Keep track of already used bits to detect overlapping values.
8236 // In that case, we will just abort the transformation.
8237 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8239 SmallVector<LoadedSlice, 4> LoadedSlices;
8241 // Check if this load is used as several smaller chunks of bits.
8242 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8243 // of computation for each trunc.
8244 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8245 UI != UIEnd; ++UI) {
8246 // Skip the uses of the chain.
8247 if (UI.getUse().getResNo() != 0)
8253 // Check if this is a trunc(lshr).
8254 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8255 isa<ConstantSDNode>(User->getOperand(1))) {
8256 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8257 User = *User->use_begin();
8260 // At this point, User is a Truncate, iff we encountered, trunc or
8262 if (User->getOpcode() != ISD::TRUNCATE)
8265 // The width of the type must be a power of 2 and greater than 8-bits.
8266 // Otherwise the load cannot be represented in LLVM IR.
8267 // Moreover, if we shifted with a non-8-bits multiple, the slice
8268 // will be across several bytes. We do not support that.
8269 unsigned Width = User->getValueSizeInBits(0);
8270 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8273 // Build the slice for this chain of computations.
8274 LoadedSlice LS(User, LD, Shift, &DAG);
8275 APInt CurrentUsedBits = LS.getUsedBits();
8277 // Check if this slice overlaps with another.
8278 if ((CurrentUsedBits & UsedBits) != 0)
8280 // Update the bits used globally.
8281 UsedBits |= CurrentUsedBits;
8283 // Check if the new slice would be legal.
8287 // Record the slice.
8288 LoadedSlices.push_back(LS);
8291 // Abort slicing if it does not seem to be profitable.
8292 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8297 // Rewrite each chain to use an independent load.
8298 // By construction, each chain can be represented by a unique load.
8300 // Prepare the argument for the new token factor for all the slices.
8301 SmallVector<SDValue, 8> ArgChains;
8302 for (SmallVectorImpl<LoadedSlice>::const_iterator
8303 LSIt = LoadedSlices.begin(),
8304 LSItEnd = LoadedSlices.end();
8305 LSIt != LSItEnd; ++LSIt) {
8306 SDValue SliceInst = LSIt->loadSlice();
8307 CombineTo(LSIt->Inst, SliceInst, true);
8308 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8309 SliceInst = SliceInst.getOperand(0);
8310 assert(SliceInst->getOpcode() == ISD::LOAD &&
8311 "It takes more than a zext to get to the loaded slice!!");
8312 ArgChains.push_back(SliceInst.getValue(1));
8315 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8316 &ArgChains[0], ArgChains.size());
8317 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8321 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8322 /// load is having specific bytes cleared out. If so, return the byte size
8323 /// being masked out and the shift amount.
8324 static std::pair<unsigned, unsigned>
8325 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8326 std::pair<unsigned, unsigned> Result(0, 0);
8328 // Check for the structure we're looking for.
8329 if (V->getOpcode() != ISD::AND ||
8330 !isa<ConstantSDNode>(V->getOperand(1)) ||
8331 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8334 // Check the chain and pointer.
8335 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8336 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8338 // The store should be chained directly to the load or be an operand of a
8340 if (LD == Chain.getNode())
8342 else if (Chain->getOpcode() != ISD::TokenFactor)
8343 return Result; // Fail.
8346 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8347 if (Chain->getOperand(i).getNode() == LD) {
8351 if (!isOk) return Result;
8354 // This only handles simple types.
8355 if (V.getValueType() != MVT::i16 &&
8356 V.getValueType() != MVT::i32 &&
8357 V.getValueType() != MVT::i64)
8360 // Check the constant mask. Invert it so that the bits being masked out are
8361 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8362 // follow the sign bit for uniformity.
8363 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8364 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8365 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8366 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8367 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8368 if (NotMaskLZ == 64) return Result; // All zero mask.
8370 // See if we have a continuous run of bits. If so, we have 0*1+0*
8371 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8374 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8375 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8376 NotMaskLZ -= 64-V.getValueSizeInBits();
8378 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8379 switch (MaskedBytes) {
8383 default: return Result; // All one mask, or 5-byte mask.
8386 // Verify that the first bit starts at a multiple of mask so that the access
8387 // is aligned the same as the access width.
8388 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8390 Result.first = MaskedBytes;
8391 Result.second = NotMaskTZ/8;
8396 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8397 /// provides a value as specified by MaskInfo. If so, replace the specified
8398 /// store with a narrower store of truncated IVal.
8400 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8401 SDValue IVal, StoreSDNode *St,
8403 unsigned NumBytes = MaskInfo.first;
8404 unsigned ByteShift = MaskInfo.second;
8405 SelectionDAG &DAG = DC->getDAG();
8407 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8408 // that uses this. If not, this is not a replacement.
8409 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8410 ByteShift*8, (ByteShift+NumBytes)*8);
8411 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8413 // Check that it is legal on the target to do this. It is legal if the new
8414 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8416 MVT VT = MVT::getIntegerVT(NumBytes*8);
8417 if (!DC->isTypeLegal(VT))
8420 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8421 // shifted by ByteShift and truncated down to NumBytes.
8423 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8424 DAG.getConstant(ByteShift*8,
8425 DC->getShiftAmountTy(IVal.getValueType())));
8427 // Figure out the offset for the store and the alignment of the access.
8429 unsigned NewAlign = St->getAlignment();
8431 if (DAG.getTargetLoweringInfo().isLittleEndian())
8432 StOffset = ByteShift;
8434 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8436 SDValue Ptr = St->getBasePtr();
8438 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8439 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8440 NewAlign = MinAlign(NewAlign, StOffset);
8443 // Truncate down to the new size.
8444 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8447 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8448 St->getPointerInfo().getWithOffset(StOffset),
8449 false, false, NewAlign).getNode();
8453 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8454 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8455 /// of the loaded bits, try narrowing the load and store if it would end up
8456 /// being a win for performance or code size.
8457 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8458 StoreSDNode *ST = cast<StoreSDNode>(N);
8459 if (ST->isVolatile())
8462 SDValue Chain = ST->getChain();
8463 SDValue Value = ST->getValue();
8464 SDValue Ptr = ST->getBasePtr();
8465 EVT VT = Value.getValueType();
8467 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8470 unsigned Opc = Value.getOpcode();
8472 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8473 // is a byte mask indicating a consecutive number of bytes, check to see if
8474 // Y is known to provide just those bytes. If so, we try to replace the
8475 // load + replace + store sequence with a single (narrower) store, which makes
8477 if (Opc == ISD::OR) {
8478 std::pair<unsigned, unsigned> MaskedLoad;
8479 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8480 if (MaskedLoad.first)
8481 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8482 Value.getOperand(1), ST,this))
8483 return SDValue(NewST, 0);
8485 // Or is commutative, so try swapping X and Y.
8486 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8487 if (MaskedLoad.first)
8488 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8489 Value.getOperand(0), ST,this))
8490 return SDValue(NewST, 0);
8493 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8494 Value.getOperand(1).getOpcode() != ISD::Constant)
8497 SDValue N0 = Value.getOperand(0);
8498 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8499 Chain == SDValue(N0.getNode(), 1)) {
8500 LoadSDNode *LD = cast<LoadSDNode>(N0);
8501 if (LD->getBasePtr() != Ptr ||
8502 LD->getPointerInfo().getAddrSpace() !=
8503 ST->getPointerInfo().getAddrSpace())
8506 // Find the type to narrow it the load / op / store to.
8507 SDValue N1 = Value.getOperand(1);
8508 unsigned BitWidth = N1.getValueSizeInBits();
8509 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8510 if (Opc == ISD::AND)
8511 Imm ^= APInt::getAllOnesValue(BitWidth);
8512 if (Imm == 0 || Imm.isAllOnesValue())
8514 unsigned ShAmt = Imm.countTrailingZeros();
8515 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8516 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8517 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8518 while (NewBW < BitWidth &&
8519 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8520 TLI.isNarrowingProfitable(VT, NewVT))) {
8521 NewBW = NextPowerOf2(NewBW);
8522 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8524 if (NewBW >= BitWidth)
8527 // If the lsb changed does not start at the type bitwidth boundary,
8528 // start at the previous one.
8530 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8531 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8532 std::min(BitWidth, ShAmt + NewBW));
8533 if ((Imm & Mask) == Imm) {
8534 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8535 if (Opc == ISD::AND)
8536 NewImm ^= APInt::getAllOnesValue(NewBW);
8537 uint64_t PtrOff = ShAmt / 8;
8538 // For big endian targets, we need to adjust the offset to the pointer to
8539 // load the correct bytes.
8540 if (TLI.isBigEndian())
8541 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8543 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8544 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8545 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8548 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8549 Ptr.getValueType(), Ptr,
8550 DAG.getConstant(PtrOff, Ptr.getValueType()));
8551 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8552 LD->getChain(), NewPtr,
8553 LD->getPointerInfo().getWithOffset(PtrOff),
8554 LD->isVolatile(), LD->isNonTemporal(),
8555 LD->isInvariant(), NewAlign,
8557 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8558 DAG.getConstant(NewImm, NewVT));
8559 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8561 ST->getPointerInfo().getWithOffset(PtrOff),
8562 false, false, NewAlign);
8564 AddToWorkList(NewPtr.getNode());
8565 AddToWorkList(NewLD.getNode());
8566 AddToWorkList(NewVal.getNode());
8567 WorkListRemover DeadNodes(*this);
8568 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8577 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8578 /// if the load value isn't used by any other operations, then consider
8579 /// transforming the pair to integer load / store operations if the target
8580 /// deems the transformation profitable.
8581 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8582 StoreSDNode *ST = cast<StoreSDNode>(N);
8583 SDValue Chain = ST->getChain();
8584 SDValue Value = ST->getValue();
8585 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8586 Value.hasOneUse() &&
8587 Chain == SDValue(Value.getNode(), 1)) {
8588 LoadSDNode *LD = cast<LoadSDNode>(Value);
8589 EVT VT = LD->getMemoryVT();
8590 if (!VT.isFloatingPoint() ||
8591 VT != ST->getMemoryVT() ||
8592 LD->isNonTemporal() ||
8593 ST->isNonTemporal() ||
8594 LD->getPointerInfo().getAddrSpace() != 0 ||
8595 ST->getPointerInfo().getAddrSpace() != 0)
8598 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8599 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8600 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8601 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8602 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8605 unsigned LDAlign = LD->getAlignment();
8606 unsigned STAlign = ST->getAlignment();
8607 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8608 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8609 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8612 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8613 LD->getChain(), LD->getBasePtr(),
8614 LD->getPointerInfo(),
8615 false, false, false, LDAlign);
8617 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8618 NewLD, ST->getBasePtr(),
8619 ST->getPointerInfo(),
8620 false, false, STAlign);
8622 AddToWorkList(NewLD.getNode());
8623 AddToWorkList(NewST.getNode());
8624 WorkListRemover DeadNodes(*this);
8625 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8633 /// Helper struct to parse and store a memory address as base + index + offset.
8634 /// We ignore sign extensions when it is safe to do so.
8635 /// The following two expressions are not equivalent. To differentiate we need
8636 /// to store whether there was a sign extension involved in the index
8638 /// (load (i64 add (i64 copyfromreg %c)
8639 /// (i64 signextend (add (i8 load %index)
8643 /// (load (i64 add (i64 copyfromreg %c)
8644 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8646 struct BaseIndexOffset {
8650 bool IsIndexSignExt;
8652 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8654 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8655 bool IsIndexSignExt) :
8656 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8658 bool equalBaseIndex(const BaseIndexOffset &Other) {
8659 return Other.Base == Base && Other.Index == Index &&
8660 Other.IsIndexSignExt == IsIndexSignExt;
8663 /// Parses tree in Ptr for base, index, offset addresses.
8664 static BaseIndexOffset match(SDValue Ptr) {
8665 bool IsIndexSignExt = false;
8667 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8668 // instruction, then it could be just the BASE or everything else we don't
8669 // know how to handle. Just use Ptr as BASE and give up.
8670 if (Ptr->getOpcode() != ISD::ADD)
8671 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8673 // We know that we have at least an ADD instruction. Try to pattern match
8674 // the simple case of BASE + OFFSET.
8675 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8676 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8677 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8681 // Inside a loop the current BASE pointer is calculated using an ADD and a
8682 // MUL instruction. In this case Ptr is the actual BASE pointer.
8683 // (i64 add (i64 %array_ptr)
8684 // (i64 mul (i64 %induction_var)
8685 // (i64 %element_size)))
8686 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8687 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8689 // Look at Base + Index + Offset cases.
8690 SDValue Base = Ptr->getOperand(0);
8691 SDValue IndexOffset = Ptr->getOperand(1);
8693 // Skip signextends.
8694 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8695 IndexOffset = IndexOffset->getOperand(0);
8696 IsIndexSignExt = true;
8699 // Either the case of Base + Index (no offset) or something else.
8700 if (IndexOffset->getOpcode() != ISD::ADD)
8701 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8703 // Now we have the case of Base + Index + offset.
8704 SDValue Index = IndexOffset->getOperand(0);
8705 SDValue Offset = IndexOffset->getOperand(1);
8707 if (!isa<ConstantSDNode>(Offset))
8708 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8710 // Ignore signextends.
8711 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8712 Index = Index->getOperand(0);
8713 IsIndexSignExt = true;
8714 } else IsIndexSignExt = false;
8716 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8717 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8721 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8722 /// is located in a sequence of memory operations connected by a chain.
8724 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8725 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8726 // Ptr to the mem node.
8727 LSBaseSDNode *MemNode;
8728 // Offset from the base ptr.
8729 int64_t OffsetFromBase;
8730 // What is the sequence number of this mem node.
8731 // Lowest mem operand in the DAG starts at zero.
8732 unsigned SequenceNum;
8735 /// Sorts store nodes in a link according to their offset from a shared
8737 struct ConsecutiveMemoryChainSorter {
8738 bool operator()(MemOpLink LHS, MemOpLink RHS) {
8739 return LHS.OffsetFromBase < RHS.OffsetFromBase;
8743 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8744 EVT MemVT = St->getMemoryVT();
8745 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8746 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8747 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8749 // Don't merge vectors into wider inputs.
8750 if (MemVT.isVector() || !MemVT.isSimple())
8753 // Perform an early exit check. Do not bother looking at stored values that
8754 // are not constants or loads.
8755 SDValue StoredVal = St->getValue();
8756 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8757 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8761 // Only look at ends of store sequences.
8762 SDValue Chain = SDValue(St, 1);
8763 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8766 // This holds the base pointer, index, and the offset in bytes from the base
8768 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8770 // We must have a base and an offset.
8771 if (!BasePtr.Base.getNode())
8774 // Do not handle stores to undef base pointers.
8775 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8778 // Save the LoadSDNodes that we find in the chain.
8779 // We need to make sure that these nodes do not interfere with
8780 // any of the store nodes.
8781 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8783 // Save the StoreSDNodes that we find in the chain.
8784 SmallVector<MemOpLink, 8> StoreNodes;
8786 // Walk up the chain and look for nodes with offsets from the same
8787 // base pointer. Stop when reaching an instruction with a different kind
8788 // or instruction which has a different base pointer.
8790 StoreSDNode *Index = St;
8792 // If the chain has more than one use, then we can't reorder the mem ops.
8793 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8796 // Find the base pointer and offset for this memory node.
8797 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8799 // Check that the base pointer is the same as the original one.
8800 if (!Ptr.equalBaseIndex(BasePtr))
8803 // Check that the alignment is the same.
8804 if (Index->getAlignment() != St->getAlignment())
8807 // The memory operands must not be volatile.
8808 if (Index->isVolatile() || Index->isIndexed())
8812 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8813 if (St->isTruncatingStore())
8816 // The stored memory type must be the same.
8817 if (Index->getMemoryVT() != MemVT)
8820 // We do not allow unaligned stores because we want to prevent overriding
8822 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8825 // We found a potential memory operand to merge.
8826 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8828 // Find the next memory operand in the chain. If the next operand in the
8829 // chain is a store then move up and continue the scan with the next
8830 // memory operand. If the next operand is a load save it and use alias
8831 // information to check if it interferes with anything.
8832 SDNode *NextInChain = Index->getChain().getNode();
8834 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8835 // We found a store node. Use it for the next iteration.
8838 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8839 if (Ldn->isVolatile()) {
8844 // Save the load node for later. Continue the scan.
8845 AliasLoadNodes.push_back(Ldn);
8846 NextInChain = Ldn->getChain().getNode();
8855 // Check if there is anything to merge.
8856 if (StoreNodes.size() < 2)
8859 // Sort the memory operands according to their distance from the base pointer.
8860 std::sort(StoreNodes.begin(), StoreNodes.end(),
8861 ConsecutiveMemoryChainSorter());
8863 // Scan the memory operations on the chain and find the first non-consecutive
8864 // store memory address.
8865 unsigned LastConsecutiveStore = 0;
8866 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8867 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8869 // Check that the addresses are consecutive starting from the second
8870 // element in the list of stores.
8872 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8873 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8878 // Check if this store interferes with any of the loads that we found.
8879 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8880 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8884 // We found a load that alias with this store. Stop the sequence.
8888 // Mark this node as useful.
8889 LastConsecutiveStore = i;
8892 // The node with the lowest store address.
8893 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8895 // Store the constants into memory as one consecutive store.
8897 unsigned LastLegalType = 0;
8898 unsigned LastLegalVectorType = 0;
8899 bool NonZero = false;
8900 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8901 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8902 SDValue StoredVal = St->getValue();
8904 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8905 NonZero |= !C->isNullValue();
8906 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8907 NonZero |= !C->getConstantFPValue()->isNullValue();
8913 // Find a legal type for the constant store.
8914 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8915 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8916 if (TLI.isTypeLegal(StoreTy))
8917 LastLegalType = i+1;
8918 // Or check whether a truncstore is legal.
8919 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8920 TargetLowering::TypePromoteInteger) {
8921 EVT LegalizedStoredValueTy =
8922 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8923 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8924 LastLegalType = i+1;
8927 // Find a legal type for the vector store.
8928 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8929 if (TLI.isTypeLegal(Ty))
8930 LastLegalVectorType = i + 1;
8933 // We only use vectors if the constant is known to be zero and the
8934 // function is not marked with the noimplicitfloat attribute.
8935 if (NonZero || NoVectors)
8936 LastLegalVectorType = 0;
8938 // Check if we found a legal integer type to store.
8939 if (LastLegalType == 0 && LastLegalVectorType == 0)
8942 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8943 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8945 // Make sure we have something to merge.
8949 unsigned EarliestNodeUsed = 0;
8950 for (unsigned i=0; i < NumElem; ++i) {
8951 // Find a chain for the new wide-store operand. Notice that some
8952 // of the store nodes that we found may not be selected for inclusion
8953 // in the wide store. The chain we use needs to be the chain of the
8954 // earliest store node which is *used* and replaced by the wide store.
8955 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8956 EarliestNodeUsed = i;
8959 // The earliest Node in the DAG.
8960 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8961 SDLoc DL(StoreNodes[0].MemNode);
8965 // Find a legal type for the vector store.
8966 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8967 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8968 StoredVal = DAG.getConstant(0, Ty);
8970 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8971 APInt StoreInt(StoreBW, 0);
8973 // Construct a single integer constant which is made of the smaller
8975 bool IsLE = TLI.isLittleEndian();
8976 for (unsigned i = 0; i < NumElem ; ++i) {
8977 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8978 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8979 SDValue Val = St->getValue();
8980 StoreInt<<=ElementSizeBytes*8;
8981 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8982 StoreInt|=C->getAPIntValue().zext(StoreBW);
8983 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8984 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8986 assert(false && "Invalid constant element type");
8990 // Create the new Load and Store operations.
8991 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8992 StoredVal = DAG.getConstant(StoreInt, StoreTy);
8995 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8996 FirstInChain->getBasePtr(),
8997 FirstInChain->getPointerInfo(),
8999 FirstInChain->getAlignment());
9001 // Replace the first store with the new store
9002 CombineTo(EarliestOp, NewStore);
9003 // Erase all other stores.
9004 for (unsigned i = 0; i < NumElem ; ++i) {
9005 if (StoreNodes[i].MemNode == EarliestOp)
9007 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9008 // ReplaceAllUsesWith will replace all uses that existed when it was
9009 // called, but graph optimizations may cause new ones to appear. For
9010 // example, the case in pr14333 looks like
9012 // St's chain -> St -> another store -> X
9014 // And the only difference from St to the other store is the chain.
9015 // When we change it's chain to be St's chain they become identical,
9016 // get CSEed and the net result is that X is now a use of St.
9017 // Since we know that St is redundant, just iterate.
9018 while (!St->use_empty())
9019 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9020 removeFromWorkList(St);
9027 // Below we handle the case of multiple consecutive stores that
9028 // come from multiple consecutive loads. We merge them into a single
9029 // wide load and a single wide store.
9031 // Look for load nodes which are used by the stored values.
9032 SmallVector<MemOpLink, 8> LoadNodes;
9034 // Find acceptable loads. Loads need to have the same chain (token factor),
9035 // must not be zext, volatile, indexed, and they must be consecutive.
9036 BaseIndexOffset LdBasePtr;
9037 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9038 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9039 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9042 // Loads must only have one use.
9043 if (!Ld->hasNUsesOfValue(1, 0))
9046 // Check that the alignment is the same as the stores.
9047 if (Ld->getAlignment() != St->getAlignment())
9050 // The memory operands must not be volatile.
9051 if (Ld->isVolatile() || Ld->isIndexed())
9054 // We do not accept ext loads.
9055 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9058 // The stored memory type must be the same.
9059 if (Ld->getMemoryVT() != MemVT)
9062 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9063 // If this is not the first ptr that we check.
9064 if (LdBasePtr.Base.getNode()) {
9065 // The base ptr must be the same.
9066 if (!LdPtr.equalBaseIndex(LdBasePtr))
9069 // Check that all other base pointers are the same as this one.
9073 // We found a potential memory operand to merge.
9074 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9077 if (LoadNodes.size() < 2)
9080 // Scan the memory operations on the chain and find the first non-consecutive
9081 // load memory address. These variables hold the index in the store node
9083 unsigned LastConsecutiveLoad = 0;
9084 // This variable refers to the size and not index in the array.
9085 unsigned LastLegalVectorType = 0;
9086 unsigned LastLegalIntegerType = 0;
9087 StartAddress = LoadNodes[0].OffsetFromBase;
9088 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9089 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9090 // All loads much share the same chain.
9091 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9094 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9095 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9097 LastConsecutiveLoad = i;
9099 // Find a legal type for the vector store.
9100 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9101 if (TLI.isTypeLegal(StoreTy))
9102 LastLegalVectorType = i + 1;
9104 // Find a legal type for the integer store.
9105 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9106 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9107 if (TLI.isTypeLegal(StoreTy))
9108 LastLegalIntegerType = i + 1;
9109 // Or check whether a truncstore and extload is legal.
9110 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9111 TargetLowering::TypePromoteInteger) {
9112 EVT LegalizedStoredValueTy =
9113 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9114 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9115 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9116 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9117 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9118 LastLegalIntegerType = i+1;
9122 // Only use vector types if the vector type is larger than the integer type.
9123 // If they are the same, use integers.
9124 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9125 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9127 // We add +1 here because the LastXXX variables refer to location while
9128 // the NumElem refers to array/index size.
9129 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9130 NumElem = std::min(LastLegalType, NumElem);
9135 // The earliest Node in the DAG.
9136 unsigned EarliestNodeUsed = 0;
9137 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9138 for (unsigned i=1; i<NumElem; ++i) {
9139 // Find a chain for the new wide-store operand. Notice that some
9140 // of the store nodes that we found may not be selected for inclusion
9141 // in the wide store. The chain we use needs to be the chain of the
9142 // earliest store node which is *used* and replaced by the wide store.
9143 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9144 EarliestNodeUsed = i;
9147 // Find if it is better to use vectors or integers to load and store
9151 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9153 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9154 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9157 SDLoc LoadDL(LoadNodes[0].MemNode);
9158 SDLoc StoreDL(StoreNodes[0].MemNode);
9160 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9161 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9162 FirstLoad->getChain(),
9163 FirstLoad->getBasePtr(),
9164 FirstLoad->getPointerInfo(),
9165 false, false, false,
9166 FirstLoad->getAlignment());
9168 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9169 FirstInChain->getBasePtr(),
9170 FirstInChain->getPointerInfo(), false, false,
9171 FirstInChain->getAlignment());
9173 // Replace one of the loads with the new load.
9174 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9175 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9176 SDValue(NewLoad.getNode(), 1));
9178 // Remove the rest of the load chains.
9179 for (unsigned i = 1; i < NumElem ; ++i) {
9180 // Replace all chain users of the old load nodes with the chain of the new
9182 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9183 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9186 // Replace the first store with the new store.
9187 CombineTo(EarliestOp, NewStore);
9188 // Erase all other stores.
9189 for (unsigned i = 0; i < NumElem ; ++i) {
9190 // Remove all Store nodes.
9191 if (StoreNodes[i].MemNode == EarliestOp)
9193 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9194 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9195 removeFromWorkList(St);
9202 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9203 StoreSDNode *ST = cast<StoreSDNode>(N);
9204 SDValue Chain = ST->getChain();
9205 SDValue Value = ST->getValue();
9206 SDValue Ptr = ST->getBasePtr();
9208 // If this is a store of a bit convert, store the input value if the
9209 // resultant store does not need a higher alignment than the original.
9210 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9211 ST->isUnindexed()) {
9212 unsigned OrigAlign = ST->getAlignment();
9213 EVT SVT = Value.getOperand(0).getValueType();
9214 unsigned Align = TLI.getDataLayout()->
9215 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9216 if (Align <= OrigAlign &&
9217 ((!LegalOperations && !ST->isVolatile()) ||
9218 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9219 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9220 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9221 ST->isNonTemporal(), OrigAlign,
9225 // Turn 'store undef, Ptr' -> nothing.
9226 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9229 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9230 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9231 // NOTE: If the original store is volatile, this transform must not increase
9232 // the number of stores. For example, on x86-32 an f64 can be stored in one
9233 // processor operation but an i64 (which is not legal) requires two. So the
9234 // transform should not be done in this case.
9235 if (Value.getOpcode() != ISD::TargetConstantFP) {
9237 switch (CFP->getSimpleValueType(0).SimpleTy) {
9238 default: llvm_unreachable("Unknown FP type");
9239 case MVT::f16: // We don't do this for these yet.
9245 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9246 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9247 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9248 bitcastToAPInt().getZExtValue(), MVT::i32);
9249 return DAG.getStore(Chain, SDLoc(N), Tmp,
9250 Ptr, ST->getMemOperand());
9254 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9255 !ST->isVolatile()) ||
9256 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9257 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9258 getZExtValue(), MVT::i64);
9259 return DAG.getStore(Chain, SDLoc(N), Tmp,
9260 Ptr, ST->getMemOperand());
9263 if (!ST->isVolatile() &&
9264 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9265 // Many FP stores are not made apparent until after legalize, e.g. for
9266 // argument passing. Since this is so common, custom legalize the
9267 // 64-bit integer store into two 32-bit stores.
9268 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9269 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9270 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9271 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9273 unsigned Alignment = ST->getAlignment();
9274 bool isVolatile = ST->isVolatile();
9275 bool isNonTemporal = ST->isNonTemporal();
9276 const MDNode *TBAAInfo = ST->getTBAAInfo();
9278 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9279 Ptr, ST->getPointerInfo(),
9280 isVolatile, isNonTemporal,
9281 ST->getAlignment(), TBAAInfo);
9282 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9283 DAG.getConstant(4, Ptr.getValueType()));
9284 Alignment = MinAlign(Alignment, 4U);
9285 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9286 Ptr, ST->getPointerInfo().getWithOffset(4),
9287 isVolatile, isNonTemporal,
9288 Alignment, TBAAInfo);
9289 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9298 // Try to infer better alignment information than the store already has.
9299 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9300 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9301 if (Align > ST->getAlignment())
9302 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9303 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9304 ST->isVolatile(), ST->isNonTemporal(), Align,
9309 // Try transforming a pair floating point load / store ops to integer
9310 // load / store ops.
9311 SDValue NewST = TransformFPLoadStorePair(N);
9312 if (NewST.getNode())
9315 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9316 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9317 if (UseAA && ST->isUnindexed()) {
9318 // Walk up chain skipping non-aliasing memory nodes.
9319 SDValue BetterChain = FindBetterChain(N, Chain);
9321 // If there is a better chain.
9322 if (Chain != BetterChain) {
9325 // Replace the chain to avoid dependency.
9326 if (ST->isTruncatingStore()) {
9327 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9328 ST->getMemoryVT(), ST->getMemOperand());
9330 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9331 ST->getMemOperand());
9334 // Create token to keep both nodes around.
9335 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9336 MVT::Other, Chain, ReplStore);
9338 // Make sure the new and old chains are cleaned up.
9339 AddToWorkList(Token.getNode());
9341 // Don't add users to work list.
9342 return CombineTo(N, Token, false);
9346 // Try transforming N to an indexed store.
9347 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9348 return SDValue(N, 0);
9350 // FIXME: is there such a thing as a truncating indexed store?
9351 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9352 Value.getValueType().isInteger()) {
9353 // See if we can simplify the input to this truncstore with knowledge that
9354 // only the low bits are being used. For example:
9355 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9357 GetDemandedBits(Value,
9358 APInt::getLowBitsSet(
9359 Value.getValueType().getScalarType().getSizeInBits(),
9360 ST->getMemoryVT().getScalarType().getSizeInBits()));
9361 AddToWorkList(Value.getNode());
9362 if (Shorter.getNode())
9363 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9364 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9366 // Otherwise, see if we can simplify the operation with
9367 // SimplifyDemandedBits, which only works if the value has a single use.
9368 if (SimplifyDemandedBits(Value,
9369 APInt::getLowBitsSet(
9370 Value.getValueType().getScalarType().getSizeInBits(),
9371 ST->getMemoryVT().getScalarType().getSizeInBits())))
9372 return SDValue(N, 0);
9375 // If this is a load followed by a store to the same location, then the store
9377 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9378 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9379 ST->isUnindexed() && !ST->isVolatile() &&
9380 // There can't be any side effects between the load and store, such as
9382 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9383 // The store is dead, remove it.
9388 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9389 // truncating store. We can do this even if this is already a truncstore.
9390 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9391 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9392 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9393 ST->getMemoryVT())) {
9394 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9395 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9398 // Only perform this optimization before the types are legal, because we
9399 // don't want to perform this optimization on every DAGCombine invocation.
9401 bool EverChanged = false;
9404 // There can be multiple store sequences on the same chain.
9405 // Keep trying to merge store sequences until we are unable to do so
9406 // or until we merge the last store on the chain.
9407 bool Changed = MergeConsecutiveStores(ST);
9408 EverChanged |= Changed;
9409 if (!Changed) break;
9410 } while (ST->getOpcode() != ISD::DELETED_NODE);
9413 return SDValue(N, 0);
9416 return ReduceLoadOpStoreWidth(N);
9419 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9420 SDValue InVec = N->getOperand(0);
9421 SDValue InVal = N->getOperand(1);
9422 SDValue EltNo = N->getOperand(2);
9425 // If the inserted element is an UNDEF, just use the input vector.
9426 if (InVal.getOpcode() == ISD::UNDEF)
9429 EVT VT = InVec.getValueType();
9431 // If we can't generate a legal BUILD_VECTOR, exit
9432 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9435 // Check that we know which element is being inserted
9436 if (!isa<ConstantSDNode>(EltNo))
9438 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9440 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9441 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9443 SmallVector<SDValue, 8> Ops;
9444 // Do not combine these two vectors if the output vector will not replace
9445 // the input vector.
9446 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9447 Ops.append(InVec.getNode()->op_begin(),
9448 InVec.getNode()->op_end());
9449 } else if (InVec.getOpcode() == ISD::UNDEF) {
9450 unsigned NElts = VT.getVectorNumElements();
9451 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9456 // Insert the element
9457 if (Elt < Ops.size()) {
9458 // All the operands of BUILD_VECTOR must have the same type;
9459 // we enforce that here.
9460 EVT OpVT = Ops[0].getValueType();
9461 if (InVal.getValueType() != OpVT)
9462 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9463 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9464 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9468 // Return the new vector
9469 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9470 VT, &Ops[0], Ops.size());
9473 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9474 // (vextract (scalar_to_vector val, 0) -> val
9475 SDValue InVec = N->getOperand(0);
9476 EVT VT = InVec.getValueType();
9477 EVT NVT = N->getValueType(0);
9479 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9480 // Check if the result type doesn't match the inserted element type. A
9481 // SCALAR_TO_VECTOR may truncate the inserted element and the
9482 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9483 SDValue InOp = InVec.getOperand(0);
9484 if (InOp.getValueType() != NVT) {
9485 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9486 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9491 SDValue EltNo = N->getOperand(1);
9492 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9494 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9495 // We only perform this optimization before the op legalization phase because
9496 // we may introduce new vector instructions which are not backed by TD
9497 // patterns. For example on AVX, extracting elements from a wide vector
9498 // without using extract_subvector.
9499 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9500 && ConstEltNo && !LegalOperations) {
9501 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9502 int NumElem = VT.getVectorNumElements();
9503 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9504 // Find the new index to extract from.
9505 int OrigElt = SVOp->getMaskElt(Elt);
9507 // Extracting an undef index is undef.
9509 return DAG.getUNDEF(NVT);
9511 // Select the right vector half to extract from.
9512 if (OrigElt < NumElem) {
9513 InVec = InVec->getOperand(0);
9515 InVec = InVec->getOperand(1);
9519 EVT IndexTy = TLI.getVectorIdxTy();
9520 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9521 InVec, DAG.getConstant(OrigElt, IndexTy));
9524 // Perform only after legalization to ensure build_vector / vector_shuffle
9525 // optimizations have already been done.
9526 if (!LegalOperations) return SDValue();
9528 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9529 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9530 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9533 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9534 bool NewLoad = false;
9535 bool BCNumEltsChanged = false;
9536 EVT ExtVT = VT.getVectorElementType();
9539 // If the result of load has to be truncated, then it's not necessarily
9541 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9544 if (InVec.getOpcode() == ISD::BITCAST) {
9545 // Don't duplicate a load with other uses.
9546 if (!InVec.hasOneUse())
9549 EVT BCVT = InVec.getOperand(0).getValueType();
9550 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9552 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9553 BCNumEltsChanged = true;
9554 InVec = InVec.getOperand(0);
9555 ExtVT = BCVT.getVectorElementType();
9559 LoadSDNode *LN0 = NULL;
9560 const ShuffleVectorSDNode *SVN = NULL;
9561 if (ISD::isNormalLoad(InVec.getNode())) {
9562 LN0 = cast<LoadSDNode>(InVec);
9563 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9564 InVec.getOperand(0).getValueType() == ExtVT &&
9565 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9566 // Don't duplicate a load with other uses.
9567 if (!InVec.hasOneUse())
9570 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9571 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9572 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9574 // (load $addr+1*size)
9576 // Don't duplicate a load with other uses.
9577 if (!InVec.hasOneUse())
9580 // If the bit convert changed the number of elements, it is unsafe
9581 // to examine the mask.
9582 if (BCNumEltsChanged)
9585 // Select the input vector, guarding against out of range extract vector.
9586 unsigned NumElems = VT.getVectorNumElements();
9587 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9588 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9590 if (InVec.getOpcode() == ISD::BITCAST) {
9591 // Don't duplicate a load with other uses.
9592 if (!InVec.hasOneUse())
9595 InVec = InVec.getOperand(0);
9597 if (ISD::isNormalLoad(InVec.getNode())) {
9598 LN0 = cast<LoadSDNode>(InVec);
9599 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9603 // Make sure we found a non-volatile load and the extractelement is
9605 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9608 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9610 return DAG.getUNDEF(LVT);
9612 unsigned Align = LN0->getAlignment();
9614 // Check the resultant load doesn't need a higher alignment than the
9618 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9620 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9626 SDValue NewPtr = LN0->getBasePtr();
9627 unsigned PtrOff = 0;
9630 PtrOff = LVT.getSizeInBits() * Elt / 8;
9631 EVT PtrType = NewPtr.getValueType();
9632 if (TLI.isBigEndian())
9633 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9634 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9635 DAG.getConstant(PtrOff, PtrType));
9638 // The replacement we need to do here is a little tricky: we need to
9639 // replace an extractelement of a load with a load.
9640 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9641 // Note that this replacement assumes that the extractvalue is the only
9642 // use of the load; that's okay because we don't want to perform this
9643 // transformation in other cases anyway.
9646 if (NVT.bitsGT(LVT)) {
9647 // If the result type of vextract is wider than the load, then issue an
9648 // extending load instead.
9649 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9650 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9651 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9652 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9653 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9654 Align, LN0->getTBAAInfo());
9655 Chain = Load.getValue(1);
9657 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9658 LN0->getPointerInfo().getWithOffset(PtrOff),
9659 LN0->isVolatile(), LN0->isNonTemporal(),
9660 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9661 Chain = Load.getValue(1);
9662 if (NVT.bitsLT(LVT))
9663 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9665 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9667 WorkListRemover DeadNodes(*this);
9668 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9669 SDValue To[] = { Load, Chain };
9670 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9671 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9672 // worklist explicitly as well.
9673 AddToWorkList(Load.getNode());
9674 AddUsersToWorkList(Load.getNode()); // Add users too
9675 // Make sure to revisit this node to clean it up; it will usually be dead.
9677 return SDValue(N, 0);
9683 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9684 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9685 // We perform this optimization post type-legalization because
9686 // the type-legalizer often scalarizes integer-promoted vectors.
9687 // Performing this optimization before may create bit-casts which
9688 // will be type-legalized to complex code sequences.
9689 // We perform this optimization only before the operation legalizer because we
9690 // may introduce illegal operations.
9691 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9694 unsigned NumInScalars = N->getNumOperands();
9696 EVT VT = N->getValueType(0);
9698 // Check to see if this is a BUILD_VECTOR of a bunch of values
9699 // which come from any_extend or zero_extend nodes. If so, we can create
9700 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9701 // optimizations. We do not handle sign-extend because we can't fill the sign
9703 EVT SourceType = MVT::Other;
9704 bool AllAnyExt = true;
9706 for (unsigned i = 0; i != NumInScalars; ++i) {
9707 SDValue In = N->getOperand(i);
9708 // Ignore undef inputs.
9709 if (In.getOpcode() == ISD::UNDEF) continue;
9711 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9712 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9714 // Abort if the element is not an extension.
9715 if (!ZeroExt && !AnyExt) {
9716 SourceType = MVT::Other;
9720 // The input is a ZeroExt or AnyExt. Check the original type.
9721 EVT InTy = In.getOperand(0).getValueType();
9723 // Check that all of the widened source types are the same.
9724 if (SourceType == MVT::Other)
9727 else if (InTy != SourceType) {
9728 // Multiple income types. Abort.
9729 SourceType = MVT::Other;
9733 // Check if all of the extends are ANY_EXTENDs.
9734 AllAnyExt &= AnyExt;
9737 // In order to have valid types, all of the inputs must be extended from the
9738 // same source type and all of the inputs must be any or zero extend.
9739 // Scalar sizes must be a power of two.
9740 EVT OutScalarTy = VT.getScalarType();
9741 bool ValidTypes = SourceType != MVT::Other &&
9742 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9743 isPowerOf2_32(SourceType.getSizeInBits());
9745 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9746 // turn into a single shuffle instruction.
9750 bool isLE = TLI.isLittleEndian();
9751 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9752 assert(ElemRatio > 1 && "Invalid element size ratio");
9753 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9754 DAG.getConstant(0, SourceType);
9756 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9757 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9759 // Populate the new build_vector
9760 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9761 SDValue Cast = N->getOperand(i);
9762 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9763 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9764 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9766 if (Cast.getOpcode() == ISD::UNDEF)
9767 In = DAG.getUNDEF(SourceType);
9769 In = Cast->getOperand(0);
9770 unsigned Index = isLE ? (i * ElemRatio) :
9771 (i * ElemRatio + (ElemRatio - 1));
9773 assert(Index < Ops.size() && "Invalid index");
9777 // The type of the new BUILD_VECTOR node.
9778 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9779 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9780 "Invalid vector size");
9781 // Check if the new vector type is legal.
9782 if (!isTypeLegal(VecVT)) return SDValue();
9784 // Make the new BUILD_VECTOR.
9785 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9787 // The new BUILD_VECTOR node has the potential to be further optimized.
9788 AddToWorkList(BV.getNode());
9789 // Bitcast to the desired type.
9790 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9793 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9794 EVT VT = N->getValueType(0);
9796 unsigned NumInScalars = N->getNumOperands();
9799 EVT SrcVT = MVT::Other;
9800 unsigned Opcode = ISD::DELETED_NODE;
9801 unsigned NumDefs = 0;
9803 for (unsigned i = 0; i != NumInScalars; ++i) {
9804 SDValue In = N->getOperand(i);
9805 unsigned Opc = In.getOpcode();
9807 if (Opc == ISD::UNDEF)
9810 // If all scalar values are floats and converted from integers.
9811 if (Opcode == ISD::DELETED_NODE &&
9812 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9819 EVT InVT = In.getOperand(0).getValueType();
9821 // If all scalar values are typed differently, bail out. It's chosen to
9822 // simplify BUILD_VECTOR of integer types.
9823 if (SrcVT == MVT::Other)
9830 // If the vector has just one element defined, it's not worth to fold it into
9831 // a vectorized one.
9835 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9836 && "Should only handle conversion from integer to float.");
9837 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9839 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9841 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9844 SmallVector<SDValue, 8> Opnds;
9845 for (unsigned i = 0; i != NumInScalars; ++i) {
9846 SDValue In = N->getOperand(i);
9848 if (In.getOpcode() == ISD::UNDEF)
9849 Opnds.push_back(DAG.getUNDEF(SrcVT));
9851 Opnds.push_back(In.getOperand(0));
9853 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9854 &Opnds[0], Opnds.size());
9855 AddToWorkList(BV.getNode());
9857 return DAG.getNode(Opcode, dl, VT, BV);
9860 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9861 unsigned NumInScalars = N->getNumOperands();
9863 EVT VT = N->getValueType(0);
9865 // A vector built entirely of undefs is undef.
9866 if (ISD::allOperandsUndef(N))
9867 return DAG.getUNDEF(VT);
9869 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9873 V = reduceBuildVecConvertToConvertBuildVec(N);
9877 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9878 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9879 // at most two distinct vectors, turn this into a shuffle node.
9881 // May only combine to shuffle after legalize if shuffle is legal.
9882 if (LegalOperations &&
9883 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9886 SDValue VecIn1, VecIn2;
9887 for (unsigned i = 0; i != NumInScalars; ++i) {
9888 // Ignore undef inputs.
9889 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9891 // If this input is something other than a EXTRACT_VECTOR_ELT with a
9892 // constant index, bail out.
9893 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9894 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9895 VecIn1 = VecIn2 = SDValue(0, 0);
9899 // We allow up to two distinct input vectors.
9900 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9901 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9904 if (VecIn1.getNode() == 0) {
9905 VecIn1 = ExtractedFromVec;
9906 } else if (VecIn2.getNode() == 0) {
9907 VecIn2 = ExtractedFromVec;
9910 VecIn1 = VecIn2 = SDValue(0, 0);
9915 // If everything is good, we can make a shuffle operation.
9916 if (VecIn1.getNode()) {
9917 SmallVector<int, 8> Mask;
9918 for (unsigned i = 0; i != NumInScalars; ++i) {
9919 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9924 // If extracting from the first vector, just use the index directly.
9925 SDValue Extract = N->getOperand(i);
9926 SDValue ExtVal = Extract.getOperand(1);
9927 if (Extract.getOperand(0) == VecIn1) {
9928 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9929 if (ExtIndex > VT.getVectorNumElements())
9932 Mask.push_back(ExtIndex);
9936 // Otherwise, use InIdx + VecSize
9937 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9938 Mask.push_back(Idx+NumInScalars);
9941 // We can't generate a shuffle node with mismatched input and output types.
9942 // Attempt to transform a single input vector to the correct type.
9943 if ((VT != VecIn1.getValueType())) {
9944 // We don't support shuffeling between TWO values of different types.
9945 if (VecIn2.getNode() != 0)
9948 // We only support widening of vectors which are half the size of the
9949 // output registers. For example XMM->YMM widening on X86 with AVX.
9950 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9953 // If the input vector type has a different base type to the output
9954 // vector type, bail out.
9955 if (VecIn1.getValueType().getVectorElementType() !=
9956 VT.getVectorElementType())
9959 // Widen the input vector by adding undef values.
9960 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9961 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9964 // If VecIn2 is unused then change it to undef.
9965 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9967 // Check that we were able to transform all incoming values to the same
9969 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9970 VecIn1.getValueType() != VT)
9973 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9974 if (!isTypeLegal(VT))
9977 // Return the new VECTOR_SHUFFLE node.
9981 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9987 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9988 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9989 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9990 // inputs come from at most two distinct vectors, turn this into a shuffle
9993 // If we only have one input vector, we don't need to do any concatenation.
9994 if (N->getNumOperands() == 1)
9995 return N->getOperand(0);
9997 // Check if all of the operands are undefs.
9998 EVT VT = N->getValueType(0);
9999 if (ISD::allOperandsUndef(N))
10000 return DAG.getUNDEF(VT);
10002 // Optimize concat_vectors where one of the vectors is undef.
10003 if (N->getNumOperands() == 2 &&
10004 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10005 SDValue In = N->getOperand(0);
10006 assert(In.getValueType().isVector() && "Must concat vectors");
10008 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10009 if (In->getOpcode() == ISD::BITCAST &&
10010 !In->getOperand(0)->getValueType(0).isVector()) {
10011 SDValue Scalar = In->getOperand(0);
10012 EVT SclTy = Scalar->getValueType(0);
10014 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10017 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10018 VT.getSizeInBits() / SclTy.getSizeInBits());
10019 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10022 SDLoc dl = SDLoc(N);
10023 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10024 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10028 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10029 // nodes often generate nop CONCAT_VECTOR nodes.
10030 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10031 // place the incoming vectors at the exact same location.
10032 SDValue SingleSource = SDValue();
10033 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10035 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10036 SDValue Op = N->getOperand(i);
10038 if (Op.getOpcode() == ISD::UNDEF)
10041 // Check if this is the identity extract:
10042 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10045 // Find the single incoming vector for the extract_subvector.
10046 if (SingleSource.getNode()) {
10047 if (Op.getOperand(0) != SingleSource)
10050 SingleSource = Op.getOperand(0);
10052 // Check the source type is the same as the type of the result.
10053 // If not, this concat may extend the vector, so we can not
10054 // optimize it away.
10055 if (SingleSource.getValueType() != N->getValueType(0))
10059 unsigned IdentityIndex = i * PartNumElem;
10060 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10061 // The extract index must be constant.
10065 // Check that we are reading from the identity index.
10066 if (CS->getZExtValue() != IdentityIndex)
10070 if (SingleSource.getNode())
10071 return SingleSource;
10076 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10077 EVT NVT = N->getValueType(0);
10078 SDValue V = N->getOperand(0);
10080 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10082 // (extract_subvec (concat V1, V2, ...), i)
10085 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10087 if (V->getOperand(0).getValueType() != NVT)
10089 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10090 unsigned NumElems = NVT.getVectorNumElements();
10091 assert((Idx % NumElems) == 0 &&
10092 "IDX in concat is not a multiple of the result vector length.");
10093 return V->getOperand(Idx / NumElems);
10097 if (V->getOpcode() == ISD::BITCAST)
10098 V = V.getOperand(0);
10100 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10102 // Handle only simple case where vector being inserted and vector
10103 // being extracted are of same type, and are half size of larger vectors.
10104 EVT BigVT = V->getOperand(0).getValueType();
10105 EVT SmallVT = V->getOperand(1).getValueType();
10106 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10109 // Only handle cases where both indexes are constants with the same type.
10110 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10111 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10113 if (InsIdx && ExtIdx &&
10114 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10115 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10117 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10119 // indices are equal or bit offsets are equal => V1
10120 // otherwise => (extract_subvec V1, ExtIdx)
10121 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10122 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10123 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10124 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10125 DAG.getNode(ISD::BITCAST, dl,
10126 N->getOperand(0).getValueType(),
10127 V->getOperand(0)), N->getOperand(1));
10134 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10135 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10136 EVT VT = N->getValueType(0);
10137 unsigned NumElts = VT.getVectorNumElements();
10139 SDValue N0 = N->getOperand(0);
10140 SDValue N1 = N->getOperand(1);
10141 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10143 SmallVector<SDValue, 4> Ops;
10144 EVT ConcatVT = N0.getOperand(0).getValueType();
10145 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10146 unsigned NumConcats = NumElts / NumElemsPerConcat;
10148 // Look at every vector that's inserted. We're looking for exact
10149 // subvector-sized copies from a concatenated vector
10150 for (unsigned I = 0; I != NumConcats; ++I) {
10151 // Make sure we're dealing with a copy.
10152 unsigned Begin = I * NumElemsPerConcat;
10153 bool AllUndef = true, NoUndef = true;
10154 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10155 if (SVN->getMaskElt(J) >= 0)
10162 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10165 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10166 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10169 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10170 if (FirstElt < N0.getNumOperands())
10171 Ops.push_back(N0.getOperand(FirstElt));
10173 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10175 } else if (AllUndef) {
10176 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10177 } else { // Mixed with general masks and undefs, can't do optimization.
10182 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10186 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10187 EVT VT = N->getValueType(0);
10188 unsigned NumElts = VT.getVectorNumElements();
10190 SDValue N0 = N->getOperand(0);
10191 SDValue N1 = N->getOperand(1);
10193 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10195 // Canonicalize shuffle undef, undef -> undef
10196 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10197 return DAG.getUNDEF(VT);
10199 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10201 // Canonicalize shuffle v, v -> v, undef
10203 SmallVector<int, 8> NewMask;
10204 for (unsigned i = 0; i != NumElts; ++i) {
10205 int Idx = SVN->getMaskElt(i);
10206 if (Idx >= (int)NumElts) Idx -= NumElts;
10207 NewMask.push_back(Idx);
10209 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10213 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10214 if (N0.getOpcode() == ISD::UNDEF) {
10215 SmallVector<int, 8> NewMask;
10216 for (unsigned i = 0; i != NumElts; ++i) {
10217 int Idx = SVN->getMaskElt(i);
10219 if (Idx >= (int)NumElts)
10222 Idx = -1; // remove reference to lhs
10224 NewMask.push_back(Idx);
10226 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10230 // Remove references to rhs if it is undef
10231 if (N1.getOpcode() == ISD::UNDEF) {
10232 bool Changed = false;
10233 SmallVector<int, 8> NewMask;
10234 for (unsigned i = 0; i != NumElts; ++i) {
10235 int Idx = SVN->getMaskElt(i);
10236 if (Idx >= (int)NumElts) {
10240 NewMask.push_back(Idx);
10243 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10246 // If it is a splat, check if the argument vector is another splat or a
10247 // build_vector with all scalar elements the same.
10248 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10249 SDNode *V = N0.getNode();
10251 // If this is a bit convert that changes the element type of the vector but
10252 // not the number of vector elements, look through it. Be careful not to
10253 // look though conversions that change things like v4f32 to v2f64.
10254 if (V->getOpcode() == ISD::BITCAST) {
10255 SDValue ConvInput = V->getOperand(0);
10256 if (ConvInput.getValueType().isVector() &&
10257 ConvInput.getValueType().getVectorNumElements() == NumElts)
10258 V = ConvInput.getNode();
10261 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10262 assert(V->getNumOperands() == NumElts &&
10263 "BUILD_VECTOR has wrong number of operands");
10265 bool AllSame = true;
10266 for (unsigned i = 0; i != NumElts; ++i) {
10267 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10268 Base = V->getOperand(i);
10272 // Splat of <u, u, u, u>, return <u, u, u, u>
10273 if (!Base.getNode())
10275 for (unsigned i = 0; i != NumElts; ++i) {
10276 if (V->getOperand(i) != Base) {
10281 // Splat of <x, x, x, x>, return <x, x, x, x>
10287 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10288 Level < AfterLegalizeVectorOps &&
10289 (N1.getOpcode() == ISD::UNDEF ||
10290 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10291 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10292 SDValue V = partitionShuffleOfConcats(N, DAG);
10298 // If this shuffle node is simply a swizzle of another shuffle node,
10299 // and it reverses the swizzle of the previous shuffle then we can
10300 // optimize shuffle(shuffle(x, undef), undef) -> x.
10301 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10302 N1.getOpcode() == ISD::UNDEF) {
10304 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10306 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10307 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10310 // The incoming shuffle must be of the same type as the result of the
10311 // current shuffle.
10312 assert(OtherSV->getOperand(0).getValueType() == VT &&
10313 "Shuffle types don't match");
10315 for (unsigned i = 0; i != NumElts; ++i) {
10316 int Idx = SVN->getMaskElt(i);
10317 assert(Idx < (int)NumElts && "Index references undef operand");
10318 // Next, this index comes from the first value, which is the incoming
10319 // shuffle. Adopt the incoming index.
10321 Idx = OtherSV->getMaskElt(Idx);
10323 // The combined shuffle must map each index to itself.
10324 if (Idx >= 0 && (unsigned)Idx != i)
10328 return OtherSV->getOperand(0);
10334 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10335 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10336 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10337 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10338 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10339 EVT VT = N->getValueType(0);
10341 SDValue LHS = N->getOperand(0);
10342 SDValue RHS = N->getOperand(1);
10343 if (N->getOpcode() == ISD::AND) {
10344 if (RHS.getOpcode() == ISD::BITCAST)
10345 RHS = RHS.getOperand(0);
10346 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10347 SmallVector<int, 8> Indices;
10348 unsigned NumElts = RHS.getNumOperands();
10349 for (unsigned i = 0; i != NumElts; ++i) {
10350 SDValue Elt = RHS.getOperand(i);
10351 if (!isa<ConstantSDNode>(Elt))
10354 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10355 Indices.push_back(i);
10356 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10357 Indices.push_back(NumElts);
10362 // Let's see if the target supports this vector_shuffle.
10363 EVT RVT = RHS.getValueType();
10364 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10367 // Return the new VECTOR_SHUFFLE node.
10368 EVT EltVT = RVT.getVectorElementType();
10369 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10370 DAG.getConstant(0, EltVT));
10371 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10372 RVT, &ZeroOps[0], ZeroOps.size());
10373 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10374 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10375 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10382 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10383 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10384 assert(N->getValueType(0).isVector() &&
10385 "SimplifyVBinOp only works on vectors!");
10387 SDValue LHS = N->getOperand(0);
10388 SDValue RHS = N->getOperand(1);
10389 SDValue Shuffle = XformToShuffleWithZero(N);
10390 if (Shuffle.getNode()) return Shuffle;
10392 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10394 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10395 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10396 // Check if both vectors are constants. If not bail out.
10397 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10398 cast<BuildVectorSDNode>(RHS)->isConstant()))
10401 SmallVector<SDValue, 8> Ops;
10402 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10403 SDValue LHSOp = LHS.getOperand(i);
10404 SDValue RHSOp = RHS.getOperand(i);
10406 // Can't fold divide by zero.
10407 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10408 N->getOpcode() == ISD::FDIV) {
10409 if ((RHSOp.getOpcode() == ISD::Constant &&
10410 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10411 (RHSOp.getOpcode() == ISD::ConstantFP &&
10412 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10416 EVT VT = LHSOp.getValueType();
10417 EVT RVT = RHSOp.getValueType();
10419 // Integer BUILD_VECTOR operands may have types larger than the element
10420 // size (e.g., when the element type is not legal). Prior to type
10421 // legalization, the types may not match between the two BUILD_VECTORS.
10422 // Truncate one of the operands to make them match.
10423 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10424 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10426 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10430 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10432 if (FoldOp.getOpcode() != ISD::UNDEF &&
10433 FoldOp.getOpcode() != ISD::Constant &&
10434 FoldOp.getOpcode() != ISD::ConstantFP)
10436 Ops.push_back(FoldOp);
10437 AddToWorkList(FoldOp.getNode());
10440 if (Ops.size() == LHS.getNumOperands())
10441 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10442 LHS.getValueType(), &Ops[0], Ops.size());
10448 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10449 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10450 assert(N->getValueType(0).isVector() &&
10451 "SimplifyVUnaryOp only works on vectors!");
10453 SDValue N0 = N->getOperand(0);
10455 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10458 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10459 SmallVector<SDValue, 8> Ops;
10460 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10461 SDValue Op = N0.getOperand(i);
10462 if (Op.getOpcode() != ISD::UNDEF &&
10463 Op.getOpcode() != ISD::ConstantFP)
10465 EVT EltVT = Op.getValueType();
10466 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10467 if (FoldOp.getOpcode() != ISD::UNDEF &&
10468 FoldOp.getOpcode() != ISD::ConstantFP)
10470 Ops.push_back(FoldOp);
10471 AddToWorkList(FoldOp.getNode());
10474 if (Ops.size() != N0.getNumOperands())
10477 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10478 N0.getValueType(), &Ops[0], Ops.size());
10481 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10482 SDValue N1, SDValue N2){
10483 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10485 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10486 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10488 // If we got a simplified select_cc node back from SimplifySelectCC, then
10489 // break it down into a new SETCC node, and a new SELECT node, and then return
10490 // the SELECT node, since we were called with a SELECT node.
10491 if (SCC.getNode()) {
10492 // Check to see if we got a select_cc back (to turn into setcc/select).
10493 // Otherwise, just return whatever node we got back, like fabs.
10494 if (SCC.getOpcode() == ISD::SELECT_CC) {
10495 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10497 SCC.getOperand(0), SCC.getOperand(1),
10498 SCC.getOperand(4));
10499 AddToWorkList(SETCC.getNode());
10500 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10501 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10509 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10510 /// are the two values being selected between, see if we can simplify the
10511 /// select. Callers of this should assume that TheSelect is deleted if this
10512 /// returns true. As such, they should return the appropriate thing (e.g. the
10513 /// node) back to the top-level of the DAG combiner loop to avoid it being
10515 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10518 // Cannot simplify select with vector condition
10519 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10521 // If this is a select from two identical things, try to pull the operation
10522 // through the select.
10523 if (LHS.getOpcode() != RHS.getOpcode() ||
10524 !LHS.hasOneUse() || !RHS.hasOneUse())
10527 // If this is a load and the token chain is identical, replace the select
10528 // of two loads with a load through a select of the address to load from.
10529 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10530 // constants have been dropped into the constant pool.
10531 if (LHS.getOpcode() == ISD::LOAD) {
10532 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10533 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10535 // Token chains must be identical.
10536 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10537 // Do not let this transformation reduce the number of volatile loads.
10538 LLD->isVolatile() || RLD->isVolatile() ||
10539 // If this is an EXTLOAD, the VT's must match.
10540 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10541 // If this is an EXTLOAD, the kind of extension must match.
10542 (LLD->getExtensionType() != RLD->getExtensionType() &&
10543 // The only exception is if one of the extensions is anyext.
10544 LLD->getExtensionType() != ISD::EXTLOAD &&
10545 RLD->getExtensionType() != ISD::EXTLOAD) ||
10546 // FIXME: this discards src value information. This is
10547 // over-conservative. It would be beneficial to be able to remember
10548 // both potential memory locations. Since we are discarding
10549 // src value info, don't do the transformation if the memory
10550 // locations are not in the default address space.
10551 LLD->getPointerInfo().getAddrSpace() != 0 ||
10552 RLD->getPointerInfo().getAddrSpace() != 0 ||
10553 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10554 LLD->getBasePtr().getValueType()))
10557 // Check that the select condition doesn't reach either load. If so,
10558 // folding this will induce a cycle into the DAG. If not, this is safe to
10559 // xform, so create a select of the addresses.
10561 if (TheSelect->getOpcode() == ISD::SELECT) {
10562 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10563 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10564 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10566 // The loads must not depend on one another.
10567 if (LLD->isPredecessorOf(RLD) ||
10568 RLD->isPredecessorOf(LLD))
10570 Addr = DAG.getSelect(SDLoc(TheSelect),
10571 LLD->getBasePtr().getValueType(),
10572 TheSelect->getOperand(0), LLD->getBasePtr(),
10573 RLD->getBasePtr());
10574 } else { // Otherwise SELECT_CC
10575 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10576 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10578 if ((LLD->hasAnyUseOfValue(1) &&
10579 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10580 (RLD->hasAnyUseOfValue(1) &&
10581 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10584 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10585 LLD->getBasePtr().getValueType(),
10586 TheSelect->getOperand(0),
10587 TheSelect->getOperand(1),
10588 LLD->getBasePtr(), RLD->getBasePtr(),
10589 TheSelect->getOperand(4));
10593 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10594 Load = DAG.getLoad(TheSelect->getValueType(0),
10596 // FIXME: Discards pointer and TBAA info.
10597 LLD->getChain(), Addr, MachinePointerInfo(),
10598 LLD->isVolatile(), LLD->isNonTemporal(),
10599 LLD->isInvariant(), LLD->getAlignment());
10601 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10602 RLD->getExtensionType() : LLD->getExtensionType(),
10604 TheSelect->getValueType(0),
10605 // FIXME: Discards pointer and TBAA info.
10606 LLD->getChain(), Addr, MachinePointerInfo(),
10607 LLD->getMemoryVT(), LLD->isVolatile(),
10608 LLD->isNonTemporal(), LLD->getAlignment());
10611 // Users of the select now use the result of the load.
10612 CombineTo(TheSelect, Load);
10614 // Users of the old loads now use the new load's chain. We know the
10615 // old-load value is dead now.
10616 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10617 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10624 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10625 /// where 'cond' is the comparison specified by CC.
10626 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10627 SDValue N2, SDValue N3,
10628 ISD::CondCode CC, bool NotExtCompare) {
10629 // (x ? y : y) -> y.
10630 if (N2 == N3) return N2;
10632 EVT VT = N2.getValueType();
10633 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10634 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10635 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10637 // Determine if the condition we're dealing with is constant
10638 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10639 N0, N1, CC, DL, false);
10640 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10641 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10643 // fold select_cc true, x, y -> x
10644 if (SCCC && !SCCC->isNullValue())
10646 // fold select_cc false, x, y -> y
10647 if (SCCC && SCCC->isNullValue())
10650 // Check to see if we can simplify the select into an fabs node
10651 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10652 // Allow either -0.0 or 0.0
10653 if (CFP->getValueAPF().isZero()) {
10654 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10655 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10656 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10657 N2 == N3.getOperand(0))
10658 return DAG.getNode(ISD::FABS, DL, VT, N0);
10660 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10661 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10662 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10663 N2.getOperand(0) == N3)
10664 return DAG.getNode(ISD::FABS, DL, VT, N3);
10668 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10669 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10670 // in it. This is a win when the constant is not otherwise available because
10671 // it replaces two constant pool loads with one. We only do this if the FP
10672 // type is known to be legal, because if it isn't, then we are before legalize
10673 // types an we want the other legalization to happen first (e.g. to avoid
10674 // messing with soft float) and if the ConstantFP is not legal, because if
10675 // it is legal, we may not need to store the FP constant in a constant pool.
10676 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10677 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10678 if (TLI.isTypeLegal(N2.getValueType()) &&
10679 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10680 TargetLowering::Legal) &&
10681 // If both constants have multiple uses, then we won't need to do an
10682 // extra load, they are likely around in registers for other users.
10683 (TV->hasOneUse() || FV->hasOneUse())) {
10684 Constant *Elts[] = {
10685 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10686 const_cast<ConstantFP*>(TV->getConstantFPValue())
10688 Type *FPTy = Elts[0]->getType();
10689 const DataLayout &TD = *TLI.getDataLayout();
10691 // Create a ConstantArray of the two constants.
10692 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10693 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10694 TD.getPrefTypeAlignment(FPTy));
10695 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10697 // Get the offsets to the 0 and 1 element of the array so that we can
10698 // select between them.
10699 SDValue Zero = DAG.getIntPtrConstant(0);
10700 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10701 SDValue One = DAG.getIntPtrConstant(EltSize);
10703 SDValue Cond = DAG.getSetCC(DL,
10704 getSetCCResultType(N0.getValueType()),
10706 AddToWorkList(Cond.getNode());
10707 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10709 AddToWorkList(CstOffset.getNode());
10710 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10712 AddToWorkList(CPIdx.getNode());
10713 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10714 MachinePointerInfo::getConstantPool(), false,
10715 false, false, Alignment);
10720 // Check to see if we can perform the "gzip trick", transforming
10721 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10722 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10723 (N1C->isNullValue() || // (a < 0) ? b : 0
10724 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10725 EVT XType = N0.getValueType();
10726 EVT AType = N2.getValueType();
10727 if (XType.bitsGE(AType)) {
10728 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10729 // single-bit constant.
10730 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10731 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10732 ShCtV = XType.getSizeInBits()-ShCtV-1;
10733 SDValue ShCt = DAG.getConstant(ShCtV,
10734 getShiftAmountTy(N0.getValueType()));
10735 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10737 AddToWorkList(Shift.getNode());
10739 if (XType.bitsGT(AType)) {
10740 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10741 AddToWorkList(Shift.getNode());
10744 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10747 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10749 DAG.getConstant(XType.getSizeInBits()-1,
10750 getShiftAmountTy(N0.getValueType())));
10751 AddToWorkList(Shift.getNode());
10753 if (XType.bitsGT(AType)) {
10754 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10755 AddToWorkList(Shift.getNode());
10758 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10762 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10763 // where y is has a single bit set.
10764 // A plaintext description would be, we can turn the SELECT_CC into an AND
10765 // when the condition can be materialized as an all-ones register. Any
10766 // single bit-test can be materialized as an all-ones register with
10767 // shift-left and shift-right-arith.
10768 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10769 N0->getValueType(0) == VT &&
10770 N1C && N1C->isNullValue() &&
10771 N2C && N2C->isNullValue()) {
10772 SDValue AndLHS = N0->getOperand(0);
10773 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10774 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10775 // Shift the tested bit over the sign bit.
10776 APInt AndMask = ConstAndRHS->getAPIntValue();
10778 DAG.getConstant(AndMask.countLeadingZeros(),
10779 getShiftAmountTy(AndLHS.getValueType()));
10780 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10782 // Now arithmetic right shift it all the way over, so the result is either
10783 // all-ones, or zero.
10785 DAG.getConstant(AndMask.getBitWidth()-1,
10786 getShiftAmountTy(Shl.getValueType()));
10787 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10789 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10793 // fold select C, 16, 0 -> shl C, 4
10794 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10795 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10796 TargetLowering::ZeroOrOneBooleanContent) {
10798 // If the caller doesn't want us to simplify this into a zext of a compare,
10800 if (NotExtCompare && N2C->getAPIntValue() == 1)
10803 // Get a SetCC of the condition
10804 // NOTE: Don't create a SETCC if it's not legal on this target.
10805 if (!LegalOperations ||
10806 TLI.isOperationLegal(ISD::SETCC,
10807 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10809 // cast from setcc result type to select result type
10811 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10813 if (N2.getValueType().bitsLT(SCC.getValueType()))
10814 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10815 N2.getValueType());
10817 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10818 N2.getValueType(), SCC);
10820 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10821 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10822 N2.getValueType(), SCC);
10825 AddToWorkList(SCC.getNode());
10826 AddToWorkList(Temp.getNode());
10828 if (N2C->getAPIntValue() == 1)
10831 // shl setcc result by log2 n2c
10832 return DAG.getNode(
10833 ISD::SHL, DL, N2.getValueType(), Temp,
10834 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10835 getShiftAmountTy(Temp.getValueType())));
10839 // Check to see if this is the equivalent of setcc
10840 // FIXME: Turn all of these into setcc if setcc if setcc is legal
10841 // otherwise, go ahead with the folds.
10842 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10843 EVT XType = N0.getValueType();
10844 if (!LegalOperations ||
10845 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10846 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10847 if (Res.getValueType() != VT)
10848 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10852 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10853 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10854 (!LegalOperations ||
10855 TLI.isOperationLegal(ISD::CTLZ, XType))) {
10856 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10857 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10858 DAG.getConstant(Log2_32(XType.getSizeInBits()),
10859 getShiftAmountTy(Ctlz.getValueType())));
10861 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10862 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10863 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10864 XType, DAG.getConstant(0, XType), N0);
10865 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10866 return DAG.getNode(ISD::SRL, DL, XType,
10867 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10868 DAG.getConstant(XType.getSizeInBits()-1,
10869 getShiftAmountTy(XType)));
10871 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10872 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10873 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10874 DAG.getConstant(XType.getSizeInBits()-1,
10875 getShiftAmountTy(N0.getValueType())));
10876 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10880 // Check to see if this is an integer abs.
10881 // select_cc setg[te] X, 0, X, -X ->
10882 // select_cc setgt X, -1, X, -X ->
10883 // select_cc setl[te] X, 0, -X, X ->
10884 // select_cc setlt X, 1, -X, X ->
10885 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10887 ConstantSDNode *SubC = NULL;
10888 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10889 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10890 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10891 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10892 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10893 (N1C->isOne() && CC == ISD::SETLT)) &&
10894 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10895 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10897 EVT XType = N0.getValueType();
10898 if (SubC && SubC->isNullValue() && XType.isInteger()) {
10899 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10901 DAG.getConstant(XType.getSizeInBits()-1,
10902 getShiftAmountTy(N0.getValueType())));
10903 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10905 AddToWorkList(Shift.getNode());
10906 AddToWorkList(Add.getNode());
10907 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10914 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10915 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10916 SDValue N1, ISD::CondCode Cond,
10917 SDLoc DL, bool foldBooleans) {
10918 TargetLowering::DAGCombinerInfo
10919 DagCombineInfo(DAG, Level, false, this);
10920 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10923 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10924 /// return a DAG expression to select that will generate the same value by
10925 /// multiplying by a magic number. See:
10926 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10927 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10928 std::vector<SDNode*> Built;
10929 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10931 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10933 AddToWorkList(*ii);
10937 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10938 /// return a DAG expression to select that will generate the same value by
10939 /// multiplying by a magic number. See:
10940 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10941 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10942 std::vector<SDNode*> Built;
10943 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10945 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10947 AddToWorkList(*ii);
10951 /// FindBaseOffset - Return true if base is a frame index, which is known not
10952 // to alias with anything but itself. Provides base object and offset as
10954 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10955 const GlobalValue *&GV, const void *&CV) {
10956 // Assume it is a primitive operation.
10957 Base = Ptr; Offset = 0; GV = 0; CV = 0;
10959 // If it's an adding a simple constant then integrate the offset.
10960 if (Base.getOpcode() == ISD::ADD) {
10961 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10962 Base = Base.getOperand(0);
10963 Offset += C->getZExtValue();
10967 // Return the underlying GlobalValue, and update the Offset. Return false
10968 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10969 // by multiple nodes with different offsets.
10970 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10971 GV = G->getGlobal();
10972 Offset += G->getOffset();
10976 // Return the underlying Constant value, and update the Offset. Return false
10977 // for ConstantSDNodes since the same constant pool entry may be represented
10978 // by multiple nodes with different offsets.
10979 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10980 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10981 : (const void *)C->getConstVal();
10982 Offset += C->getOffset();
10985 // If it's any of the following then it can't alias with anything but itself.
10986 return isa<FrameIndexSDNode>(Base);
10989 /// isAlias - Return true if there is any possibility that the two addresses
10991 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
10992 const Value *SrcValue1, int SrcValueOffset1,
10993 unsigned SrcValueAlign1,
10994 const MDNode *TBAAInfo1,
10995 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
10996 const Value *SrcValue2, int SrcValueOffset2,
10997 unsigned SrcValueAlign2,
10998 const MDNode *TBAAInfo2) const {
10999 // If they are the same then they must be aliases.
11000 if (Ptr1 == Ptr2) return true;
11002 // If they are both volatile then they cannot be reordered.
11003 if (IsVolatile1 && IsVolatile2) return true;
11005 // Gather base node and offset information.
11006 SDValue Base1, Base2;
11007 int64_t Offset1, Offset2;
11008 const GlobalValue *GV1, *GV2;
11009 const void *CV1, *CV2;
11010 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11011 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11013 // If they have a same base address then check to see if they overlap.
11014 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11015 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11017 // It is possible for different frame indices to alias each other, mostly
11018 // when tail call optimization reuses return address slots for arguments.
11019 // To catch this case, look up the actual index of frame indices to compute
11020 // the real alias relationship.
11021 if (isFrameIndex1 && isFrameIndex2) {
11022 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11023 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11024 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11025 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11028 // Otherwise, if we know what the bases are, and they aren't identical, then
11029 // we know they cannot alias.
11030 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11033 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11034 // compared to the size and offset of the access, we may be able to prove they
11035 // do not alias. This check is conservative for now to catch cases created by
11036 // splitting vector types.
11037 if ((SrcValueAlign1 == SrcValueAlign2) &&
11038 (SrcValueOffset1 != SrcValueOffset2) &&
11039 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11040 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11041 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11043 // There is no overlap between these relatively aligned accesses of similar
11044 // size, return no alias.
11045 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11049 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11050 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11051 if (UseAA && SrcValue1 && SrcValue2) {
11052 // Use alias analysis information.
11053 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11054 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11055 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11056 AliasAnalysis::AliasResult AAResult =
11057 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
11058 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
11059 if (AAResult == AliasAnalysis::NoAlias)
11063 // Otherwise we have to assume they alias.
11067 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11068 SDValue Ptr0, Ptr1;
11069 int64_t Size0, Size1;
11070 bool IsVolatile0, IsVolatile1;
11071 const Value *SrcValue0, *SrcValue1;
11072 int SrcValueOffset0, SrcValueOffset1;
11073 unsigned SrcValueAlign0, SrcValueAlign1;
11074 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11075 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11076 SrcValueAlign0, SrcTBAAInfo0);
11077 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11078 SrcValueAlign1, SrcTBAAInfo1);
11079 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11080 SrcValueAlign0, SrcTBAAInfo0,
11081 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11082 SrcValueAlign1, SrcTBAAInfo1);
11085 /// FindAliasInfo - Extracts the relevant alias information from the memory
11086 /// node. Returns true if the operand was a nonvolatile load.
11087 bool DAGCombiner::FindAliasInfo(SDNode *N,
11088 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11089 const Value *&SrcValue,
11090 int &SrcValueOffset,
11091 unsigned &SrcValueAlign,
11092 const MDNode *&TBAAInfo) const {
11093 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11095 Ptr = LS->getBasePtr();
11096 Size = LS->getMemoryVT().getSizeInBits() >> 3;
11097 IsVolatile = LS->isVolatile();
11098 SrcValue = LS->getSrcValue();
11099 SrcValueOffset = LS->getSrcValueOffset();
11100 SrcValueAlign = LS->getOriginalAlignment();
11101 TBAAInfo = LS->getTBAAInfo();
11102 return isa<LoadSDNode>(LS) && !IsVolatile;
11105 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11106 /// looking for aliasing nodes and adding them to the Aliases vector.
11107 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11108 SmallVectorImpl<SDValue> &Aliases) {
11109 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11110 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11112 // Get alias information for node.
11116 const Value *SrcValue;
11117 int SrcValueOffset;
11118 unsigned SrcValueAlign;
11119 const MDNode *SrcTBAAInfo;
11120 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11121 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11124 Chains.push_back(OriginalChain);
11125 unsigned Depth = 0;
11127 // Look at each chain and determine if it is an alias. If so, add it to the
11128 // aliases list. If not, then continue up the chain looking for the next
11130 while (!Chains.empty()) {
11131 SDValue Chain = Chains.back();
11134 // For TokenFactor nodes, look at each operand and only continue up the
11135 // chain until we find two aliases. If we've seen two aliases, assume we'll
11136 // find more and revert to original chain since the xform is unlikely to be
11139 // FIXME: The depth check could be made to return the last non-aliasing
11140 // chain we found before we hit a tokenfactor rather than the original
11142 if (Depth > 6 || Aliases.size() == 2) {
11144 Aliases.push_back(OriginalChain);
11148 // Don't bother if we've been before.
11149 if (!Visited.insert(Chain.getNode()))
11152 switch (Chain.getOpcode()) {
11153 case ISD::EntryToken:
11154 // Entry token is ideal chain operand, but handled in FindBetterChain.
11159 // Get alias information for Chain.
11163 const Value *OpSrcValue;
11164 int OpSrcValueOffset;
11165 unsigned OpSrcValueAlign;
11166 const MDNode *OpSrcTBAAInfo;
11167 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11168 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11172 // If chain is alias then stop here.
11173 if (!(IsLoad && IsOpLoad) &&
11174 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11175 SrcValueAlign, SrcTBAAInfo,
11176 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11177 OpSrcValueAlign, OpSrcTBAAInfo)) {
11178 Aliases.push_back(Chain);
11180 // Look further up the chain.
11181 Chains.push_back(Chain.getOperand(0));
11187 case ISD::TokenFactor:
11188 // We have to check each of the operands of the token factor for "small"
11189 // token factors, so we queue them up. Adding the operands to the queue
11190 // (stack) in reverse order maintains the original order and increases the
11191 // likelihood that getNode will find a matching token factor (CSE.)
11192 if (Chain.getNumOperands() > 16) {
11193 Aliases.push_back(Chain);
11196 for (unsigned n = Chain.getNumOperands(); n;)
11197 Chains.push_back(Chain.getOperand(--n));
11202 // For all other instructions we will just have to take what we can get.
11203 Aliases.push_back(Chain);
11208 // We need to be careful here to also search for aliases through the
11209 // value operand of a store, etc. Consider the following situation:
11211 // L1 = load Token1, %52
11212 // S1 = store Token1, L1, %51
11213 // L2 = load Token1, %52+8
11214 // S2 = store Token1, L2, %51+8
11215 // Token2 = Token(S1, S2)
11216 // L3 = load Token2, %53
11217 // S3 = store Token2, L3, %52
11218 // L4 = load Token2, %53+8
11219 // S4 = store Token2, L4, %52+8
11220 // If we search for aliases of S3 (which loads address %52), and we look
11221 // only through the chain, then we'll miss the trivial dependence on L1
11222 // (which also loads from %52). We then might change all loads and
11223 // stores to use Token1 as their chain operand, which could result in
11224 // copying %53 into %52 before copying %52 into %51 (which should
11227 // The problem is, however, that searching for such data dependencies
11228 // can become expensive, and the cost is not directly related to the
11229 // chain depth. Instead, we'll rule out such configurations here by
11230 // insisting that we've visited all chain users (except for users
11231 // of the original chain, which is not necessary). When doing this,
11232 // we need to look through nodes we don't care about (otherwise, things
11233 // like register copies will interfere with trivial cases).
11235 SmallVector<const SDNode *, 16> Worklist;
11236 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11237 IE = Visited.end(); I != IE; ++I)
11238 if (*I != OriginalChain.getNode())
11239 Worklist.push_back(*I);
11241 while (!Worklist.empty()) {
11242 const SDNode *M = Worklist.pop_back_val();
11244 // We have already visited M, and want to make sure we've visited any uses
11245 // of M that we care about. For uses that we've not visisted, and don't
11246 // care about, queue them to the worklist.
11248 for (SDNode::use_iterator UI = M->use_begin(),
11249 UIE = M->use_end(); UI != UIE; ++UI)
11250 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11251 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11252 // We've not visited this use, and we care about it (it could have an
11253 // ordering dependency with the original node).
11255 Aliases.push_back(OriginalChain);
11259 // We've not visited this use, but we don't care about it. Mark it as
11260 // visited and enqueue it to the worklist.
11261 Worklist.push_back(*UI);
11266 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11267 /// for a better chain (aliasing node.)
11268 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11269 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11271 // Accumulate all the aliases to this node.
11272 GatherAllAliases(N, OldChain, Aliases);
11274 // If no operands then chain to entry token.
11275 if (Aliases.size() == 0)
11276 return DAG.getEntryNode();
11278 // If a single operand then chain to it. We don't need to revisit it.
11279 if (Aliases.size() == 1)
11282 // Construct a custom tailored token factor.
11283 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11284 &Aliases[0], Aliases.size());
11287 // SelectionDAG::Combine - This is the entry point for the file.
11289 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11290 CodeGenOpt::Level OptLevel) {
11291 /// run - This is the main entry point to this class.
11293 DAGCombiner(*this, AA, OptLevel).Run(Level);