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 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "dagcombine"
16 #include "llvm/CodeGen/SelectionDAG.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Target/TargetFrameInfo.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
35 STATISTIC(NodesCombined , "Number of dag nodes combined");
36 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
37 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
41 CombinerAA("combiner-alias-analysis", cl::Hidden,
42 cl::desc("Turn on alias analysis during testing"));
45 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
46 cl::desc("Include global information in alias analysis"));
48 //------------------------------ DAGCombiner ---------------------------------//
50 class VISIBILITY_HIDDEN DAGCombiner {
55 // Worklist of all of the nodes that need to be simplified.
56 std::vector<SDNode*> WorkList;
58 // AA - Used for DAG load/store alias analysis.
61 /// AddUsersToWorkList - When an instruction is simplified, add all users of
62 /// the instruction to the work lists because they might get more simplified
65 void AddUsersToWorkList(SDNode *N) {
66 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
71 /// visit - call the node-specific routine that knows how to fold each
72 /// particular type of node.
73 SDOperand visit(SDNode *N);
76 /// AddToWorkList - Add to the work list making sure it's instance is at the
77 /// the back (next to be processed.)
78 void AddToWorkList(SDNode *N) {
79 removeFromWorkList(N);
80 WorkList.push_back(N);
83 /// removeFromWorkList - remove all instances of N from the worklist.
85 void removeFromWorkList(SDNode *N) {
86 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
90 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
93 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
94 return CombineTo(N, &Res, 1, AddTo);
97 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
99 SDOperand To[] = { Res0, Res1 };
100 return CombineTo(N, To, 2, AddTo);
105 /// SimplifyDemandedBits - Check the specified integer node value to see if
106 /// it can be simplified or if things it uses can be simplified by bit
107 /// propagation. If so, return true.
108 bool SimplifyDemandedBits(SDOperand Op) {
109 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
110 return SimplifyDemandedBits(Op, Demanded);
113 bool SimplifyDemandedBits(SDOperand Op, const APInt &Demanded);
115 bool CombineToPreIndexedLoadStore(SDNode *N);
116 bool CombineToPostIndexedLoadStore(SDNode *N);
119 /// combine - call the node-specific routine that knows how to fold each
120 /// particular type of node. If that doesn't do anything, try the
121 /// target-specific DAG combines.
122 SDOperand combine(SDNode *N);
124 // Visitation implementation - Implement dag node combining for different
125 // node types. The semantics are as follows:
127 // SDOperand.Val == 0 - No change was made
128 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
129 // otherwise - N should be replaced by the returned Operand.
131 SDOperand visitTokenFactor(SDNode *N);
132 SDOperand visitMERGE_VALUES(SDNode *N);
133 SDOperand visitADD(SDNode *N);
134 SDOperand visitSUB(SDNode *N);
135 SDOperand visitADDC(SDNode *N);
136 SDOperand visitADDE(SDNode *N);
137 SDOperand visitMUL(SDNode *N);
138 SDOperand visitSDIV(SDNode *N);
139 SDOperand visitUDIV(SDNode *N);
140 SDOperand visitSREM(SDNode *N);
141 SDOperand visitUREM(SDNode *N);
142 SDOperand visitMULHU(SDNode *N);
143 SDOperand visitMULHS(SDNode *N);
144 SDOperand visitSMUL_LOHI(SDNode *N);
145 SDOperand visitUMUL_LOHI(SDNode *N);
146 SDOperand visitSDIVREM(SDNode *N);
147 SDOperand visitUDIVREM(SDNode *N);
148 SDOperand visitAND(SDNode *N);
149 SDOperand visitOR(SDNode *N);
150 SDOperand visitXOR(SDNode *N);
151 SDOperand SimplifyVBinOp(SDNode *N);
152 SDOperand visitSHL(SDNode *N);
153 SDOperand visitSRA(SDNode *N);
154 SDOperand visitSRL(SDNode *N);
155 SDOperand visitCTLZ(SDNode *N);
156 SDOperand visitCTTZ(SDNode *N);
157 SDOperand visitCTPOP(SDNode *N);
158 SDOperand visitSELECT(SDNode *N);
159 SDOperand visitSELECT_CC(SDNode *N);
160 SDOperand visitSETCC(SDNode *N);
161 SDOperand visitSIGN_EXTEND(SDNode *N);
162 SDOperand visitZERO_EXTEND(SDNode *N);
163 SDOperand visitANY_EXTEND(SDNode *N);
164 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
165 SDOperand visitTRUNCATE(SDNode *N);
166 SDOperand visitBIT_CONVERT(SDNode *N);
167 SDOperand visitBUILD_PAIR(SDNode *N);
168 SDOperand visitFADD(SDNode *N);
169 SDOperand visitFSUB(SDNode *N);
170 SDOperand visitFMUL(SDNode *N);
171 SDOperand visitFDIV(SDNode *N);
172 SDOperand visitFREM(SDNode *N);
173 SDOperand visitFCOPYSIGN(SDNode *N);
174 SDOperand visitSINT_TO_FP(SDNode *N);
175 SDOperand visitUINT_TO_FP(SDNode *N);
176 SDOperand visitFP_TO_SINT(SDNode *N);
177 SDOperand visitFP_TO_UINT(SDNode *N);
178 SDOperand visitFP_ROUND(SDNode *N);
179 SDOperand visitFP_ROUND_INREG(SDNode *N);
180 SDOperand visitFP_EXTEND(SDNode *N);
181 SDOperand visitFNEG(SDNode *N);
182 SDOperand visitFABS(SDNode *N);
183 SDOperand visitBRCOND(SDNode *N);
184 SDOperand visitBR_CC(SDNode *N);
185 SDOperand visitLOAD(SDNode *N);
186 SDOperand visitSTORE(SDNode *N);
187 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
188 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
189 SDOperand visitBUILD_VECTOR(SDNode *N);
190 SDOperand visitCONCAT_VECTORS(SDNode *N);
191 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
193 SDOperand XformToShuffleWithZero(SDNode *N);
194 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
196 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
198 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
199 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
200 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
201 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
202 SDOperand N3, ISD::CondCode CC,
203 bool NotExtCompare = false);
204 SDOperand SimplifySetCC(MVT VT, SDOperand N0, SDOperand N1,
205 ISD::CondCode Cond, bool foldBooleans = true);
206 SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
208 SDOperand CombineConsecutiveLoads(SDNode *N, MVT VT);
209 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT);
210 SDOperand BuildSDIV(SDNode *N);
211 SDOperand BuildUDIV(SDNode *N);
212 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
213 SDOperand ReduceLoadWidth(SDNode *N);
215 SDOperand GetDemandedBits(SDOperand V, const APInt &Mask);
217 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
218 /// looking for aliasing nodes and adding them to the Aliases vector.
219 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
220 SmallVector<SDOperand, 8> &Aliases);
222 /// isAlias - Return true if there is any possibility that the two addresses
224 bool isAlias(SDOperand Ptr1, int64_t Size1,
225 const Value *SrcValue1, int SrcValueOffset1,
226 SDOperand Ptr2, int64_t Size2,
227 const Value *SrcValue2, int SrcValueOffset2);
229 /// FindAliasInfo - Extracts the relevant alias information from the memory
230 /// node. Returns true if the operand was a load.
231 bool FindAliasInfo(SDNode *N,
232 SDOperand &Ptr, int64_t &Size,
233 const Value *&SrcValue, int &SrcValueOffset);
235 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
236 /// looking for a better chain (aliasing node.)
237 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
240 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
242 TLI(D.getTargetLoweringInfo()),
243 AfterLegalize(false),
246 /// Run - runs the dag combiner on all nodes in the work list
247 void Run(bool RunningAfterLegalize);
253 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
254 /// nodes from the worklist.
255 class VISIBILITY_HIDDEN WorkListRemover :
256 public SelectionDAG::DAGUpdateListener {
259 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
261 virtual void NodeDeleted(SDNode *N, SDNode *E) {
262 DC.removeFromWorkList(N);
265 virtual void NodeUpdated(SDNode *N) {
271 //===----------------------------------------------------------------------===//
272 // TargetLowering::DAGCombinerInfo implementation
273 //===----------------------------------------------------------------------===//
275 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
276 ((DAGCombiner*)DC)->AddToWorkList(N);
279 SDOperand TargetLowering::DAGCombinerInfo::
280 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
281 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
284 SDOperand TargetLowering::DAGCombinerInfo::
285 CombineTo(SDNode *N, SDOperand Res) {
286 return ((DAGCombiner*)DC)->CombineTo(N, Res);
290 SDOperand TargetLowering::DAGCombinerInfo::
291 CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
292 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
296 //===----------------------------------------------------------------------===//
298 //===----------------------------------------------------------------------===//
300 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
301 /// specified expression for the same cost as the expression itself, or 2 if we
302 /// can compute the negated form more cheaply than the expression itself.
303 static char isNegatibleForFree(SDOperand Op, bool AfterLegalize,
304 unsigned Depth = 0) {
305 // No compile time optimizations on this type.
306 if (Op.getValueType() == MVT::ppcf128)
309 // fneg is removable even if it has multiple uses.
310 if (Op.getOpcode() == ISD::FNEG) return 2;
312 // Don't allow anything with multiple uses.
313 if (!Op.hasOneUse()) return 0;
315 // Don't recurse exponentially.
316 if (Depth > 6) return 0;
318 switch (Op.getOpcode()) {
319 default: return false;
320 case ISD::ConstantFP:
321 // Don't invert constant FP values after legalize. The negated constant
322 // isn't necessarily legal.
323 return AfterLegalize ? 0 : 1;
325 // FIXME: determine better conditions for this xform.
326 if (!UnsafeFPMath) return 0;
329 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
332 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
334 // We can't turn -(A-B) into B-A when we honor signed zeros.
335 if (!UnsafeFPMath) return 0;
342 if (HonorSignDependentRoundingFPMath()) return 0;
344 // -(X*Y) -> (-X * Y) or (X*-Y)
345 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
348 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
353 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
357 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
358 /// returns the newly negated expression.
359 static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
360 bool AfterLegalize, unsigned Depth = 0) {
361 // fneg is removable even if it has multiple uses.
362 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
364 // Don't allow anything with multiple uses.
365 assert(Op.hasOneUse() && "Unknown reuse!");
367 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
368 switch (Op.getOpcode()) {
369 default: assert(0 && "Unknown code");
370 case ISD::ConstantFP: {
371 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
373 return DAG.getConstantFP(V, Op.getValueType());
376 // FIXME: determine better conditions for this xform.
377 assert(UnsafeFPMath);
380 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
381 return DAG.getNode(ISD::FSUB, Op.getValueType(),
382 GetNegatedExpression(Op.getOperand(0), DAG,
383 AfterLegalize, Depth+1),
386 return DAG.getNode(ISD::FSUB, Op.getValueType(),
387 GetNegatedExpression(Op.getOperand(1), DAG,
388 AfterLegalize, Depth+1),
391 // We can't turn -(A-B) into B-A when we honor signed zeros.
392 assert(UnsafeFPMath);
395 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
396 if (N0CFP->getValueAPF().isZero())
397 return Op.getOperand(1);
400 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
405 assert(!HonorSignDependentRoundingFPMath());
408 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
409 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
410 GetNegatedExpression(Op.getOperand(0), DAG,
411 AfterLegalize, Depth+1),
415 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
417 GetNegatedExpression(Op.getOperand(1), DAG,
418 AfterLegalize, Depth+1));
422 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
423 GetNegatedExpression(Op.getOperand(0), DAG,
424 AfterLegalize, Depth+1));
426 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
427 GetNegatedExpression(Op.getOperand(0), DAG,
428 AfterLegalize, Depth+1),
434 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
435 // that selects between the values 1 and 0, making it equivalent to a setcc.
436 // Also, set the incoming LHS, RHS, and CC references to the appropriate
437 // nodes based on the type of node we are checking. This simplifies life a
438 // bit for the callers.
439 static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
441 if (N.getOpcode() == ISD::SETCC) {
442 LHS = N.getOperand(0);
443 RHS = N.getOperand(1);
444 CC = N.getOperand(2);
447 if (N.getOpcode() == ISD::SELECT_CC &&
448 N.getOperand(2).getOpcode() == ISD::Constant &&
449 N.getOperand(3).getOpcode() == ISD::Constant &&
450 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
451 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
452 LHS = N.getOperand(0);
453 RHS = N.getOperand(1);
454 CC = N.getOperand(4);
460 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
461 // one use. If this is true, it allows the users to invert the operation for
462 // free when it is profitable to do so.
463 static bool isOneUseSetCC(SDOperand N) {
464 SDOperand N0, N1, N2;
465 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
470 SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
471 MVT VT = N0.getValueType();
472 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
473 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
474 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
475 if (isa<ConstantSDNode>(N1)) {
476 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
477 AddToWorkList(OpNode.Val);
478 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
479 } else if (N0.hasOneUse()) {
480 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
481 AddToWorkList(OpNode.Val);
482 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
485 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
486 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
487 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
488 if (isa<ConstantSDNode>(N0)) {
489 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
490 AddToWorkList(OpNode.Val);
491 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
492 } else if (N1.hasOneUse()) {
493 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
494 AddToWorkList(OpNode.Val);
495 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
501 SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
503 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
505 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
506 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
507 DOUT << " and " << NumTo-1 << " other values\n";
508 WorkListRemover DeadNodes(*this);
509 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
512 // Push the new nodes and any users onto the worklist
513 for (unsigned i = 0, e = NumTo; i != e; ++i) {
514 AddToWorkList(To[i].Val);
515 AddUsersToWorkList(To[i].Val);
519 // Nodes can be reintroduced into the worklist. Make sure we do not
520 // process a node that has been replaced.
521 removeFromWorkList(N);
523 // Finally, since the node is now dead, remove it from the graph.
525 return SDOperand(N, 0);
528 /// SimplifyDemandedBits - Check the specified integer node value to see if
529 /// it can be simplified or if things it uses can be simplified by bit
530 /// propagation. If so, return true.
531 bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, const APInt &Demanded) {
532 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
533 APInt KnownZero, KnownOne;
534 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
538 AddToWorkList(Op.Val);
540 // Replace the old value with the new one.
542 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
543 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
546 // Replace all uses. If any nodes become isomorphic to other nodes and
547 // are deleted, make sure to remove them from our worklist.
548 WorkListRemover DeadNodes(*this);
549 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
551 // Push the new node and any (possibly new) users onto the worklist.
552 AddToWorkList(TLO.New.Val);
553 AddUsersToWorkList(TLO.New.Val);
555 // Finally, if the node is now dead, remove it from the graph. The node
556 // may not be dead if the replacement process recursively simplified to
557 // something else needing this node.
558 if (TLO.Old.Val->use_empty()) {
559 removeFromWorkList(TLO.Old.Val);
561 // If the operands of this node are only used by the node, they will now
562 // be dead. Make sure to visit them first to delete dead nodes early.
563 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
564 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
565 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
567 DAG.DeleteNode(TLO.Old.Val);
572 //===----------------------------------------------------------------------===//
573 // Main DAG Combiner implementation
574 //===----------------------------------------------------------------------===//
576 void DAGCombiner::Run(bool RunningAfterLegalize) {
577 // set the instance variable, so that the various visit routines may use it.
578 AfterLegalize = RunningAfterLegalize;
580 // Add all the dag nodes to the worklist.
581 WorkList.reserve(DAG.allnodes_size());
582 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
583 E = DAG.allnodes_end(); I != E; ++I)
584 WorkList.push_back(I);
586 // Create a dummy node (which is not added to allnodes), that adds a reference
587 // to the root node, preventing it from being deleted, and tracking any
588 // changes of the root.
589 HandleSDNode Dummy(DAG.getRoot());
591 // The root of the dag may dangle to deleted nodes until the dag combiner is
592 // done. Set it to null to avoid confusion.
593 DAG.setRoot(SDOperand());
595 // while the worklist isn't empty, inspect the node on the end of it and
596 // try and combine it.
597 while (!WorkList.empty()) {
598 SDNode *N = WorkList.back();
601 // If N has no uses, it is dead. Make sure to revisit all N's operands once
602 // N is deleted from the DAG, since they too may now be dead or may have a
603 // reduced number of uses, allowing other xforms.
604 if (N->use_empty() && N != &Dummy) {
605 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
606 AddToWorkList(N->getOperand(i).Val);
612 SDOperand RV = combine(N);
619 // If we get back the same node we passed in, rather than a new node or
620 // zero, we know that the node must have defined multiple values and
621 // CombineTo was used. Since CombineTo takes care of the worklist
622 // mechanics for us, we have no work to do in this case.
626 assert(N->getOpcode() != ISD::DELETED_NODE &&
627 RV.Val->getOpcode() != ISD::DELETED_NODE &&
628 "Node was deleted but visit returned new node!");
630 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
631 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
633 WorkListRemover DeadNodes(*this);
634 if (N->getNumValues() == RV.Val->getNumValues())
635 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
637 assert(N->getValueType(0) == RV.getValueType() &&
638 N->getNumValues() == 1 && "Type mismatch");
640 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
643 // Push the new node and any users onto the worklist
644 AddToWorkList(RV.Val);
645 AddUsersToWorkList(RV.Val);
647 // Add any uses of the old node to the worklist in case this node is the
648 // last one that uses them. They may become dead after this node is
650 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
651 AddToWorkList(N->getOperand(i).Val);
653 // Nodes can be reintroduced into the worklist. Make sure we do not
654 // process a node that has been replaced.
655 removeFromWorkList(N);
657 // Finally, since the node is now dead, remove it from the graph.
661 // If the root changed (e.g. it was a dead load, update the root).
662 DAG.setRoot(Dummy.getValue());
665 SDOperand DAGCombiner::visit(SDNode *N) {
666 switch(N->getOpcode()) {
668 case ISD::TokenFactor: return visitTokenFactor(N);
669 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
670 case ISD::ADD: return visitADD(N);
671 case ISD::SUB: return visitSUB(N);
672 case ISD::ADDC: return visitADDC(N);
673 case ISD::ADDE: return visitADDE(N);
674 case ISD::MUL: return visitMUL(N);
675 case ISD::SDIV: return visitSDIV(N);
676 case ISD::UDIV: return visitUDIV(N);
677 case ISD::SREM: return visitSREM(N);
678 case ISD::UREM: return visitUREM(N);
679 case ISD::MULHU: return visitMULHU(N);
680 case ISD::MULHS: return visitMULHS(N);
681 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
682 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
683 case ISD::SDIVREM: return visitSDIVREM(N);
684 case ISD::UDIVREM: return visitUDIVREM(N);
685 case ISD::AND: return visitAND(N);
686 case ISD::OR: return visitOR(N);
687 case ISD::XOR: return visitXOR(N);
688 case ISD::SHL: return visitSHL(N);
689 case ISD::SRA: return visitSRA(N);
690 case ISD::SRL: return visitSRL(N);
691 case ISD::CTLZ: return visitCTLZ(N);
692 case ISD::CTTZ: return visitCTTZ(N);
693 case ISD::CTPOP: return visitCTPOP(N);
694 case ISD::SELECT: return visitSELECT(N);
695 case ISD::SELECT_CC: return visitSELECT_CC(N);
696 case ISD::SETCC: return visitSETCC(N);
697 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
698 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
699 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
700 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
701 case ISD::TRUNCATE: return visitTRUNCATE(N);
702 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
703 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
704 case ISD::FADD: return visitFADD(N);
705 case ISD::FSUB: return visitFSUB(N);
706 case ISD::FMUL: return visitFMUL(N);
707 case ISD::FDIV: return visitFDIV(N);
708 case ISD::FREM: return visitFREM(N);
709 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
710 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
711 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
712 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
713 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
714 case ISD::FP_ROUND: return visitFP_ROUND(N);
715 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
716 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
717 case ISD::FNEG: return visitFNEG(N);
718 case ISD::FABS: return visitFABS(N);
719 case ISD::BRCOND: return visitBRCOND(N);
720 case ISD::BR_CC: return visitBR_CC(N);
721 case ISD::LOAD: return visitLOAD(N);
722 case ISD::STORE: return visitSTORE(N);
723 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
724 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
725 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
726 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
727 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
732 SDOperand DAGCombiner::combine(SDNode *N) {
734 SDOperand RV = visit(N);
736 // If nothing happened, try a target-specific DAG combine.
738 assert(N->getOpcode() != ISD::DELETED_NODE &&
739 "Node was deleted but visit returned NULL!");
741 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
742 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
744 // Expose the DAG combiner to the target combiner impls.
745 TargetLowering::DAGCombinerInfo
746 DagCombineInfo(DAG, !AfterLegalize, false, this);
748 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
752 // If N is a commutative binary node, try commuting it to enable more
755 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
756 N->getNumValues() == 1) {
757 SDOperand N0 = N->getOperand(0);
758 SDOperand N1 = N->getOperand(1);
759 // Constant operands are canonicalized to RHS.
760 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
761 SDOperand Ops[] = { N1, N0 };
762 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
765 return SDOperand(CSENode, 0);
772 /// getInputChainForNode - Given a node, return its input chain if it has one,
773 /// otherwise return a null sd operand.
774 static SDOperand getInputChainForNode(SDNode *N) {
775 if (unsigned NumOps = N->getNumOperands()) {
776 if (N->getOperand(0).getValueType() == MVT::Other)
777 return N->getOperand(0);
778 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
779 return N->getOperand(NumOps-1);
780 for (unsigned i = 1; i < NumOps-1; ++i)
781 if (N->getOperand(i).getValueType() == MVT::Other)
782 return N->getOperand(i);
784 return SDOperand(0, 0);
787 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
788 // If N has two operands, where one has an input chain equal to the other,
789 // the 'other' chain is redundant.
790 if (N->getNumOperands() == 2) {
791 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
792 return N->getOperand(0);
793 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
794 return N->getOperand(1);
797 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
798 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
799 SmallPtrSet<SDNode*, 16> SeenOps;
800 bool Changed = false; // If we should replace this token factor.
802 // Start out with this token factor.
805 // Iterate through token factors. The TFs grows when new token factors are
807 for (unsigned i = 0; i < TFs.size(); ++i) {
810 // Check each of the operands.
811 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
812 SDOperand Op = TF->getOperand(i);
814 switch (Op.getOpcode()) {
815 case ISD::EntryToken:
816 // Entry tokens don't need to be added to the list. They are
821 case ISD::TokenFactor:
822 if ((CombinerAA || Op.hasOneUse()) &&
823 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
824 // Queue up for processing.
825 TFs.push_back(Op.Val);
826 // Clean up in case the token factor is removed.
827 AddToWorkList(Op.Val);
834 // Only add if it isn't already in the list.
835 if (SeenOps.insert(Op.Val))
846 // If we've change things around then replace token factor.
849 // The entry token is the only possible outcome.
850 Result = DAG.getEntryNode();
852 // New and improved token factor.
853 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
856 // Don't add users to work list.
857 return CombineTo(N, Result, false);
863 /// MERGE_VALUES can always be eliminated.
864 SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
865 WorkListRemover DeadNodes(*this);
866 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
867 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
869 removeFromWorkList(N);
871 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
876 SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
877 MVT VT = N0.getValueType();
878 SDOperand N00 = N0.getOperand(0);
879 SDOperand N01 = N0.getOperand(1);
880 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
881 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
882 isa<ConstantSDNode>(N00.getOperand(1))) {
883 N0 = DAG.getNode(ISD::ADD, VT,
884 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
885 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
886 return DAG.getNode(ISD::ADD, VT, N0, N1);
892 SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
894 MVT VT = N->getValueType(0);
895 unsigned Opc = N->getOpcode();
896 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
897 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
898 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
899 ISD::CondCode CC = ISD::SETCC_INVALID;
901 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
903 SDOperand CCOp = Slct.getOperand(0);
904 if (CCOp.getOpcode() == ISD::SETCC)
905 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
908 bool DoXform = false;
910 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
912 if (LHS.getOpcode() == ISD::Constant &&
913 cast<ConstantSDNode>(LHS)->isNullValue())
915 else if (CC != ISD::SETCC_INVALID &&
916 RHS.getOpcode() == ISD::Constant &&
917 cast<ConstantSDNode>(RHS)->isNullValue()) {
919 SDOperand Op0 = Slct.getOperand(0);
920 bool isInt = (isSlctCC ? Op0.getValueType() :
921 Op0.getOperand(0).getValueType()).isInteger();
922 CC = ISD::getSetCCInverse(CC, isInt);
928 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
930 return DAG.getSelectCC(OtherOp, Result,
931 Slct.getOperand(0), Slct.getOperand(1), CC);
932 SDOperand CCOp = Slct.getOperand(0);
934 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
935 CCOp.getOperand(1), CC);
936 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
941 SDOperand DAGCombiner::visitADD(SDNode *N) {
942 SDOperand N0 = N->getOperand(0);
943 SDOperand N1 = N->getOperand(1);
944 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
945 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
946 MVT VT = N0.getValueType();
950 SDOperand FoldedVOp = SimplifyVBinOp(N);
951 if (FoldedVOp.Val) return FoldedVOp;
954 // fold (add x, undef) -> undef
955 if (N0.getOpcode() == ISD::UNDEF)
957 if (N1.getOpcode() == ISD::UNDEF)
959 // fold (add c1, c2) -> c1+c2
961 return DAG.getConstant(N0C->getAPIntValue() + N1C->getAPIntValue(), VT);
962 // canonicalize constant to RHS
964 return DAG.getNode(ISD::ADD, VT, N1, N0);
965 // fold (add x, 0) -> x
966 if (N1C && N1C->isNullValue())
968 // fold ((c1-A)+c2) -> (c1+c2)-A
969 if (N1C && N0.getOpcode() == ISD::SUB)
970 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
971 return DAG.getNode(ISD::SUB, VT,
972 DAG.getConstant(N1C->getAPIntValue()+
973 N0C->getAPIntValue(), VT),
976 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
979 // fold ((0-A) + B) -> B-A
980 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
981 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
982 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
983 // fold (A + (0-B)) -> A-B
984 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
985 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
986 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
987 // fold (A+(B-A)) -> B
988 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
989 return N1.getOperand(0);
991 if (!VT.isVector() && SimplifyDemandedBits(SDOperand(N, 0)))
992 return SDOperand(N, 0);
994 // fold (a+b) -> (a|b) iff a and b share no bits.
995 if (VT.isInteger() && !VT.isVector()) {
996 APInt LHSZero, LHSOne;
997 APInt RHSZero, RHSOne;
998 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
999 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1000 if (LHSZero.getBoolValue()) {
1001 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1003 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1004 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1005 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1006 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1007 return DAG.getNode(ISD::OR, VT, N0, N1);
1011 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1012 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
1013 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
1014 if (Result.Val) return Result;
1016 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
1017 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
1018 if (Result.Val) return Result;
1021 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1022 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
1023 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
1024 if (Result.Val) return Result;
1026 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1027 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1028 if (Result.Val) return Result;
1034 SDOperand DAGCombiner::visitADDC(SDNode *N) {
1035 SDOperand N0 = N->getOperand(0);
1036 SDOperand N1 = N->getOperand(1);
1037 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1038 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1039 MVT VT = N0.getValueType();
1041 // If the flag result is dead, turn this into an ADD.
1042 if (N->hasNUsesOfValue(0, 1))
1043 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1044 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1046 // canonicalize constant to RHS.
1048 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1050 // fold (addc x, 0) -> x + no carry out
1051 if (N1C && N1C->isNullValue())
1052 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1054 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1055 APInt LHSZero, LHSOne;
1056 APInt RHSZero, RHSOne;
1057 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1058 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1059 if (LHSZero.getBoolValue()) {
1060 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1062 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1063 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1064 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1065 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1066 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1067 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1073 SDOperand DAGCombiner::visitADDE(SDNode *N) {
1074 SDOperand N0 = N->getOperand(0);
1075 SDOperand N1 = N->getOperand(1);
1076 SDOperand CarryIn = N->getOperand(2);
1077 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1078 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1079 //MVT VT = N0.getValueType();
1081 // canonicalize constant to RHS
1083 return DAG.getNode(ISD::ADDE, N->getVTList(), N1, N0, CarryIn);
1085 // fold (adde x, y, false) -> (addc x, y)
1086 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1087 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1094 SDOperand DAGCombiner::visitSUB(SDNode *N) {
1095 SDOperand N0 = N->getOperand(0);
1096 SDOperand N1 = N->getOperand(1);
1097 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1098 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1099 MVT VT = N0.getValueType();
1102 if (VT.isVector()) {
1103 SDOperand FoldedVOp = SimplifyVBinOp(N);
1104 if (FoldedVOp.Val) return FoldedVOp;
1107 // fold (sub x, x) -> 0
1109 return DAG.getConstant(0, N->getValueType(0));
1110 // fold (sub c1, c2) -> c1-c2
1112 return DAG.getNode(ISD::SUB, VT, N0, N1);
1113 // fold (sub x, c) -> (add x, -c)
1115 return DAG.getNode(ISD::ADD, VT, N0,
1116 DAG.getConstant(-N1C->getAPIntValue(), VT));
1117 // fold (A+B)-A -> B
1118 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1119 return N0.getOperand(1);
1120 // fold (A+B)-B -> A
1121 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1122 return N0.getOperand(0);
1123 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1124 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1125 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1126 if (Result.Val) return Result;
1128 // If either operand of a sub is undef, the result is undef
1129 if (N0.getOpcode() == ISD::UNDEF)
1131 if (N1.getOpcode() == ISD::UNDEF)
1137 SDOperand DAGCombiner::visitMUL(SDNode *N) {
1138 SDOperand N0 = N->getOperand(0);
1139 SDOperand N1 = N->getOperand(1);
1140 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1141 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1142 MVT VT = N0.getValueType();
1145 if (VT.isVector()) {
1146 SDOperand FoldedVOp = SimplifyVBinOp(N);
1147 if (FoldedVOp.Val) return FoldedVOp;
1150 // fold (mul x, undef) -> 0
1151 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1152 return DAG.getConstant(0, VT);
1153 // fold (mul c1, c2) -> c1*c2
1155 return DAG.getNode(ISD::MUL, VT, N0, N1);
1156 // canonicalize constant to RHS
1158 return DAG.getNode(ISD::MUL, VT, N1, N0);
1159 // fold (mul x, 0) -> 0
1160 if (N1C && N1C->isNullValue())
1162 // fold (mul x, -1) -> 0-x
1163 if (N1C && N1C->isAllOnesValue())
1164 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1165 // fold (mul x, (1 << c)) -> x << c
1166 if (N1C && N1C->getAPIntValue().isPowerOf2())
1167 return DAG.getNode(ISD::SHL, VT, N0,
1168 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1169 TLI.getShiftAmountTy()));
1170 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1171 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1172 // FIXME: If the input is something that is easily negated (e.g. a
1173 // single-use add), we should put the negate there.
1174 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1175 DAG.getNode(ISD::SHL, VT, N0,
1176 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1177 TLI.getShiftAmountTy())));
1180 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1181 if (N1C && N0.getOpcode() == ISD::SHL &&
1182 isa<ConstantSDNode>(N0.getOperand(1))) {
1183 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1184 AddToWorkList(C3.Val);
1185 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1188 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1191 SDOperand Sh(0,0), Y(0,0);
1192 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1193 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1194 N0.Val->hasOneUse()) {
1196 } else if (N1.getOpcode() == ISD::SHL &&
1197 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1201 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1202 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1205 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1206 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1207 isa<ConstantSDNode>(N0.getOperand(1))) {
1208 return DAG.getNode(ISD::ADD, VT,
1209 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1210 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1214 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1221 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1222 SDOperand N0 = N->getOperand(0);
1223 SDOperand N1 = N->getOperand(1);
1224 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1225 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1226 MVT VT = N->getValueType(0);
1229 if (VT.isVector()) {
1230 SDOperand FoldedVOp = SimplifyVBinOp(N);
1231 if (FoldedVOp.Val) return FoldedVOp;
1234 // fold (sdiv c1, c2) -> c1/c2
1235 if (N0C && N1C && !N1C->isNullValue())
1236 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1237 // fold (sdiv X, 1) -> X
1238 if (N1C && N1C->getSignExtended() == 1LL)
1240 // fold (sdiv X, -1) -> 0-X
1241 if (N1C && N1C->isAllOnesValue())
1242 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1243 // If we know the sign bits of both operands are zero, strength reduce to a
1244 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1245 if (!VT.isVector()) {
1246 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1247 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1249 // fold (sdiv X, pow2) -> simple ops after legalize
1250 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1251 (isPowerOf2_64(N1C->getSignExtended()) ||
1252 isPowerOf2_64(-N1C->getSignExtended()))) {
1253 // If dividing by powers of two is cheap, then don't perform the following
1255 if (TLI.isPow2DivCheap())
1257 int64_t pow2 = N1C->getSignExtended();
1258 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1259 unsigned lg2 = Log2_64(abs2);
1260 // Splat the sign bit into the register
1261 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1262 DAG.getConstant(VT.getSizeInBits()-1,
1263 TLI.getShiftAmountTy()));
1264 AddToWorkList(SGN.Val);
1265 // Add (N0 < 0) ? abs2 - 1 : 0;
1266 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1267 DAG.getConstant(VT.getSizeInBits()-lg2,
1268 TLI.getShiftAmountTy()));
1269 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1270 AddToWorkList(SRL.Val);
1271 AddToWorkList(ADD.Val); // Divide by pow2
1272 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1273 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1274 // If we're dividing by a positive value, we're done. Otherwise, we must
1275 // negate the result.
1278 AddToWorkList(SRA.Val);
1279 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1281 // if integer divide is expensive and we satisfy the requirements, emit an
1282 // alternate sequence.
1283 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1284 !TLI.isIntDivCheap()) {
1285 SDOperand Op = BuildSDIV(N);
1286 if (Op.Val) return Op;
1290 if (N0.getOpcode() == ISD::UNDEF)
1291 return DAG.getConstant(0, VT);
1292 // X / undef -> undef
1293 if (N1.getOpcode() == ISD::UNDEF)
1299 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1300 SDOperand N0 = N->getOperand(0);
1301 SDOperand N1 = N->getOperand(1);
1302 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1303 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1304 MVT VT = N->getValueType(0);
1307 if (VT.isVector()) {
1308 SDOperand FoldedVOp = SimplifyVBinOp(N);
1309 if (FoldedVOp.Val) return FoldedVOp;
1312 // fold (udiv c1, c2) -> c1/c2
1313 if (N0C && N1C && !N1C->isNullValue())
1314 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1315 // fold (udiv x, (1 << c)) -> x >>u c
1316 if (N1C && N1C->getAPIntValue().isPowerOf2())
1317 return DAG.getNode(ISD::SRL, VT, N0,
1318 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1319 TLI.getShiftAmountTy()));
1320 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1321 if (N1.getOpcode() == ISD::SHL) {
1322 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1323 if (SHC->getAPIntValue().isPowerOf2()) {
1324 MVT ADDVT = N1.getOperand(1).getValueType();
1325 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1326 DAG.getConstant(SHC->getAPIntValue()
1329 AddToWorkList(Add.Val);
1330 return DAG.getNode(ISD::SRL, VT, N0, Add);
1334 // fold (udiv x, c) -> alternate
1335 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1336 SDOperand Op = BuildUDIV(N);
1337 if (Op.Val) return Op;
1341 if (N0.getOpcode() == ISD::UNDEF)
1342 return DAG.getConstant(0, VT);
1343 // X / undef -> undef
1344 if (N1.getOpcode() == ISD::UNDEF)
1350 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1351 SDOperand N0 = N->getOperand(0);
1352 SDOperand N1 = N->getOperand(1);
1353 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1354 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1355 MVT VT = N->getValueType(0);
1357 // fold (srem c1, c2) -> c1%c2
1358 if (N0C && N1C && !N1C->isNullValue())
1359 return DAG.getNode(ISD::SREM, VT, N0, N1);
1360 // If we know the sign bits of both operands are zero, strength reduce to a
1361 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1362 if (!VT.isVector()) {
1363 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1364 return DAG.getNode(ISD::UREM, VT, N0, N1);
1367 // If X/C can be simplified by the division-by-constant logic, lower
1368 // X%C to the equivalent of X-X/C*C.
1369 if (N1C && !N1C->isNullValue()) {
1370 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1371 AddToWorkList(Div.Val);
1372 SDOperand OptimizedDiv = combine(Div.Val);
1373 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1374 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1375 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1376 AddToWorkList(Mul.Val);
1382 if (N0.getOpcode() == ISD::UNDEF)
1383 return DAG.getConstant(0, VT);
1384 // X % undef -> undef
1385 if (N1.getOpcode() == ISD::UNDEF)
1391 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1392 SDOperand N0 = N->getOperand(0);
1393 SDOperand N1 = N->getOperand(1);
1394 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1395 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1396 MVT VT = N->getValueType(0);
1398 // fold (urem c1, c2) -> c1%c2
1399 if (N0C && N1C && !N1C->isNullValue())
1400 return DAG.getNode(ISD::UREM, VT, N0, N1);
1401 // fold (urem x, pow2) -> (and x, pow2-1)
1402 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1403 return DAG.getNode(ISD::AND, VT, N0,
1404 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1405 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1406 if (N1.getOpcode() == ISD::SHL) {
1407 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1408 if (SHC->getAPIntValue().isPowerOf2()) {
1410 DAG.getNode(ISD::ADD, VT, N1,
1411 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1413 AddToWorkList(Add.Val);
1414 return DAG.getNode(ISD::AND, VT, N0, Add);
1419 // If X/C can be simplified by the division-by-constant logic, lower
1420 // X%C to the equivalent of X-X/C*C.
1421 if (N1C && !N1C->isNullValue()) {
1422 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1423 SDOperand OptimizedDiv = combine(Div.Val);
1424 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1425 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1426 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1427 AddToWorkList(Mul.Val);
1433 if (N0.getOpcode() == ISD::UNDEF)
1434 return DAG.getConstant(0, VT);
1435 // X % undef -> undef
1436 if (N1.getOpcode() == ISD::UNDEF)
1442 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1443 SDOperand N0 = N->getOperand(0);
1444 SDOperand N1 = N->getOperand(1);
1445 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1446 MVT VT = N->getValueType(0);
1448 // fold (mulhs x, 0) -> 0
1449 if (N1C && N1C->isNullValue())
1451 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1452 if (N1C && N1C->getAPIntValue() == 1)
1453 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1454 DAG.getConstant(N0.getValueType().getSizeInBits()-1,
1455 TLI.getShiftAmountTy()));
1456 // fold (mulhs x, undef) -> 0
1457 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1458 return DAG.getConstant(0, VT);
1463 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1464 SDOperand N0 = N->getOperand(0);
1465 SDOperand N1 = N->getOperand(1);
1466 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1467 MVT VT = N->getValueType(0);
1469 // fold (mulhu x, 0) -> 0
1470 if (N1C && N1C->isNullValue())
1472 // fold (mulhu x, 1) -> 0
1473 if (N1C && N1C->getAPIntValue() == 1)
1474 return DAG.getConstant(0, N0.getValueType());
1475 // fold (mulhu x, undef) -> 0
1476 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1477 return DAG.getConstant(0, VT);
1482 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1483 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1484 /// that are being performed. Return true if a simplification was made.
1486 SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1488 // If the high half is not needed, just compute the low half.
1489 bool HiExists = N->hasAnyUseOfValue(1);
1492 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1493 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1494 N->getNumOperands());
1495 return CombineTo(N, Res, Res);
1498 // If the low half is not needed, just compute the high half.
1499 bool LoExists = N->hasAnyUseOfValue(0);
1502 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1503 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1504 N->getNumOperands());
1505 return CombineTo(N, Res, Res);
1508 // If both halves are used, return as it is.
1509 if (LoExists && HiExists)
1512 // If the two computed results can be simplified separately, separate them.
1514 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1515 N->op_begin(), N->getNumOperands());
1516 AddToWorkList(Lo.Val);
1517 SDOperand LoOpt = combine(Lo.Val);
1518 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
1520 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1521 return CombineTo(N, LoOpt, LoOpt);
1525 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1526 N->op_begin(), N->getNumOperands());
1527 AddToWorkList(Hi.Val);
1528 SDOperand HiOpt = combine(Hi.Val);
1529 if (HiOpt.Val && HiOpt != Hi &&
1531 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1532 return CombineTo(N, HiOpt, HiOpt);
1537 SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1538 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1539 if (Res.Val) return Res;
1544 SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1545 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1546 if (Res.Val) return Res;
1551 SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
1552 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1553 if (Res.Val) return Res;
1558 SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
1559 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1560 if (Res.Val) return Res;
1565 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1566 /// two operands of the same opcode, try to simplify it.
1567 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1568 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1569 MVT VT = N0.getValueType();
1570 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1572 // For each of OP in AND/OR/XOR:
1573 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1574 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1575 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1576 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1577 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1578 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1579 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1580 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1581 N0.getOperand(0).getValueType(),
1582 N0.getOperand(0), N1.getOperand(0));
1583 AddToWorkList(ORNode.Val);
1584 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1587 // For each of OP in SHL/SRL/SRA/AND...
1588 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1589 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1590 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1591 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1592 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1593 N0.getOperand(1) == N1.getOperand(1)) {
1594 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1595 N0.getOperand(0).getValueType(),
1596 N0.getOperand(0), N1.getOperand(0));
1597 AddToWorkList(ORNode.Val);
1598 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1604 SDOperand DAGCombiner::visitAND(SDNode *N) {
1605 SDOperand N0 = N->getOperand(0);
1606 SDOperand N1 = N->getOperand(1);
1607 SDOperand LL, LR, RL, RR, CC0, CC1;
1608 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1609 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1610 MVT VT = N1.getValueType();
1611 unsigned BitWidth = VT.getSizeInBits();
1614 if (VT.isVector()) {
1615 SDOperand FoldedVOp = SimplifyVBinOp(N);
1616 if (FoldedVOp.Val) return FoldedVOp;
1619 // fold (and x, undef) -> 0
1620 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1621 return DAG.getConstant(0, VT);
1622 // fold (and c1, c2) -> c1&c2
1624 return DAG.getNode(ISD::AND, VT, N0, N1);
1625 // canonicalize constant to RHS
1627 return DAG.getNode(ISD::AND, VT, N1, N0);
1628 // fold (and x, -1) -> x
1629 if (N1C && N1C->isAllOnesValue())
1631 // if (and x, c) is known to be zero, return 0
1632 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
1633 APInt::getAllOnesValue(BitWidth)))
1634 return DAG.getConstant(0, VT);
1636 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1639 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1640 if (N1C && N0.getOpcode() == ISD::OR)
1641 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1642 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1644 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1645 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1646 SDOperand N0Op0 = N0.getOperand(0);
1647 APInt Mask = ~N1C->getAPIntValue();
1648 Mask.trunc(N0Op0.getValueSizeInBits());
1649 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1650 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1653 // Replace uses of the AND with uses of the Zero extend node.
1656 // We actually want to replace all uses of the any_extend with the
1657 // zero_extend, to avoid duplicating things. This will later cause this
1658 // AND to be folded.
1659 CombineTo(N0.Val, Zext);
1660 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1663 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1664 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1665 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1666 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1668 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1669 LL.getValueType().isInteger()) {
1670 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1671 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1672 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1673 AddToWorkList(ORNode.Val);
1674 return DAG.getSetCC(VT, ORNode, LR, Op1);
1676 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1677 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1678 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1679 AddToWorkList(ANDNode.Val);
1680 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1682 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1683 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1684 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1685 AddToWorkList(ORNode.Val);
1686 return DAG.getSetCC(VT, ORNode, LR, Op1);
1689 // canonicalize equivalent to ll == rl
1690 if (LL == RR && LR == RL) {
1691 Op1 = ISD::getSetCCSwappedOperands(Op1);
1694 if (LL == RL && LR == RR) {
1695 bool isInteger = LL.getValueType().isInteger();
1696 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1697 if (Result != ISD::SETCC_INVALID)
1698 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1702 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1703 if (N0.getOpcode() == N1.getOpcode()) {
1704 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1705 if (Tmp.Val) return Tmp;
1708 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1709 // fold (and (sra)) -> (and (srl)) when possible.
1710 if (!VT.isVector() &&
1711 SimplifyDemandedBits(SDOperand(N, 0)))
1712 return SDOperand(N, 0);
1713 // fold (zext_inreg (extload x)) -> (zextload x)
1714 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1715 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1716 MVT EVT = LN0->getMemoryVT();
1717 // If we zero all the possible extended bits, then we can turn this into
1718 // a zextload if we are running before legalize or the operation is legal.
1719 unsigned BitWidth = N1.getValueSizeInBits();
1720 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1721 BitWidth - EVT.getSizeInBits())) &&
1722 ((!AfterLegalize && !LN0->isVolatile()) ||
1723 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1724 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1725 LN0->getBasePtr(), LN0->getSrcValue(),
1726 LN0->getSrcValueOffset(), EVT,
1728 LN0->getAlignment());
1730 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1731 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1734 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1735 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1737 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1738 MVT EVT = LN0->getMemoryVT();
1739 // If we zero all the possible extended bits, then we can turn this into
1740 // a zextload if we are running before legalize or the operation is legal.
1741 unsigned BitWidth = N1.getValueSizeInBits();
1742 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1743 BitWidth - EVT.getSizeInBits())) &&
1744 ((!AfterLegalize && !LN0->isVolatile()) ||
1745 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1746 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1747 LN0->getBasePtr(), LN0->getSrcValue(),
1748 LN0->getSrcValueOffset(), EVT,
1750 LN0->getAlignment());
1752 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1753 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1757 // fold (and (load x), 255) -> (zextload x, i8)
1758 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1759 if (N1C && N0.getOpcode() == ISD::LOAD) {
1760 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1761 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1762 LN0->isUnindexed() && N0.hasOneUse() &&
1763 // Do not change the width of a volatile load.
1764 !LN0->isVolatile()) {
1765 MVT EVT = MVT::Other;
1766 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1767 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1768 EVT = MVT::getIntegerVT(ActiveBits);
1770 MVT LoadedVT = LN0->getMemoryVT();
1771 // Do not generate loads of non-round integer types since these can
1772 // be expensive (and would be wrong if the type is not byte sized).
1773 if (EVT != MVT::Other && LoadedVT.bitsGT(EVT) && EVT.isRound() &&
1774 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1775 MVT PtrType = N0.getOperand(1).getValueType();
1776 // For big endian targets, we need to add an offset to the pointer to
1777 // load the correct bytes. For little endian systems, we merely need to
1778 // read fewer bytes from the same pointer.
1779 unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
1780 unsigned EVTStoreBytes = EVT.getStoreSizeInBits()/8;
1781 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1782 unsigned Alignment = LN0->getAlignment();
1783 SDOperand NewPtr = LN0->getBasePtr();
1784 if (TLI.isBigEndian()) {
1785 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1786 DAG.getConstant(PtrOff, PtrType));
1787 Alignment = MinAlign(Alignment, PtrOff);
1789 AddToWorkList(NewPtr.Val);
1791 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1792 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1793 LN0->isVolatile(), Alignment);
1795 CombineTo(N0.Val, Load, Load.getValue(1));
1796 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1804 SDOperand DAGCombiner::visitOR(SDNode *N) {
1805 SDOperand N0 = N->getOperand(0);
1806 SDOperand N1 = N->getOperand(1);
1807 SDOperand LL, LR, RL, RR, CC0, CC1;
1808 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1809 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1810 MVT VT = N1.getValueType();
1813 if (VT.isVector()) {
1814 SDOperand FoldedVOp = SimplifyVBinOp(N);
1815 if (FoldedVOp.Val) return FoldedVOp;
1818 // fold (or x, undef) -> -1
1819 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1820 return DAG.getConstant(~0ULL, VT);
1821 // fold (or c1, c2) -> c1|c2
1823 return DAG.getNode(ISD::OR, VT, N0, N1);
1824 // canonicalize constant to RHS
1826 return DAG.getNode(ISD::OR, VT, N1, N0);
1827 // fold (or x, 0) -> x
1828 if (N1C && N1C->isNullValue())
1830 // fold (or x, -1) -> -1
1831 if (N1C && N1C->isAllOnesValue())
1833 // fold (or x, c) -> c iff (x & ~c) == 0
1834 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1837 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1840 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1841 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1842 isa<ConstantSDNode>(N0.getOperand(1))) {
1843 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1844 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1846 DAG.getConstant(N1C->getAPIntValue() |
1847 C1->getAPIntValue(), VT));
1849 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1850 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1851 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1852 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1854 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1855 LL.getValueType().isInteger()) {
1856 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1857 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1858 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1859 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1860 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1861 AddToWorkList(ORNode.Val);
1862 return DAG.getSetCC(VT, ORNode, LR, Op1);
1864 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1865 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1866 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1867 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1868 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1869 AddToWorkList(ANDNode.Val);
1870 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1873 // canonicalize equivalent to ll == rl
1874 if (LL == RR && LR == RL) {
1875 Op1 = ISD::getSetCCSwappedOperands(Op1);
1878 if (LL == RL && LR == RR) {
1879 bool isInteger = LL.getValueType().isInteger();
1880 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1881 if (Result != ISD::SETCC_INVALID)
1882 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1886 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1887 if (N0.getOpcode() == N1.getOpcode()) {
1888 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1889 if (Tmp.Val) return Tmp;
1892 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1893 if (N0.getOpcode() == ISD::AND &&
1894 N1.getOpcode() == ISD::AND &&
1895 N0.getOperand(1).getOpcode() == ISD::Constant &&
1896 N1.getOperand(1).getOpcode() == ISD::Constant &&
1897 // Don't increase # computations.
1898 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1899 // We can only do this xform if we know that bits from X that are set in C2
1900 // but not in C1 are already zero. Likewise for Y.
1901 const APInt &LHSMask =
1902 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1903 const APInt &RHSMask =
1904 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
1906 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1907 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1908 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1909 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1914 // See if this is some rotate idiom.
1915 if (SDNode *Rot = MatchRotate(N0, N1))
1916 return SDOperand(Rot, 0);
1922 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1923 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1924 if (Op.getOpcode() == ISD::AND) {
1925 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1926 Mask = Op.getOperand(1);
1927 Op = Op.getOperand(0);
1933 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1941 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1942 // idioms for rotate, and if the target supports rotation instructions, generate
1944 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1945 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
1946 MVT VT = LHS.getValueType();
1947 if (!TLI.isTypeLegal(VT)) return 0;
1949 // The target must have at least one rotate flavor.
1950 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1951 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1952 if (!HasROTL && !HasROTR) return 0;
1954 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1955 SDOperand LHSShift; // The shift.
1956 SDOperand LHSMask; // AND value if any.
1957 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1958 return 0; // Not part of a rotate.
1960 SDOperand RHSShift; // The shift.
1961 SDOperand RHSMask; // AND value if any.
1962 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1963 return 0; // Not part of a rotate.
1965 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1966 return 0; // Not shifting the same value.
1968 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1969 return 0; // Shifts must disagree.
1971 // Canonicalize shl to left side in a shl/srl pair.
1972 if (RHSShift.getOpcode() == ISD::SHL) {
1973 std::swap(LHS, RHS);
1974 std::swap(LHSShift, RHSShift);
1975 std::swap(LHSMask , RHSMask );
1978 unsigned OpSizeInBits = VT.getSizeInBits();
1979 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1980 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1981 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1983 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1984 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1985 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
1986 RHSShiftAmt.getOpcode() == ISD::Constant) {
1987 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
1988 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
1989 if ((LShVal + RShVal) != OpSizeInBits)
1994 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
1996 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
1998 // If there is an AND of either shifted operand, apply it to the result.
1999 if (LHSMask.Val || RHSMask.Val) {
2000 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2003 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2004 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2007 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2008 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2011 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2017 // If there is a mask here, and we have a variable shift, we can't be sure
2018 // that we're masking out the right stuff.
2019 if (LHSMask.Val || RHSMask.Val)
2022 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2023 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2024 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2025 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2026 if (ConstantSDNode *SUBC =
2027 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2028 if (SUBC->getAPIntValue() == OpSizeInBits) {
2030 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2032 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2037 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2038 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2039 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2040 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2041 if (ConstantSDNode *SUBC =
2042 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2043 if (SUBC->getAPIntValue() == OpSizeInBits) {
2045 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2047 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2052 // Look for sign/zext/any-extended cases:
2053 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2054 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2055 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2056 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2057 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2058 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2059 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2060 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2061 if (RExtOp0.getOpcode() == ISD::SUB &&
2062 RExtOp0.getOperand(1) == LExtOp0) {
2063 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2065 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2066 // (rotl x, (sub 32, y))
2067 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2068 if (SUBC->getAPIntValue() == OpSizeInBits) {
2070 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2072 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2075 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2076 RExtOp0 == LExtOp0.getOperand(1)) {
2077 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2079 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2080 // (rotr x, (sub 32, y))
2081 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2082 if (SUBC->getAPIntValue() == OpSizeInBits) {
2084 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2086 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2096 SDOperand DAGCombiner::visitXOR(SDNode *N) {
2097 SDOperand N0 = N->getOperand(0);
2098 SDOperand N1 = N->getOperand(1);
2099 SDOperand LHS, RHS, CC;
2100 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2101 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2102 MVT VT = N0.getValueType();
2105 if (VT.isVector()) {
2106 SDOperand FoldedVOp = SimplifyVBinOp(N);
2107 if (FoldedVOp.Val) return FoldedVOp;
2110 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2111 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2112 return DAG.getConstant(0, VT);
2113 // fold (xor x, undef) -> undef
2114 if (N0.getOpcode() == ISD::UNDEF)
2116 if (N1.getOpcode() == ISD::UNDEF)
2118 // fold (xor c1, c2) -> c1^c2
2120 return DAG.getNode(ISD::XOR, VT, N0, N1);
2121 // canonicalize constant to RHS
2123 return DAG.getNode(ISD::XOR, VT, N1, N0);
2124 // fold (xor x, 0) -> x
2125 if (N1C && N1C->isNullValue())
2128 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2131 // fold !(x cc y) -> (x !cc y)
2132 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2133 bool isInt = LHS.getValueType().isInteger();
2134 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2136 if (N0.getOpcode() == ISD::SETCC)
2137 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2138 if (N0.getOpcode() == ISD::SELECT_CC)
2139 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2140 assert(0 && "Unhandled SetCC Equivalent!");
2143 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2144 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2145 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2146 SDOperand V = N0.getOperand(0);
2147 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
2148 DAG.getConstant(1, V.getValueType()));
2149 AddToWorkList(V.Val);
2150 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2153 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2154 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2155 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2156 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2157 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2158 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2159 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2160 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2161 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2162 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2165 // fold !(x or y) -> (!x and !y) iff x or y are constants
2166 if (N1C && N1C->isAllOnesValue() &&
2167 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2168 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2169 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2170 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2171 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2172 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2173 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2174 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2177 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2178 if (N1C && N0.getOpcode() == ISD::XOR) {
2179 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2180 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2182 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2183 DAG.getConstant(N1C->getAPIntValue()^
2184 N00C->getAPIntValue(), VT));
2186 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2187 DAG.getConstant(N1C->getAPIntValue()^
2188 N01C->getAPIntValue(), VT));
2190 // fold (xor x, x) -> 0
2192 if (!VT.isVector()) {
2193 return DAG.getConstant(0, VT);
2194 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2195 // Produce a vector of zeros.
2196 SDOperand El = DAG.getConstant(0, VT.getVectorElementType());
2197 std::vector<SDOperand> Ops(VT.getVectorNumElements(), El);
2198 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2202 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2203 if (N0.getOpcode() == N1.getOpcode()) {
2204 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2205 if (Tmp.Val) return Tmp;
2208 // Simplify the expression using non-local knowledge.
2209 if (!VT.isVector() &&
2210 SimplifyDemandedBits(SDOperand(N, 0)))
2211 return SDOperand(N, 0);
2216 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2217 /// the shift amount is a constant.
2218 SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2219 SDNode *LHS = N->getOperand(0).Val;
2220 if (!LHS->hasOneUse()) return SDOperand();
2222 // We want to pull some binops through shifts, so that we have (and (shift))
2223 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2224 // thing happens with address calculations, so it's important to canonicalize
2226 bool HighBitSet = false; // Can we transform this if the high bit is set?
2228 switch (LHS->getOpcode()) {
2229 default: return SDOperand();
2232 HighBitSet = false; // We can only transform sra if the high bit is clear.
2235 HighBitSet = true; // We can only transform sra if the high bit is set.
2238 if (N->getOpcode() != ISD::SHL)
2239 return SDOperand(); // only shl(add) not sr[al](add).
2240 HighBitSet = false; // We can only transform sra if the high bit is clear.
2244 // We require the RHS of the binop to be a constant as well.
2245 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2246 if (!BinOpCst) return SDOperand();
2249 // FIXME: disable this for unless the input to the binop is a shift by a
2250 // constant. If it is not a shift, it pessimizes some common cases like:
2252 //void foo(int *X, int i) { X[i & 1235] = 1; }
2253 //int bar(int *X, int i) { return X[i & 255]; }
2254 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2255 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2256 BinOpLHSVal->getOpcode() != ISD::SRA &&
2257 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2258 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2261 MVT VT = N->getValueType(0);
2263 // If this is a signed shift right, and the high bit is modified
2264 // by the logical operation, do not perform the transformation.
2265 // The highBitSet boolean indicates the value of the high bit of
2266 // the constant which would cause it to be modified for this
2268 if (N->getOpcode() == ISD::SRA) {
2269 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2270 if (BinOpRHSSignSet != HighBitSet)
2274 // Fold the constants, shifting the binop RHS by the shift amount.
2275 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2276 LHS->getOperand(1), N->getOperand(1));
2278 // Create the new shift.
2279 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2282 // Create the new binop.
2283 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2287 SDOperand DAGCombiner::visitSHL(SDNode *N) {
2288 SDOperand N0 = N->getOperand(0);
2289 SDOperand N1 = N->getOperand(1);
2290 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2291 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2292 MVT VT = N0.getValueType();
2293 unsigned OpSizeInBits = VT.getSizeInBits();
2295 // fold (shl c1, c2) -> c1<<c2
2297 return DAG.getNode(ISD::SHL, VT, N0, N1);
2298 // fold (shl 0, x) -> 0
2299 if (N0C && N0C->isNullValue())
2301 // fold (shl x, c >= size(x)) -> undef
2302 if (N1C && N1C->getValue() >= OpSizeInBits)
2303 return DAG.getNode(ISD::UNDEF, VT);
2304 // fold (shl x, 0) -> x
2305 if (N1C && N1C->isNullValue())
2307 // if (shl x, c) is known to be zero, return 0
2308 if (DAG.MaskedValueIsZero(SDOperand(N, 0),
2309 APInt::getAllOnesValue(VT.getSizeInBits())))
2310 return DAG.getConstant(0, VT);
2311 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2312 return SDOperand(N, 0);
2313 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2314 if (N1C && N0.getOpcode() == ISD::SHL &&
2315 N0.getOperand(1).getOpcode() == ISD::Constant) {
2316 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2317 uint64_t c2 = N1C->getValue();
2318 if (c1 + c2 > OpSizeInBits)
2319 return DAG.getConstant(0, VT);
2320 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2321 DAG.getConstant(c1 + c2, N1.getValueType()));
2323 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2324 // (srl (and x, -1 << c1), c1-c2)
2325 if (N1C && N0.getOpcode() == ISD::SRL &&
2326 N0.getOperand(1).getOpcode() == ISD::Constant) {
2327 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2328 uint64_t c2 = N1C->getValue();
2329 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2330 DAG.getConstant(~0ULL << c1, VT));
2332 return DAG.getNode(ISD::SHL, VT, Mask,
2333 DAG.getConstant(c2-c1, N1.getValueType()));
2335 return DAG.getNode(ISD::SRL, VT, Mask,
2336 DAG.getConstant(c1-c2, N1.getValueType()));
2338 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2339 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2340 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2341 DAG.getConstant(~0ULL << N1C->getValue(), VT));
2343 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2346 SDOperand DAGCombiner::visitSRA(SDNode *N) {
2347 SDOperand N0 = N->getOperand(0);
2348 SDOperand N1 = N->getOperand(1);
2349 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2350 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2351 MVT VT = N0.getValueType();
2353 // fold (sra c1, c2) -> c1>>c2
2355 return DAG.getNode(ISD::SRA, VT, N0, N1);
2356 // fold (sra 0, x) -> 0
2357 if (N0C && N0C->isNullValue())
2359 // fold (sra -1, x) -> -1
2360 if (N0C && N0C->isAllOnesValue())
2362 // fold (sra x, c >= size(x)) -> undef
2363 if (N1C && N1C->getValue() >= VT.getSizeInBits())
2364 return DAG.getNode(ISD::UNDEF, VT);
2365 // fold (sra x, 0) -> x
2366 if (N1C && N1C->isNullValue())
2368 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2370 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2371 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getValue();
2372 MVT EVT = MVT::getIntegerVT(LowBits);
2373 if (EVT.isSimple() && // TODO: remove when apint codegen support lands.
2374 (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
2375 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2376 DAG.getValueType(EVT));
2379 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2380 if (N1C && N0.getOpcode() == ISD::SRA) {
2381 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2382 unsigned Sum = N1C->getValue() + C1->getValue();
2383 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
2384 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2385 DAG.getConstant(Sum, N1C->getValueType(0)));
2389 // fold sra (shl X, m), result_size - n
2390 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
2391 // result_size - n != m.
2392 // If truncate is free for the target sext(shl) is likely to result in better
2394 if (N0.getOpcode() == ISD::SHL) {
2395 // Get the two constanst of the shifts, CN0 = m, CN = n.
2396 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2398 // Determine what the truncate's result bitsize and type would be.
2399 unsigned VTValSize = VT.getSizeInBits();
2401 MVT::getIntegerVT(VTValSize - N1C->getValue());
2402 // Determine the residual right-shift amount.
2403 unsigned ShiftAmt = N1C->getValue() - N01C->getValue();
2405 // If the shift is not a no-op (in which case this should be just a sign
2406 // extend already), the truncated to type is legal, sign_extend is legal
2407 // on that type, and the the truncate to that type is both legal and free,
2408 // perform the transform.
2410 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
2411 TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
2412 TLI.isTruncateFree(VT, TruncVT)) {
2414 SDOperand Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2415 SDOperand Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2416 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2417 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
2422 // Simplify, based on bits shifted out of the LHS.
2423 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2424 return SDOperand(N, 0);
2427 // If the sign bit is known to be zero, switch this to a SRL.
2428 if (DAG.SignBitIsZero(N0))
2429 return DAG.getNode(ISD::SRL, VT, N0, N1);
2431 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2434 SDOperand DAGCombiner::visitSRL(SDNode *N) {
2435 SDOperand N0 = N->getOperand(0);
2436 SDOperand N1 = N->getOperand(1);
2437 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2438 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2439 MVT VT = N0.getValueType();
2440 unsigned OpSizeInBits = VT.getSizeInBits();
2442 // fold (srl c1, c2) -> c1 >>u c2
2444 return DAG.getNode(ISD::SRL, VT, N0, N1);
2445 // fold (srl 0, x) -> 0
2446 if (N0C && N0C->isNullValue())
2448 // fold (srl x, c >= size(x)) -> undef
2449 if (N1C && N1C->getValue() >= OpSizeInBits)
2450 return DAG.getNode(ISD::UNDEF, VT);
2451 // fold (srl x, 0) -> x
2452 if (N1C && N1C->isNullValue())
2454 // if (srl x, c) is known to be zero, return 0
2455 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
2456 APInt::getAllOnesValue(OpSizeInBits)))
2457 return DAG.getConstant(0, VT);
2459 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2460 if (N1C && N0.getOpcode() == ISD::SRL &&
2461 N0.getOperand(1).getOpcode() == ISD::Constant) {
2462 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2463 uint64_t c2 = N1C->getValue();
2464 if (c1 + c2 > OpSizeInBits)
2465 return DAG.getConstant(0, VT);
2466 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2467 DAG.getConstant(c1 + c2, N1.getValueType()));
2470 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2471 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2472 // Shifting in all undef bits?
2473 MVT SmallVT = N0.getOperand(0).getValueType();
2474 if (N1C->getValue() >= SmallVT.getSizeInBits())
2475 return DAG.getNode(ISD::UNDEF, VT);
2477 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2478 AddToWorkList(SmallShift.Val);
2479 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2482 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2483 // bit, which is unmodified by sra.
2484 if (N1C && N1C->getValue()+1 == VT.getSizeInBits()) {
2485 if (N0.getOpcode() == ISD::SRA)
2486 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2489 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2490 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2491 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2492 APInt KnownZero, KnownOne;
2493 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2494 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2496 // If any of the input bits are KnownOne, then the input couldn't be all
2497 // zeros, thus the result of the srl will always be zero.
2498 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2500 // If all of the bits input the to ctlz node are known to be zero, then
2501 // the result of the ctlz is "32" and the result of the shift is one.
2502 APInt UnknownBits = ~KnownZero & Mask;
2503 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2505 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2506 if ((UnknownBits & (UnknownBits-1)) == 0) {
2507 // Okay, we know that only that the single bit specified by UnknownBits
2508 // could be set on input to the CTLZ node. If this bit is set, the SRL
2509 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2510 // to an SRL,XOR pair, which is likely to simplify more.
2511 unsigned ShAmt = UnknownBits.countTrailingZeros();
2512 SDOperand Op = N0.getOperand(0);
2514 Op = DAG.getNode(ISD::SRL, VT, Op,
2515 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2516 AddToWorkList(Op.Val);
2518 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2522 // fold operands of srl based on knowledge that the low bits are not
2524 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2525 return SDOperand(N, 0);
2527 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2530 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2531 SDOperand N0 = N->getOperand(0);
2532 MVT VT = N->getValueType(0);
2534 // fold (ctlz c1) -> c2
2535 if (isa<ConstantSDNode>(N0))
2536 return DAG.getNode(ISD::CTLZ, VT, N0);
2540 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2541 SDOperand N0 = N->getOperand(0);
2542 MVT VT = N->getValueType(0);
2544 // fold (cttz c1) -> c2
2545 if (isa<ConstantSDNode>(N0))
2546 return DAG.getNode(ISD::CTTZ, VT, N0);
2550 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2551 SDOperand N0 = N->getOperand(0);
2552 MVT VT = N->getValueType(0);
2554 // fold (ctpop c1) -> c2
2555 if (isa<ConstantSDNode>(N0))
2556 return DAG.getNode(ISD::CTPOP, VT, N0);
2560 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2561 SDOperand N0 = N->getOperand(0);
2562 SDOperand N1 = N->getOperand(1);
2563 SDOperand N2 = N->getOperand(2);
2564 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2565 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2566 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2567 MVT VT = N->getValueType(0);
2568 MVT VT0 = N0.getValueType();
2570 // fold select C, X, X -> X
2573 // fold select true, X, Y -> X
2574 if (N0C && !N0C->isNullValue())
2576 // fold select false, X, Y -> Y
2577 if (N0C && N0C->isNullValue())
2579 // fold select C, 1, X -> C | X
2580 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2581 return DAG.getNode(ISD::OR, VT, N0, N2);
2582 // fold select C, 0, 1 -> ~C
2583 if (VT.isInteger() && VT0.isInteger() &&
2584 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2585 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2588 AddToWorkList(XORNode.Val);
2590 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2591 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2593 // fold select C, 0, X -> ~C & X
2594 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2595 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2596 AddToWorkList(XORNode.Val);
2597 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2599 // fold select C, X, 1 -> ~C | X
2600 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2601 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2602 AddToWorkList(XORNode.Val);
2603 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2605 // fold select C, X, 0 -> C & X
2606 // FIXME: this should check for C type == X type, not i1?
2607 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2608 return DAG.getNode(ISD::AND, VT, N0, N1);
2609 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2610 if (VT == MVT::i1 && N0 == N1)
2611 return DAG.getNode(ISD::OR, VT, N0, N2);
2612 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2613 if (VT == MVT::i1 && N0 == N2)
2614 return DAG.getNode(ISD::AND, VT, N0, N1);
2616 // If we can fold this based on the true/false value, do so.
2617 if (SimplifySelectOps(N, N1, N2))
2618 return SDOperand(N, 0); // Don't revisit N.
2620 // fold selects based on a setcc into other things, such as min/max/abs
2621 if (N0.getOpcode() == ISD::SETCC) {
2623 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2624 // having to say they don't support SELECT_CC on every type the DAG knows
2625 // about, since there is no way to mark an opcode illegal at all value types
2626 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2627 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2628 N1, N2, N0.getOperand(2));
2630 return SimplifySelect(N0, N1, N2);
2635 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2636 SDOperand N0 = N->getOperand(0);
2637 SDOperand N1 = N->getOperand(1);
2638 SDOperand N2 = N->getOperand(2);
2639 SDOperand N3 = N->getOperand(3);
2640 SDOperand N4 = N->getOperand(4);
2641 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2643 // fold select_cc lhs, rhs, x, x, cc -> x
2647 // Determine if the condition we're dealing with is constant
2648 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
2649 if (SCC.Val) AddToWorkList(SCC.Val);
2651 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2652 if (!SCCC->isNullValue())
2653 return N2; // cond always true -> true val
2655 return N3; // cond always false -> false val
2658 // Fold to a simpler select_cc
2659 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2660 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2661 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2664 // If we can fold this based on the true/false value, do so.
2665 if (SimplifySelectOps(N, N2, N3))
2666 return SDOperand(N, 0); // Don't revisit N.
2668 // fold select_cc into other things, such as min/max/abs
2669 return SimplifySelectCC(N0, N1, N2, N3, CC);
2672 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2673 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2674 cast<CondCodeSDNode>(N->getOperand(2))->get());
2677 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2678 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2679 // transformation. Returns true if extension are possible and the above
2680 // mentioned transformation is profitable.
2681 static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2683 SmallVector<SDNode*, 4> &ExtendNodes,
2684 TargetLowering &TLI) {
2685 bool HasCopyToRegUses = false;
2686 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2687 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2692 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2693 if (User->getOpcode() == ISD::SETCC) {
2694 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2695 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2696 // Sign bits will be lost after a zext.
2699 for (unsigned i = 0; i != 2; ++i) {
2700 SDOperand UseOp = User->getOperand(i);
2703 if (!isa<ConstantSDNode>(UseOp))
2708 ExtendNodes.push_back(User);
2710 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2711 SDOperand UseOp = User->getOperand(i);
2713 // If truncate from extended type to original load type is free
2714 // on this target, then it's ok to extend a CopyToReg.
2715 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2716 HasCopyToRegUses = true;
2724 if (HasCopyToRegUses) {
2725 bool BothLiveOut = false;
2726 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2729 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2730 SDOperand UseOp = User->getOperand(i);
2731 if (UseOp.Val == N && UseOp.ResNo == 0) {
2738 // Both unextended and extended values are live out. There had better be
2739 // good a reason for the transformation.
2740 return ExtendNodes.size();
2745 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2746 SDOperand N0 = N->getOperand(0);
2747 MVT VT = N->getValueType(0);
2749 // fold (sext c1) -> c1
2750 if (isa<ConstantSDNode>(N0))
2751 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2753 // fold (sext (sext x)) -> (sext x)
2754 // fold (sext (aext x)) -> (sext x)
2755 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2756 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2758 if (N0.getOpcode() == ISD::TRUNCATE) {
2759 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2760 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2761 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2762 if (NarrowLoad.Val) {
2763 if (NarrowLoad.Val != N0.Val)
2764 CombineTo(N0.Val, NarrowLoad);
2765 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2768 // See if the value being truncated is already sign extended. If so, just
2769 // eliminate the trunc/sext pair.
2770 SDOperand Op = N0.getOperand(0);
2771 unsigned OpBits = Op.getValueType().getSizeInBits();
2772 unsigned MidBits = N0.getValueType().getSizeInBits();
2773 unsigned DestBits = VT.getSizeInBits();
2774 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2776 if (OpBits == DestBits) {
2777 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2778 // bits, it is already ready.
2779 if (NumSignBits > DestBits-MidBits)
2781 } else if (OpBits < DestBits) {
2782 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2783 // bits, just sext from i32.
2784 if (NumSignBits > OpBits-MidBits)
2785 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2787 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2788 // bits, just truncate to i32.
2789 if (NumSignBits > OpBits-MidBits)
2790 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2793 // fold (sext (truncate x)) -> (sextinreg x).
2794 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2795 N0.getValueType())) {
2796 if (Op.getValueType().bitsLT(VT))
2797 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2798 else if (Op.getValueType().bitsGT(VT))
2799 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2800 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2801 DAG.getValueType(N0.getValueType()));
2805 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2806 if (ISD::isNON_EXTLoad(N0.Val) &&
2807 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2808 TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))) {
2809 bool DoXform = true;
2810 SmallVector<SDNode*, 4> SetCCs;
2811 if (!N0.hasOneUse())
2812 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2814 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2815 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2816 LN0->getBasePtr(), LN0->getSrcValue(),
2817 LN0->getSrcValueOffset(),
2820 LN0->getAlignment());
2821 CombineTo(N, ExtLoad);
2822 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2823 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2824 // Extend SetCC uses if necessary.
2825 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2826 SDNode *SetCC = SetCCs[i];
2827 SmallVector<SDOperand, 4> Ops;
2828 for (unsigned j = 0; j != 2; ++j) {
2829 SDOperand SOp = SetCC->getOperand(j);
2831 Ops.push_back(ExtLoad);
2833 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2835 Ops.push_back(SetCC->getOperand(2));
2836 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2837 &Ops[0], Ops.size()));
2839 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2843 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2844 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2845 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2846 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2847 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2848 MVT EVT = LN0->getMemoryVT();
2849 if ((!AfterLegalize && !LN0->isVolatile()) ||
2850 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2851 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2852 LN0->getBasePtr(), LN0->getSrcValue(),
2853 LN0->getSrcValueOffset(), EVT,
2855 LN0->getAlignment());
2856 CombineTo(N, ExtLoad);
2857 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2858 ExtLoad.getValue(1));
2859 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2863 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2864 if (N0.getOpcode() == ISD::SETCC) {
2866 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2867 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2868 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2869 if (SCC.Val) return SCC;
2872 // fold (sext x) -> (zext x) if the sign bit is known zero.
2873 if ((!AfterLegalize || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
2874 DAG.SignBitIsZero(N0))
2875 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2880 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2881 SDOperand N0 = N->getOperand(0);
2882 MVT VT = N->getValueType(0);
2884 // fold (zext c1) -> c1
2885 if (isa<ConstantSDNode>(N0))
2886 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2887 // fold (zext (zext x)) -> (zext x)
2888 // fold (zext (aext x)) -> (zext x)
2889 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2890 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2892 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2893 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2894 if (N0.getOpcode() == ISD::TRUNCATE) {
2895 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2896 if (NarrowLoad.Val) {
2897 if (NarrowLoad.Val != N0.Val)
2898 CombineTo(N0.Val, NarrowLoad);
2899 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2903 // fold (zext (truncate x)) -> (and x, mask)
2904 if (N0.getOpcode() == ISD::TRUNCATE &&
2905 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2906 SDOperand Op = N0.getOperand(0);
2907 if (Op.getValueType().bitsLT(VT)) {
2908 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2909 } else if (Op.getValueType().bitsGT(VT)) {
2910 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2912 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2915 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2916 if (N0.getOpcode() == ISD::AND &&
2917 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2918 N0.getOperand(1).getOpcode() == ISD::Constant) {
2919 SDOperand X = N0.getOperand(0).getOperand(0);
2920 if (X.getValueType().bitsLT(VT)) {
2921 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2922 } else if (X.getValueType().bitsGT(VT)) {
2923 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2925 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2926 Mask.zext(VT.getSizeInBits());
2927 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2930 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2931 if (ISD::isNON_EXTLoad(N0.Val) &&
2932 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2933 TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2934 bool DoXform = true;
2935 SmallVector<SDNode*, 4> SetCCs;
2936 if (!N0.hasOneUse())
2937 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2939 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2940 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2941 LN0->getBasePtr(), LN0->getSrcValue(),
2942 LN0->getSrcValueOffset(),
2945 LN0->getAlignment());
2946 CombineTo(N, ExtLoad);
2947 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2948 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2949 // Extend SetCC uses if necessary.
2950 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2951 SDNode *SetCC = SetCCs[i];
2952 SmallVector<SDOperand, 4> Ops;
2953 for (unsigned j = 0; j != 2; ++j) {
2954 SDOperand SOp = SetCC->getOperand(j);
2956 Ops.push_back(ExtLoad);
2958 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
2960 Ops.push_back(SetCC->getOperand(2));
2961 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2962 &Ops[0], Ops.size()));
2964 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2968 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2969 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2970 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2971 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2972 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2973 MVT EVT = LN0->getMemoryVT();
2974 if ((!AfterLegalize && !LN0->isVolatile()) ||
2975 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT)) {
2976 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2977 LN0->getBasePtr(), LN0->getSrcValue(),
2978 LN0->getSrcValueOffset(), EVT,
2980 LN0->getAlignment());
2981 CombineTo(N, ExtLoad);
2982 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2983 ExtLoad.getValue(1));
2984 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2988 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2989 if (N0.getOpcode() == ISD::SETCC) {
2991 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2992 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2993 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2994 if (SCC.Val) return SCC;
3000 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
3001 SDOperand N0 = N->getOperand(0);
3002 MVT VT = N->getValueType(0);
3004 // fold (aext c1) -> c1
3005 if (isa<ConstantSDNode>(N0))
3006 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
3007 // fold (aext (aext x)) -> (aext x)
3008 // fold (aext (zext x)) -> (zext x)
3009 // fold (aext (sext x)) -> (sext x)
3010 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3011 N0.getOpcode() == ISD::ZERO_EXTEND ||
3012 N0.getOpcode() == ISD::SIGN_EXTEND)
3013 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3015 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3016 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3017 if (N0.getOpcode() == ISD::TRUNCATE) {
3018 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
3019 if (NarrowLoad.Val) {
3020 if (NarrowLoad.Val != N0.Val)
3021 CombineTo(N0.Val, NarrowLoad);
3022 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3026 // fold (aext (truncate x))
3027 if (N0.getOpcode() == ISD::TRUNCATE) {
3028 SDOperand TruncOp = N0.getOperand(0);
3029 if (TruncOp.getValueType() == VT)
3030 return TruncOp; // x iff x size == zext size.
3031 if (TruncOp.getValueType().bitsGT(VT))
3032 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3033 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3036 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3037 if (N0.getOpcode() == ISD::AND &&
3038 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3039 N0.getOperand(1).getOpcode() == ISD::Constant) {
3040 SDOperand X = N0.getOperand(0).getOperand(0);
3041 if (X.getValueType().bitsLT(VT)) {
3042 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3043 } else if (X.getValueType().bitsGT(VT)) {
3044 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3046 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3047 Mask.zext(VT.getSizeInBits());
3048 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3051 // fold (aext (load x)) -> (aext (truncate (extload x)))
3052 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3053 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3054 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3055 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3056 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3057 LN0->getBasePtr(), LN0->getSrcValue(),
3058 LN0->getSrcValueOffset(),
3061 LN0->getAlignment());
3062 CombineTo(N, ExtLoad);
3063 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3064 ExtLoad.getValue(1));
3065 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3068 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3069 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3070 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3071 if (N0.getOpcode() == ISD::LOAD &&
3072 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3074 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3075 MVT EVT = LN0->getMemoryVT();
3076 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3077 LN0->getChain(), LN0->getBasePtr(),
3079 LN0->getSrcValueOffset(), EVT,
3081 LN0->getAlignment());
3082 CombineTo(N, ExtLoad);
3083 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3084 ExtLoad.getValue(1));
3085 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3088 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3089 if (N0.getOpcode() == ISD::SETCC) {
3091 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3092 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3093 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3101 /// GetDemandedBits - See if the specified operand can be simplified with the
3102 /// knowledge that only the bits specified by Mask are used. If so, return the
3103 /// simpler operand, otherwise return a null SDOperand.
3104 SDOperand DAGCombiner::GetDemandedBits(SDOperand V, const APInt &Mask) {
3105 switch (V.getOpcode()) {
3109 // If the LHS or RHS don't contribute bits to the or, drop them.
3110 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3111 return V.getOperand(1);
3112 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3113 return V.getOperand(0);
3116 // Only look at single-use SRLs.
3117 if (!V.Val->hasOneUse())
3119 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3120 // See if we can recursively simplify the LHS.
3121 unsigned Amt = RHSC->getValue();
3122 APInt NewMask = Mask << Amt;
3123 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3124 if (SimplifyLHS.Val) {
3125 return DAG.getNode(ISD::SRL, V.getValueType(),
3126 SimplifyLHS, V.getOperand(1));
3133 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3134 /// bits and then truncated to a narrower type and where N is a multiple
3135 /// of number of bits of the narrower type, transform it to a narrower load
3136 /// from address + N / num of bits of new type. If the result is to be
3137 /// extended, also fold the extension to form a extending load.
3138 SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3139 unsigned Opc = N->getOpcode();
3140 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3141 SDOperand N0 = N->getOperand(0);
3142 MVT VT = N->getValueType(0);
3143 MVT EVT = N->getValueType(0);
3145 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3147 if (Opc == ISD::SIGN_EXTEND_INREG) {
3148 ExtType = ISD::SEXTLOAD;
3149 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3150 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3154 unsigned EVTBits = EVT.getSizeInBits();
3156 bool CombineSRL = false;
3157 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3158 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3159 ShAmt = N01->getValue();
3160 // Is the shift amount a multiple of size of VT?
3161 if ((ShAmt & (EVTBits-1)) == 0) {
3162 N0 = N0.getOperand(0);
3163 if (N0.getValueType().getSizeInBits() <= EVTBits)
3170 // Do not generate loads of non-round integer types since these can
3171 // be expensive (and would be wrong if the type is not byte sized).
3172 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() && VT.isRound() &&
3173 // Do not change the width of a volatile load.
3174 !cast<LoadSDNode>(N0)->isVolatile()) {
3175 assert(N0.getValueType().getSizeInBits() > EVTBits &&
3176 "Cannot truncate to larger type!");
3177 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3178 MVT PtrType = N0.getOperand(1).getValueType();
3179 // For big endian targets, we need to adjust the offset to the pointer to
3180 // load the correct bytes.
3181 if (TLI.isBigEndian()) {
3182 unsigned LVTStoreBits = N0.getValueType().getStoreSizeInBits();
3183 unsigned EVTStoreBits = EVT.getStoreSizeInBits();
3184 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3186 uint64_t PtrOff = ShAmt / 8;
3187 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3188 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3189 DAG.getConstant(PtrOff, PtrType));
3190 AddToWorkList(NewPtr.Val);
3191 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3192 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3193 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3194 LN0->isVolatile(), NewAlign)
3195 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3196 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
3197 LN0->isVolatile(), NewAlign);
3200 WorkListRemover DeadNodes(*this);
3201 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3203 CombineTo(N->getOperand(0).Val, Load);
3205 CombineTo(N0.Val, Load, Load.getValue(1));
3207 if (Opc == ISD::SIGN_EXTEND_INREG)
3208 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3210 return DAG.getNode(Opc, VT, Load);
3212 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3219 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3220 SDOperand N0 = N->getOperand(0);
3221 SDOperand N1 = N->getOperand(1);
3222 MVT VT = N->getValueType(0);
3223 MVT EVT = cast<VTSDNode>(N1)->getVT();
3224 unsigned VTBits = VT.getSizeInBits();
3225 unsigned EVTBits = EVT.getSizeInBits();
3227 // fold (sext_in_reg c1) -> c1
3228 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3229 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3231 // If the input is already sign extended, just drop the extension.
3232 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
3235 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3236 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3237 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3238 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3241 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3242 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3243 return DAG.getZeroExtendInReg(N0, EVT);
3245 // fold operands of sext_in_reg based on knowledge that the top bits are not
3247 if (SimplifyDemandedBits(SDOperand(N, 0)))
3248 return SDOperand(N, 0);
3250 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3251 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3252 SDOperand NarrowLoad = ReduceLoadWidth(N);
3256 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3257 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3258 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3259 if (N0.getOpcode() == ISD::SRL) {
3260 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3261 if (ShAmt->getValue()+EVTBits <= VT.getSizeInBits()) {
3262 // We can turn this into an SRA iff the input to the SRL is already sign
3264 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3265 if (VT.getSizeInBits()-(ShAmt->getValue()+EVTBits) < InSignBits)
3266 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3270 // fold (sext_inreg (extload x)) -> (sextload x)
3271 if (ISD::isEXTLoad(N0.Val) &&
3272 ISD::isUNINDEXEDLoad(N0.Val) &&
3273 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3274 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3275 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3276 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3277 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3278 LN0->getBasePtr(), LN0->getSrcValue(),
3279 LN0->getSrcValueOffset(), EVT,
3281 LN0->getAlignment());
3282 CombineTo(N, ExtLoad);
3283 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3284 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3286 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3287 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3289 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3290 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3291 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3292 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3293 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3294 LN0->getBasePtr(), LN0->getSrcValue(),
3295 LN0->getSrcValueOffset(), EVT,
3297 LN0->getAlignment());
3298 CombineTo(N, ExtLoad);
3299 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3300 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3305 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3306 SDOperand N0 = N->getOperand(0);
3307 MVT VT = N->getValueType(0);
3310 if (N0.getValueType() == N->getValueType(0))
3312 // fold (truncate c1) -> c1
3313 if (isa<ConstantSDNode>(N0))
3314 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3315 // fold (truncate (truncate x)) -> (truncate x)
3316 if (N0.getOpcode() == ISD::TRUNCATE)
3317 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3318 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3319 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3320 N0.getOpcode() == ISD::ANY_EXTEND) {
3321 if (N0.getOperand(0).getValueType().bitsLT(VT))
3322 // if the source is smaller than the dest, we still need an extend
3323 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3324 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3325 // if the source is larger than the dest, than we just need the truncate
3326 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3328 // if the source and dest are the same type, we can drop both the extend
3330 return N0.getOperand(0);
3333 // See if we can simplify the input to this truncate through knowledge that
3334 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3337 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3338 VT.getSizeInBits()));
3340 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3342 // fold (truncate (load x)) -> (smaller load x)
3343 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3344 return ReduceLoadWidth(N);
3347 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3348 SDOperand Elt = N->getOperand(i);
3349 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3351 return Elt.getOperand(Elt.ResNo).Val;
3354 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3355 /// if load locations are consecutive.
3356 SDOperand DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT VT) {
3357 assert(N->getOpcode() == ISD::BUILD_PAIR);
3359 SDNode *LD1 = getBuildPairElt(N, 0);
3360 if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3362 MVT LD1VT = LD1->getValueType(0);
3363 SDNode *LD2 = getBuildPairElt(N, 1);
3364 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3365 if (ISD::isNON_EXTLoad(LD2) &&
3367 // If both are volatile this would reduce the number of volatile loads.
3368 // If one is volatile it might be ok, but play conservative and bail out.
3369 !cast<LoadSDNode>(LD1)->isVolatile() &&
3370 !cast<LoadSDNode>(LD2)->isVolatile() &&
3371 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
3372 LoadSDNode *LD = cast<LoadSDNode>(LD1);
3373 unsigned Align = LD->getAlignment();
3374 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
3375 getABITypeAlignment(VT.getTypeForMVT());
3376 if (NewAlign <= Align &&
3377 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT)))
3378 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(),
3379 LD->getSrcValue(), LD->getSrcValueOffset(),
3385 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3386 SDOperand N0 = N->getOperand(0);
3387 MVT VT = N->getValueType(0);
3389 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3390 // Only do this before legalize, since afterward the target may be depending
3391 // on the bitconvert.
3392 // First check to see if this is all constant.
3393 if (!AfterLegalize &&
3394 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3396 bool isSimple = true;
3397 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3398 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3399 N0.getOperand(i).getOpcode() != ISD::Constant &&
3400 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3405 MVT DestEltVT = N->getValueType(0).getVectorElementType();
3406 assert(!DestEltVT.isVector() &&
3407 "Element type of vector ValueType must not be vector!");
3409 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3413 // If the input is a constant, let getNode() fold it.
3414 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3415 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3416 if (Res.Val != N) return Res;
3419 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3420 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3422 // fold (conv (load x)) -> (load (conv*)x)
3423 // If the resultant load doesn't need a higher alignment than the original!
3424 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
3425 // Do not change the width of a volatile load.
3426 !cast<LoadSDNode>(N0)->isVolatile() &&
3427 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT))) {
3428 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3429 unsigned Align = TLI.getTargetMachine().getTargetData()->
3430 getABITypeAlignment(VT.getTypeForMVT());
3431 unsigned OrigAlign = LN0->getAlignment();
3432 if (Align <= OrigAlign) {
3433 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3434 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3435 LN0->isVolatile(), OrigAlign);
3437 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3443 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3444 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3445 // This often reduces constant pool loads.
3446 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3447 N0.Val->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3448 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3449 AddToWorkList(NewConv.Val);
3451 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3452 if (N0.getOpcode() == ISD::FNEG)
3453 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3454 assert(N0.getOpcode() == ISD::FABS);
3455 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3458 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3459 // Note that we don't handle copysign(x,cst) because this can always be folded
3460 // to an fneg or fabs.
3461 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
3462 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3463 VT.isInteger() && !VT.isVector()) {
3464 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3465 SDOperand X = DAG.getNode(ISD::BIT_CONVERT,
3466 MVT::getIntegerVT(OrigXWidth),
3468 AddToWorkList(X.Val);
3470 // If X has a different width than the result/lhs, sext it or truncate it.
3471 unsigned VTWidth = VT.getSizeInBits();
3472 if (OrigXWidth < VTWidth) {
3473 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3474 AddToWorkList(X.Val);
3475 } else if (OrigXWidth > VTWidth) {
3476 // To get the sign bit in the right place, we have to shift it right
3477 // before truncating.
3478 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3479 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3480 AddToWorkList(X.Val);
3481 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3482 AddToWorkList(X.Val);
3485 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3486 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3487 AddToWorkList(X.Val);
3489 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3490 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3491 AddToWorkList(Cst.Val);
3493 return DAG.getNode(ISD::OR, VT, X, Cst);
3496 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3497 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3498 SDOperand CombineLD = CombineConsecutiveLoads(N0.Val, VT);
3506 SDOperand DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3507 MVT VT = N->getValueType(0);
3508 return CombineConsecutiveLoads(N, VT);
3511 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3512 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3513 /// destination element value type.
3514 SDOperand DAGCombiner::
3515 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT DstEltVT) {
3516 MVT SrcEltVT = BV->getOperand(0).getValueType();
3518 // If this is already the right type, we're done.
3519 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3521 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3522 unsigned DstBitSize = DstEltVT.getSizeInBits();
3524 // If this is a conversion of N elements of one type to N elements of another
3525 // type, convert each element. This handles FP<->INT cases.
3526 if (SrcBitSize == DstBitSize) {
3527 SmallVector<SDOperand, 8> Ops;
3528 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3529 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3530 AddToWorkList(Ops.back().Val);
3532 MVT VT = MVT::getVectorVT(DstEltVT,
3533 BV->getValueType(0).getVectorNumElements());
3534 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3537 // Otherwise, we're growing or shrinking the elements. To avoid having to
3538 // handle annoying details of growing/shrinking FP values, we convert them to
3540 if (SrcEltVT.isFloatingPoint()) {
3541 // Convert the input float vector to a int vector where the elements are the
3543 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3544 MVT IntVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits());
3545 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3549 // Now we know the input is an integer vector. If the output is a FP type,
3550 // convert to integer first, then to FP of the right size.
3551 if (DstEltVT.isFloatingPoint()) {
3552 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3553 MVT TmpVT = MVT::getIntegerVT(DstEltVT.getSizeInBits());
3554 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3556 // Next, convert to FP elements of the same size.
3557 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3560 // Okay, we know the src/dst types are both integers of differing types.
3561 // Handling growing first.
3562 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
3563 if (SrcBitSize < DstBitSize) {
3564 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3566 SmallVector<SDOperand, 8> Ops;
3567 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3568 i += NumInputsPerOutput) {
3569 bool isLE = TLI.isLittleEndian();
3570 APInt NewBits = APInt(DstBitSize, 0);
3571 bool EltIsUndef = true;
3572 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3573 // Shift the previously computed bits over.
3574 NewBits <<= SrcBitSize;
3575 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3576 if (Op.getOpcode() == ISD::UNDEF) continue;
3580 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
3584 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3586 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3589 MVT VT = MVT::getVectorVT(DstEltVT, Ops.size());
3590 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3593 // Finally, this must be the case where we are shrinking elements: each input
3594 // turns into multiple outputs.
3595 bool isS2V = ISD::isScalarToVector(BV);
3596 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3597 MVT VT = MVT::getVectorVT(DstEltVT, NumOutputsPerInput*BV->getNumOperands());
3598 SmallVector<SDOperand, 8> Ops;
3599 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3600 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3601 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3602 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3605 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
3606 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3607 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3608 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3609 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3610 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3611 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
3612 OpVal = OpVal.lshr(DstBitSize);
3615 // For big endian targets, swap the order of the pieces of each element.
3616 if (TLI.isBigEndian())
3617 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3619 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3624 SDOperand DAGCombiner::visitFADD(SDNode *N) {
3625 SDOperand N0 = N->getOperand(0);
3626 SDOperand N1 = N->getOperand(1);
3627 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3628 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3629 MVT VT = N->getValueType(0);
3632 if (VT.isVector()) {
3633 SDOperand FoldedVOp = SimplifyVBinOp(N);
3634 if (FoldedVOp.Val) return FoldedVOp;
3637 // fold (fadd c1, c2) -> c1+c2
3638 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3639 return DAG.getNode(ISD::FADD, VT, N0, N1);
3640 // canonicalize constant to RHS
3641 if (N0CFP && !N1CFP)
3642 return DAG.getNode(ISD::FADD, VT, N1, N0);
3643 // fold (A + (-B)) -> A-B
3644 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3645 return DAG.getNode(ISD::FSUB, VT, N0,
3646 GetNegatedExpression(N1, DAG, AfterLegalize));
3647 // fold ((-A) + B) -> B-A
3648 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3649 return DAG.getNode(ISD::FSUB, VT, N1,
3650 GetNegatedExpression(N0, DAG, AfterLegalize));
3652 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3653 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3654 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3655 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3656 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3661 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3662 SDOperand N0 = N->getOperand(0);
3663 SDOperand N1 = N->getOperand(1);
3664 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3665 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3666 MVT VT = N->getValueType(0);
3669 if (VT.isVector()) {
3670 SDOperand FoldedVOp = SimplifyVBinOp(N);
3671 if (FoldedVOp.Val) return FoldedVOp;
3674 // fold (fsub c1, c2) -> c1-c2
3675 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3676 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3678 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3679 if (isNegatibleForFree(N1, AfterLegalize))
3680 return GetNegatedExpression(N1, DAG, AfterLegalize);
3681 return DAG.getNode(ISD::FNEG, VT, N1);
3683 // fold (A-(-B)) -> A+B
3684 if (isNegatibleForFree(N1, AfterLegalize))
3685 return DAG.getNode(ISD::FADD, VT, N0,
3686 GetNegatedExpression(N1, DAG, AfterLegalize));
3691 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3692 SDOperand N0 = N->getOperand(0);
3693 SDOperand N1 = N->getOperand(1);
3694 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3695 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3696 MVT VT = N->getValueType(0);
3699 if (VT.isVector()) {
3700 SDOperand FoldedVOp = SimplifyVBinOp(N);
3701 if (FoldedVOp.Val) return FoldedVOp;
3704 // fold (fmul c1, c2) -> c1*c2
3705 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3706 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3707 // canonicalize constant to RHS
3708 if (N0CFP && !N1CFP)
3709 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3710 // fold (fmul X, 2.0) -> (fadd X, X)
3711 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3712 return DAG.getNode(ISD::FADD, VT, N0, N0);
3713 // fold (fmul X, -1.0) -> (fneg X)
3714 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3715 return DAG.getNode(ISD::FNEG, VT, N0);
3718 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3719 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3720 // Both can be negated for free, check to see if at least one is cheaper
3722 if (LHSNeg == 2 || RHSNeg == 2)
3723 return DAG.getNode(ISD::FMUL, VT,
3724 GetNegatedExpression(N0, DAG, AfterLegalize),
3725 GetNegatedExpression(N1, DAG, AfterLegalize));
3729 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3730 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3731 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3732 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3733 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3738 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3739 SDOperand N0 = N->getOperand(0);
3740 SDOperand N1 = N->getOperand(1);
3741 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3742 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3743 MVT VT = N->getValueType(0);
3746 if (VT.isVector()) {
3747 SDOperand FoldedVOp = SimplifyVBinOp(N);
3748 if (FoldedVOp.Val) return FoldedVOp;
3751 // fold (fdiv c1, c2) -> c1/c2
3752 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3753 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3757 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3758 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3759 // Both can be negated for free, check to see if at least one is cheaper
3761 if (LHSNeg == 2 || RHSNeg == 2)
3762 return DAG.getNode(ISD::FDIV, VT,
3763 GetNegatedExpression(N0, DAG, AfterLegalize),
3764 GetNegatedExpression(N1, DAG, AfterLegalize));
3771 SDOperand DAGCombiner::visitFREM(SDNode *N) {
3772 SDOperand N0 = N->getOperand(0);
3773 SDOperand N1 = N->getOperand(1);
3774 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3775 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3776 MVT VT = N->getValueType(0);
3778 // fold (frem c1, c2) -> fmod(c1,c2)
3779 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3780 return DAG.getNode(ISD::FREM, VT, N0, N1);
3785 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3786 SDOperand N0 = N->getOperand(0);
3787 SDOperand N1 = N->getOperand(1);
3788 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3789 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3790 MVT VT = N->getValueType(0);
3792 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
3793 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3796 const APFloat& V = N1CFP->getValueAPF();
3797 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3798 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3799 if (!V.isNegative())
3800 return DAG.getNode(ISD::FABS, VT, N0);
3802 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3805 // copysign(fabs(x), y) -> copysign(x, y)
3806 // copysign(fneg(x), y) -> copysign(x, y)
3807 // copysign(copysign(x,z), y) -> copysign(x, y)
3808 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3809 N0.getOpcode() == ISD::FCOPYSIGN)
3810 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3812 // copysign(x, abs(y)) -> abs(x)
3813 if (N1.getOpcode() == ISD::FABS)
3814 return DAG.getNode(ISD::FABS, VT, N0);
3816 // copysign(x, copysign(y,z)) -> copysign(x, z)
3817 if (N1.getOpcode() == ISD::FCOPYSIGN)
3818 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3820 // copysign(x, fp_extend(y)) -> copysign(x, y)
3821 // copysign(x, fp_round(y)) -> copysign(x, y)
3822 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3823 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3830 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3831 SDOperand N0 = N->getOperand(0);
3832 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3833 MVT VT = N->getValueType(0);
3834 MVT OpVT = N0.getValueType();
3836 // fold (sint_to_fp c1) -> c1fp
3837 if (N0C && OpVT != MVT::ppcf128)
3838 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3840 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
3841 // but UINT_TO_FP is legal on this target, try to convert.
3842 if (!TLI.isOperationLegal(ISD::SINT_TO_FP, OpVT) &&
3843 TLI.isOperationLegal(ISD::UINT_TO_FP, OpVT)) {
3844 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
3845 if (DAG.SignBitIsZero(N0))
3846 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3853 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3854 SDOperand N0 = N->getOperand(0);
3855 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3856 MVT VT = N->getValueType(0);
3857 MVT OpVT = N0.getValueType();
3859 // fold (uint_to_fp c1) -> c1fp
3860 if (N0C && OpVT != MVT::ppcf128)
3861 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3863 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
3864 // but SINT_TO_FP is legal on this target, try to convert.
3865 if (!TLI.isOperationLegal(ISD::UINT_TO_FP, OpVT) &&
3866 TLI.isOperationLegal(ISD::SINT_TO_FP, OpVT)) {
3867 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
3868 if (DAG.SignBitIsZero(N0))
3869 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3875 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3876 SDOperand N0 = N->getOperand(0);
3877 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3878 MVT VT = N->getValueType(0);
3880 // fold (fp_to_sint c1fp) -> c1
3882 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3886 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3887 SDOperand N0 = N->getOperand(0);
3888 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3889 MVT VT = N->getValueType(0);
3891 // fold (fp_to_uint c1fp) -> c1
3892 if (N0CFP && VT != MVT::ppcf128)
3893 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3897 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3898 SDOperand N0 = N->getOperand(0);
3899 SDOperand N1 = N->getOperand(1);
3900 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3901 MVT VT = N->getValueType(0);
3903 // fold (fp_round c1fp) -> c1fp
3904 if (N0CFP && N0.getValueType() != MVT::ppcf128)
3905 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
3907 // fold (fp_round (fp_extend x)) -> x
3908 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3909 return N0.getOperand(0);
3911 // fold (fp_round (fp_round x)) -> (fp_round x)
3912 if (N0.getOpcode() == ISD::FP_ROUND) {
3913 // This is a value preserving truncation if both round's are.
3914 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3915 N0.Val->getConstantOperandVal(1) == 1;
3916 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3917 DAG.getIntPtrConstant(IsTrunc));
3920 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3921 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
3922 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
3923 AddToWorkList(Tmp.Val);
3924 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3930 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3931 SDOperand N0 = N->getOperand(0);
3932 MVT VT = N->getValueType(0);
3933 MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3934 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3936 // fold (fp_round_inreg c1fp) -> c1fp
3938 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
3939 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3944 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3945 SDOperand N0 = N->getOperand(0);
3946 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3947 MVT VT = N->getValueType(0);
3949 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
3950 if (N->hasOneUse() &&
3951 N->use_begin().getUse().getSDOperand().getOpcode() == ISD::FP_ROUND)
3954 // fold (fp_extend c1fp) -> c1fp
3955 if (N0CFP && VT != MVT::ppcf128)
3956 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
3958 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3960 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3961 SDOperand In = N0.getOperand(0);
3962 if (In.getValueType() == VT) return In;
3963 if (VT.bitsLT(In.getValueType()))
3964 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3965 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3968 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
3969 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3970 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3971 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3972 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3973 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3974 LN0->getBasePtr(), LN0->getSrcValue(),
3975 LN0->getSrcValueOffset(),
3978 LN0->getAlignment());
3979 CombineTo(N, ExtLoad);
3980 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3981 DAG.getIntPtrConstant(1)),
3982 ExtLoad.getValue(1));
3983 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3989 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3990 SDOperand N0 = N->getOperand(0);
3992 if (isNegatibleForFree(N0, AfterLegalize))
3993 return GetNegatedExpression(N0, DAG, AfterLegalize);
3995 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
3996 // constant pool values.
3997 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3998 N0.getOperand(0).getValueType().isInteger() &&
3999 !N0.getOperand(0).getValueType().isVector()) {
4000 SDOperand Int = N0.getOperand(0);
4001 MVT IntVT = Int.getValueType();
4002 if (IntVT.isInteger() && !IntVT.isVector()) {
4003 Int = DAG.getNode(ISD::XOR, IntVT, Int,
4004 DAG.getConstant(IntVT.getIntegerVTSignBit(), IntVT));
4005 AddToWorkList(Int.Val);
4006 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4013 SDOperand DAGCombiner::visitFABS(SDNode *N) {
4014 SDOperand N0 = N->getOperand(0);
4015 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4016 MVT VT = N->getValueType(0);
4018 // fold (fabs c1) -> fabs(c1)
4019 if (N0CFP && VT != MVT::ppcf128)
4020 return DAG.getNode(ISD::FABS, VT, N0);
4021 // fold (fabs (fabs x)) -> (fabs x)
4022 if (N0.getOpcode() == ISD::FABS)
4023 return N->getOperand(0);
4024 // fold (fabs (fneg x)) -> (fabs x)
4025 // fold (fabs (fcopysign x, y)) -> (fabs x)
4026 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4027 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
4029 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4030 // constant pool values.
4031 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
4032 N0.getOperand(0).getValueType().isInteger() &&
4033 !N0.getOperand(0).getValueType().isVector()) {
4034 SDOperand Int = N0.getOperand(0);
4035 MVT IntVT = Int.getValueType();
4036 if (IntVT.isInteger() && !IntVT.isVector()) {
4037 Int = DAG.getNode(ISD::AND, IntVT, Int,
4038 DAG.getConstant(~IntVT.getIntegerVTSignBit(), IntVT));
4039 AddToWorkList(Int.Val);
4040 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4047 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
4048 SDOperand Chain = N->getOperand(0);
4049 SDOperand N1 = N->getOperand(1);
4050 SDOperand N2 = N->getOperand(2);
4051 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4053 // never taken branch, fold to chain
4054 if (N1C && N1C->isNullValue())
4056 // unconditional branch
4057 if (N1C && N1C->getAPIntValue() == 1)
4058 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
4059 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4061 if (N1.getOpcode() == ISD::SETCC &&
4062 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
4063 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
4064 N1.getOperand(0), N1.getOperand(1), N2);
4069 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4071 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
4072 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4073 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4075 // Use SimplifySetCC to simplify SETCC's.
4076 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
4077 if (Simp.Val) AddToWorkList(Simp.Val);
4079 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
4081 // fold br_cc true, dest -> br dest (unconditional branch)
4082 if (SCCC && !SCCC->isNullValue())
4083 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
4085 // fold br_cc false, dest -> unconditional fall through
4086 if (SCCC && SCCC->isNullValue())
4087 return N->getOperand(0);
4089 // fold to a simpler setcc
4090 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
4091 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
4092 Simp.getOperand(2), Simp.getOperand(0),
4093 Simp.getOperand(1), N->getOperand(4));
4098 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4099 /// pre-indexed load / store when the base pointer is an add or subtract
4100 /// and it has other uses besides the load / store. After the
4101 /// transformation, the new indexed load / store has effectively folded
4102 /// the add / subtract in and all of its other uses are redirected to the
4103 /// new load / store.
4104 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4111 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4112 if (LD->isIndexed())
4114 VT = LD->getMemoryVT();
4115 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4116 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4118 Ptr = LD->getBasePtr();
4119 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4120 if (ST->isIndexed())
4122 VT = ST->getMemoryVT();
4123 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4124 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4126 Ptr = ST->getBasePtr();
4131 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4132 // out. There is no reason to make this a preinc/predec.
4133 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4134 Ptr.Val->hasOneUse())
4137 // Ask the target to do addressing mode selection.
4140 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4141 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4143 // Don't create a indexed load / store with zero offset.
4144 if (isa<ConstantSDNode>(Offset) &&
4145 cast<ConstantSDNode>(Offset)->isNullValue())
4148 // Try turning it into a pre-indexed load / store except when:
4149 // 1) The new base ptr is a frame index.
4150 // 2) If N is a store and the new base ptr is either the same as or is a
4151 // predecessor of the value being stored.
4152 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4153 // that would create a cycle.
4154 // 4) All uses are load / store ops that use it as old base ptr.
4156 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4157 // (plus the implicit offset) to a register to preinc anyway.
4158 if (isa<FrameIndexSDNode>(BasePtr))
4163 SDOperand Val = cast<StoreSDNode>(N)->getValue();
4164 if (Val == BasePtr || BasePtr.Val->isPredecessorOf(Val.Val))
4168 // Now check for #3 and #4.
4169 bool RealUse = false;
4170 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4171 E = Ptr.Val->use_end(); I != E; ++I) {
4175 if (Use->isPredecessorOf(N))
4178 if (!((Use->getOpcode() == ISD::LOAD &&
4179 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4180 (Use->getOpcode() == ISD::STORE &&
4181 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4189 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4191 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4194 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4195 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4197 WorkListRemover DeadNodes(*this);
4199 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4201 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4204 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4208 // Finally, since the node is now dead, remove it from the graph.
4211 // Replace the uses of Ptr with uses of the updated base value.
4212 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4214 removeFromWorkList(Ptr.Val);
4215 DAG.DeleteNode(Ptr.Val);
4220 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4221 /// add / sub of the base pointer node into a post-indexed load / store.
4222 /// The transformation folded the add / subtract into the new indexed
4223 /// load / store effectively and all of its uses are redirected to the
4224 /// new load / store.
4225 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4232 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4233 if (LD->isIndexed())
4235 VT = LD->getMemoryVT();
4236 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4237 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4239 Ptr = LD->getBasePtr();
4240 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4241 if (ST->isIndexed())
4243 VT = ST->getMemoryVT();
4244 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4245 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4247 Ptr = ST->getBasePtr();
4252 if (Ptr.Val->hasOneUse())
4255 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4256 E = Ptr.Val->use_end(); I != E; ++I) {
4259 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4264 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4265 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4267 std::swap(BasePtr, Offset);
4270 // Don't create a indexed load / store with zero offset.
4271 if (isa<ConstantSDNode>(Offset) &&
4272 cast<ConstantSDNode>(Offset)->isNullValue())
4275 // Try turning it into a post-indexed load / store except when
4276 // 1) All uses are load / store ops that use it as base ptr.
4277 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4278 // nor a successor of N. Otherwise, if Op is folded that would
4282 bool TryNext = false;
4283 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4284 EE = BasePtr.Val->use_end(); II != EE; ++II) {
4289 // If all the uses are load / store addresses, then don't do the
4291 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4292 bool RealUse = false;
4293 for (SDNode::use_iterator III = Use->use_begin(),
4294 EEE = Use->use_end(); III != EEE; ++III) {
4295 SDNode *UseUse = *III;
4296 if (!((UseUse->getOpcode() == ISD::LOAD &&
4297 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
4298 (UseUse->getOpcode() == ISD::STORE &&
4299 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
4313 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4314 SDOperand Result = isLoad
4315 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4316 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4319 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4320 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4322 WorkListRemover DeadNodes(*this);
4324 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4326 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4329 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4333 // Finally, since the node is now dead, remove it from the graph.
4336 // Replace the uses of Use with uses of the updated base value.
4337 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4338 Result.getValue(isLoad ? 1 : 0),
4340 removeFromWorkList(Op);
4349 /// InferAlignment - If we can infer some alignment information from this
4350 /// pointer, return it.
4351 static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4352 // If this is a direct reference to a stack slot, use information about the
4353 // stack slot's alignment.
4354 int FrameIdx = 1 << 31;
4355 int64_t FrameOffset = 0;
4356 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4357 FrameIdx = FI->getIndex();
4358 } else if (Ptr.getOpcode() == ISD::ADD &&
4359 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4360 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4361 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4362 FrameOffset = Ptr.getConstantOperandVal(1);
4365 if (FrameIdx != (1 << 31)) {
4366 // FIXME: Handle FI+CST.
4367 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4368 if (MFI.isFixedObjectIndex(FrameIdx)) {
4369 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4371 // The alignment of the frame index can be determined from its offset from
4372 // the incoming frame position. If the frame object is at offset 32 and
4373 // the stack is guaranteed to be 16-byte aligned, then we know that the
4374 // object is 16-byte aligned.
4375 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4376 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4378 // Finally, the frame object itself may have a known alignment. Factor
4379 // the alignment + offset into a new alignment. For example, if we know
4380 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4381 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4382 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4383 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4385 return std::max(Align, FIInfoAlign);
4392 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4393 LoadSDNode *LD = cast<LoadSDNode>(N);
4394 SDOperand Chain = LD->getChain();
4395 SDOperand Ptr = LD->getBasePtr();
4397 // Try to infer better alignment information than the load already has.
4398 if (LD->isUnindexed()) {
4399 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4400 if (Align > LD->getAlignment())
4401 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4402 Chain, Ptr, LD->getSrcValue(),
4403 LD->getSrcValueOffset(), LD->getMemoryVT(),
4404 LD->isVolatile(), Align);
4409 // If load is not volatile and there are no uses of the loaded value (and
4410 // the updated indexed value in case of indexed loads), change uses of the
4411 // chain value into uses of the chain input (i.e. delete the dead load).
4412 if (!LD->isVolatile()) {
4413 if (N->getValueType(1) == MVT::Other) {
4415 if (N->hasNUsesOfValue(0, 0)) {
4416 // It's not safe to use the two value CombineTo variant here. e.g.
4417 // v1, chain2 = load chain1, loc
4418 // v2, chain3 = load chain2, loc
4420 // Now we replace use of chain2 with chain1. This makes the second load
4421 // isomorphic to the one we are deleting, and thus makes this load live.
4422 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4423 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4425 WorkListRemover DeadNodes(*this);
4426 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
4427 if (N->use_empty()) {
4428 removeFromWorkList(N);
4431 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4435 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4436 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4437 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4438 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4439 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4440 DOUT << " and 2 other values\n";
4441 WorkListRemover DeadNodes(*this);
4442 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
4443 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
4444 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
4446 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
4447 removeFromWorkList(N);
4449 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4454 // If this load is directly stored, replace the load value with the stored
4456 // TODO: Handle store large -> read small portion.
4457 // TODO: Handle TRUNCSTORE/LOADEXT
4458 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4459 !LD->isVolatile()) {
4460 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4461 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4462 if (PrevST->getBasePtr() == Ptr &&
4463 PrevST->getValue().getValueType() == N->getValueType(0))
4464 return CombineTo(N, Chain.getOperand(1), Chain);
4469 // Walk up chain skipping non-aliasing memory nodes.
4470 SDOperand BetterChain = FindBetterChain(N, Chain);
4472 // If there is a better chain.
4473 if (Chain != BetterChain) {
4476 // Replace the chain to void dependency.
4477 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4478 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
4479 LD->getSrcValue(), LD->getSrcValueOffset(),
4480 LD->isVolatile(), LD->getAlignment());
4482 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4483 LD->getValueType(0),
4484 BetterChain, Ptr, LD->getSrcValue(),
4485 LD->getSrcValueOffset(),
4488 LD->getAlignment());
4491 // Create token factor to keep old chain connected.
4492 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4493 Chain, ReplLoad.getValue(1));
4495 // Replace uses with load result and token factor. Don't add users
4497 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4501 // Try transforming N to an indexed load.
4502 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4503 return SDOperand(N, 0);
4509 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4510 StoreSDNode *ST = cast<StoreSDNode>(N);
4511 SDOperand Chain = ST->getChain();
4512 SDOperand Value = ST->getValue();
4513 SDOperand Ptr = ST->getBasePtr();
4515 // Try to infer better alignment information than the store already has.
4516 if (ST->isUnindexed()) {
4517 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4518 if (Align > ST->getAlignment())
4519 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4520 ST->getSrcValueOffset(), ST->getMemoryVT(),
4521 ST->isVolatile(), Align);
4525 // If this is a store of a bit convert, store the input value if the
4526 // resultant store does not need a higher alignment than the original.
4527 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
4528 ST->isUnindexed()) {
4529 unsigned Align = ST->getAlignment();
4530 MVT SVT = Value.getOperand(0).getValueType();
4531 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4532 getABITypeAlignment(SVT.getTypeForMVT());
4533 if (Align <= OrigAlign &&
4534 ((!AfterLegalize && !ST->isVolatile()) ||
4535 TLI.isOperationLegal(ISD::STORE, SVT)))
4536 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4537 ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign);
4540 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4541 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4542 // NOTE: If the original store is volatile, this transform must not increase
4543 // the number of stores. For example, on x86-32 an f64 can be stored in one
4544 // processor operation but an i64 (which is not legal) requires two. So the
4545 // transform should not be done in this case.
4546 if (Value.getOpcode() != ISD::TargetConstantFP) {
4548 switch (CFP->getValueType(0).getSimpleVT()) {
4549 default: assert(0 && "Unknown FP type");
4550 case MVT::f80: // We don't do this for these yet.
4555 if ((!AfterLegalize && !ST->isVolatile()) ||
4556 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4557 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4558 convertToAPInt().getZExtValue(), MVT::i32);
4559 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4560 ST->getSrcValueOffset(), ST->isVolatile(),
4561 ST->getAlignment());
4565 if ((!AfterLegalize && !ST->isVolatile()) ||
4566 TLI.isOperationLegal(ISD::STORE, MVT::i64)) {
4567 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4568 getZExtValue(), MVT::i64);
4569 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4570 ST->getSrcValueOffset(), ST->isVolatile(),
4571 ST->getAlignment());
4572 } else if (!ST->isVolatile() &&
4573 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4574 // Many FP stores are not made apparent until after legalize, e.g. for
4575 // argument passing. Since this is so common, custom legalize the
4576 // 64-bit integer store into two 32-bit stores.
4577 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
4578 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4579 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
4580 if (TLI.isBigEndian()) std::swap(Lo, Hi);
4582 int SVOffset = ST->getSrcValueOffset();
4583 unsigned Alignment = ST->getAlignment();
4584 bool isVolatile = ST->isVolatile();
4586 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4587 ST->getSrcValueOffset(),
4588 isVolatile, ST->getAlignment());
4589 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4590 DAG.getConstant(4, Ptr.getValueType()));
4592 Alignment = MinAlign(Alignment, 4U);
4593 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4594 SVOffset, isVolatile, Alignment);
4595 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4603 // Walk up chain skipping non-aliasing memory nodes.
4604 SDOperand BetterChain = FindBetterChain(N, Chain);
4606 // If there is a better chain.
4607 if (Chain != BetterChain) {
4608 // Replace the chain to avoid dependency.
4609 SDOperand ReplStore;
4610 if (ST->isTruncatingStore()) {
4611 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4612 ST->getSrcValue(),ST->getSrcValueOffset(),
4614 ST->isVolatile(), ST->getAlignment());
4616 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4617 ST->getSrcValue(), ST->getSrcValueOffset(),
4618 ST->isVolatile(), ST->getAlignment());
4621 // Create token to keep both nodes around.
4623 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4625 // Don't add users to work list.
4626 return CombineTo(N, Token, false);
4630 // Try transforming N to an indexed store.
4631 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4632 return SDOperand(N, 0);
4634 // FIXME: is there such a thing as a truncating indexed store?
4635 if (ST->isTruncatingStore() && ST->isUnindexed() &&
4636 Value.getValueType().isInteger()) {
4637 // See if we can simplify the input to this truncstore with knowledge that
4638 // only the low bits are being used. For example:
4639 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4641 GetDemandedBits(Value,
4642 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4643 ST->getMemoryVT().getSizeInBits()));
4644 AddToWorkList(Value.Val);
4646 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4647 ST->getSrcValueOffset(), ST->getMemoryVT(),
4648 ST->isVolatile(), ST->getAlignment());
4650 // Otherwise, see if we can simplify the operation with
4651 // SimplifyDemandedBits, which only works if the value has a single use.
4652 if (SimplifyDemandedBits(Value,
4653 APInt::getLowBitsSet(
4654 Value.getValueSizeInBits(),
4655 ST->getMemoryVT().getSizeInBits())))
4656 return SDOperand(N, 0);
4659 // If this is a load followed by a store to the same location, then the store
4661 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
4662 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
4663 ST->isUnindexed() && !ST->isVolatile() &&
4664 // There can't be any side effects between the load and store, such as
4666 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
4667 // The store is dead, remove it.
4672 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4673 // truncating store. We can do this even if this is already a truncstore.
4674 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4675 && Value.Val->hasOneUse() && ST->isUnindexed() &&
4676 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4677 ST->getMemoryVT())) {
4678 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4679 ST->getSrcValueOffset(), ST->getMemoryVT(),
4680 ST->isVolatile(), ST->getAlignment());
4686 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4687 SDOperand InVec = N->getOperand(0);
4688 SDOperand InVal = N->getOperand(1);
4689 SDOperand EltNo = N->getOperand(2);
4691 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4692 // vector with the inserted element.
4693 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4694 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4695 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4696 if (Elt < Ops.size())
4698 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4699 &Ops[0], Ops.size());
4705 SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4706 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
4707 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
4708 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
4710 // Perform only after legalization to ensure build_vector / vector_shuffle
4711 // optimizations have already been done.
4712 if (!AfterLegalize) return SDOperand();
4714 SDOperand InVec = N->getOperand(0);
4715 SDOperand EltNo = N->getOperand(1);
4717 if (isa<ConstantSDNode>(EltNo)) {
4718 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4719 bool NewLoad = false;
4720 MVT VT = InVec.getValueType();
4721 MVT EVT = VT.getVectorElementType();
4723 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4724 MVT BCVT = InVec.getOperand(0).getValueType();
4725 if (!BCVT.isVector() || EVT.bitsGT(BCVT.getVectorElementType()))
4727 InVec = InVec.getOperand(0);
4728 EVT = BCVT.getVectorElementType();
4732 LoadSDNode *LN0 = NULL;
4733 if (ISD::isNormalLoad(InVec.Val))
4734 LN0 = cast<LoadSDNode>(InVec);
4735 else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4736 InVec.getOperand(0).getValueType() == EVT &&
4737 ISD::isNormalLoad(InVec.getOperand(0).Val)) {
4738 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4739 } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
4740 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
4742 // (load $addr+1*size)
4743 unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2).
4744 getOperand(Elt))->getValue();
4745 unsigned NumElems = InVec.getOperand(2).getNumOperands();
4746 InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
4747 if (InVec.getOpcode() == ISD::BIT_CONVERT)
4748 InVec = InVec.getOperand(0);
4749 if (ISD::isNormalLoad(InVec.Val)) {
4750 LN0 = cast<LoadSDNode>(InVec);
4751 Elt = (Idx < NumElems) ? Idx : Idx - NumElems;
4754 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
4757 unsigned Align = LN0->getAlignment();
4759 // Check the resultant load doesn't need a higher alignment than the
4761 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4762 getABITypeAlignment(LVT.getTypeForMVT());
4763 if (NewAlign > Align || !TLI.isOperationLegal(ISD::LOAD, LVT))
4768 SDOperand NewPtr = LN0->getBasePtr();
4770 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
4771 MVT PtrType = NewPtr.getValueType();
4772 if (TLI.isBigEndian())
4773 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
4774 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
4775 DAG.getConstant(PtrOff, PtrType));
4777 return DAG.getLoad(LVT, LN0->getChain(), NewPtr,
4778 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4779 LN0->isVolatile(), Align);
4785 SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4786 unsigned NumInScalars = N->getNumOperands();
4787 MVT VT = N->getValueType(0);
4788 unsigned NumElts = VT.getVectorNumElements();
4789 MVT EltType = VT.getVectorElementType();
4791 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4792 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4793 // at most two distinct vectors, turn this into a shuffle node.
4794 SDOperand VecIn1, VecIn2;
4795 for (unsigned i = 0; i != NumInScalars; ++i) {
4796 // Ignore undef inputs.
4797 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4799 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4800 // constant index, bail out.
4801 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4802 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4803 VecIn1 = VecIn2 = SDOperand(0, 0);
4807 // If the input vector type disagrees with the result of the build_vector,
4808 // we can't make a shuffle.
4809 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4810 if (ExtractedFromVec.getValueType() != VT) {
4811 VecIn1 = VecIn2 = SDOperand(0, 0);
4815 // Otherwise, remember this. We allow up to two distinct input vectors.
4816 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4819 if (VecIn1.Val == 0) {
4820 VecIn1 = ExtractedFromVec;
4821 } else if (VecIn2.Val == 0) {
4822 VecIn2 = ExtractedFromVec;
4825 VecIn1 = VecIn2 = SDOperand(0, 0);
4830 // If everything is good, we can make a shuffle operation.
4832 SmallVector<SDOperand, 8> BuildVecIndices;
4833 for (unsigned i = 0; i != NumInScalars; ++i) {
4834 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4835 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4839 SDOperand Extract = N->getOperand(i);
4841 // If extracting from the first vector, just use the index directly.
4842 if (Extract.getOperand(0) == VecIn1) {
4843 BuildVecIndices.push_back(Extract.getOperand(1));
4847 // Otherwise, use InIdx + VecSize
4848 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
4849 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
4852 // Add count and size info.
4853 MVT BuildVecVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
4855 // Return the new VECTOR_SHUFFLE node.
4861 // Use an undef build_vector as input for the second operand.
4862 std::vector<SDOperand> UnOps(NumInScalars,
4863 DAG.getNode(ISD::UNDEF,
4865 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4866 &UnOps[0], UnOps.size());
4867 AddToWorkList(Ops[1].Val);
4869 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4870 &BuildVecIndices[0], BuildVecIndices.size());
4871 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4877 SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4878 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4879 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4880 // inputs come from at most two distinct vectors, turn this into a shuffle
4883 // If we only have one input vector, we don't need to do any concatenation.
4884 if (N->getNumOperands() == 1) {
4885 return N->getOperand(0);
4891 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4892 SDOperand ShufMask = N->getOperand(2);
4893 unsigned NumElts = ShufMask.getNumOperands();
4895 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4896 bool isIdentity = true;
4897 for (unsigned i = 0; i != NumElts; ++i) {
4898 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4899 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4904 if (isIdentity) return N->getOperand(0);
4906 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4908 for (unsigned i = 0; i != NumElts; ++i) {
4909 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4910 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4915 if (isIdentity) return N->getOperand(1);
4917 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4919 bool isUnary = true;
4920 bool isSplat = true;
4922 unsigned BaseIdx = 0;
4923 for (unsigned i = 0; i != NumElts; ++i)
4924 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4925 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4926 int V = (Idx < NumElts) ? 0 : 1;
4940 SDOperand N0 = N->getOperand(0);
4941 SDOperand N1 = N->getOperand(1);
4942 // Normalize unary shuffle so the RHS is undef.
4943 if (isUnary && VecNum == 1)
4946 // If it is a splat, check if the argument vector is a build_vector with
4947 // all scalar elements the same.
4951 // If this is a bit convert that changes the element type of the vector but
4952 // not the number of vector elements, look through it. Be careful not to
4953 // look though conversions that change things like v4f32 to v2f64.
4954 if (V->getOpcode() == ISD::BIT_CONVERT) {
4955 SDOperand ConvInput = V->getOperand(0);
4956 if (ConvInput.getValueType().isVector() &&
4957 ConvInput.getValueType().getVectorNumElements() == NumElts)
4961 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4962 unsigned NumElems = V->getNumOperands();
4963 if (NumElems > BaseIdx) {
4965 bool AllSame = true;
4966 for (unsigned i = 0; i != NumElems; ++i) {
4967 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4968 Base = V->getOperand(i);
4972 // Splat of <u, u, u, u>, return <u, u, u, u>
4975 for (unsigned i = 0; i != NumElems; ++i) {
4976 if (V->getOperand(i) != Base) {
4981 // Splat of <x, x, x, x>, return <x, x, x, x>
4988 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4990 if (isUnary || N0 == N1) {
4991 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4993 SmallVector<SDOperand, 8> MappedOps;
4994 for (unsigned i = 0; i != NumElts; ++i) {
4995 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4996 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4997 MappedOps.push_back(ShufMask.getOperand(i));
5000 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
5001 MappedOps.push_back(DAG.getConstant(NewIdx,
5002 ShufMask.getOperand(i).getValueType()));
5005 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
5006 &MappedOps[0], MappedOps.size());
5007 AddToWorkList(ShufMask.Val);
5008 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
5010 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
5017 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5018 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5019 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5020 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5021 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5022 SDOperand LHS = N->getOperand(0);
5023 SDOperand RHS = N->getOperand(1);
5024 if (N->getOpcode() == ISD::AND) {
5025 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5026 RHS = RHS.getOperand(0);
5027 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5028 std::vector<SDOperand> IdxOps;
5029 unsigned NumOps = RHS.getNumOperands();
5030 unsigned NumElts = NumOps;
5031 MVT EVT = RHS.getValueType().getVectorElementType();
5032 for (unsigned i = 0; i != NumElts; ++i) {
5033 SDOperand Elt = RHS.getOperand(i);
5034 if (!isa<ConstantSDNode>(Elt))
5036 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5037 IdxOps.push_back(DAG.getConstant(i, EVT));
5038 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5039 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
5044 // Let's see if the target supports this vector_shuffle.
5045 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
5048 // Return the new VECTOR_SHUFFLE node.
5049 MVT VT = MVT::getVectorVT(EVT, NumElts);
5050 std::vector<SDOperand> Ops;
5051 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
5053 AddToWorkList(LHS.Val);
5054 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
5055 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5056 &ZeroOps[0], ZeroOps.size()));
5057 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5058 &IdxOps[0], IdxOps.size()));
5059 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
5060 &Ops[0], Ops.size());
5061 if (VT != N->getValueType(0))
5062 Result = DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Result);
5069 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5070 SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
5071 // After legalize, the target may be depending on adds and other
5072 // binary ops to provide legal ways to construct constants or other
5073 // things. Simplifying them may result in a loss of legality.
5074 if (AfterLegalize) return SDOperand();
5076 MVT VT = N->getValueType(0);
5077 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5079 MVT EltType = VT.getVectorElementType();
5080 SDOperand LHS = N->getOperand(0);
5081 SDOperand RHS = N->getOperand(1);
5082 SDOperand Shuffle = XformToShuffleWithZero(N);
5083 if (Shuffle.Val) return Shuffle;
5085 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5087 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5088 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5089 SmallVector<SDOperand, 8> Ops;
5090 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5091 SDOperand LHSOp = LHS.getOperand(i);
5092 SDOperand RHSOp = RHS.getOperand(i);
5093 // If these two elements can't be folded, bail out.
5094 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5095 LHSOp.getOpcode() != ISD::Constant &&
5096 LHSOp.getOpcode() != ISD::ConstantFP) ||
5097 (RHSOp.getOpcode() != ISD::UNDEF &&
5098 RHSOp.getOpcode() != ISD::Constant &&
5099 RHSOp.getOpcode() != ISD::ConstantFP))
5101 // Can't fold divide by zero.
5102 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5103 N->getOpcode() == ISD::FDIV) {
5104 if ((RHSOp.getOpcode() == ISD::Constant &&
5105 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
5106 (RHSOp.getOpcode() == ISD::ConstantFP &&
5107 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
5110 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
5111 AddToWorkList(Ops.back().Val);
5112 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5113 Ops.back().getOpcode() == ISD::Constant ||
5114 Ops.back().getOpcode() == ISD::ConstantFP) &&
5115 "Scalar binop didn't fold!");
5118 if (Ops.size() == LHS.getNumOperands()) {
5119 MVT VT = LHS.getValueType();
5120 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
5127 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
5128 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5130 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
5131 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5132 // If we got a simplified select_cc node back from SimplifySelectCC, then
5133 // break it down into a new SETCC node, and a new SELECT node, and then return
5134 // the SELECT node, since we were called with a SELECT node.
5136 // Check to see if we got a select_cc back (to turn into setcc/select).
5137 // Otherwise, just return whatever node we got back, like fabs.
5138 if (SCC.getOpcode() == ISD::SELECT_CC) {
5139 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5140 SCC.getOperand(0), SCC.getOperand(1),
5142 AddToWorkList(SETCC.Val);
5143 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5144 SCC.getOperand(3), SETCC);
5151 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5152 /// are the two values being selected between, see if we can simplify the
5153 /// select. Callers of this should assume that TheSelect is deleted if this
5154 /// returns true. As such, they should return the appropriate thing (e.g. the
5155 /// node) back to the top-level of the DAG combiner loop to avoid it being
5158 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
5161 // If this is a select from two identical things, try to pull the operation
5162 // through the select.
5163 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5164 // If this is a load and the token chain is identical, replace the select
5165 // of two loads with a load through a select of the address to load from.
5166 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5167 // constants have been dropped into the constant pool.
5168 if (LHS.getOpcode() == ISD::LOAD &&
5169 // Do not let this transformation reduce the number of volatile loads.
5170 !cast<LoadSDNode>(LHS)->isVolatile() &&
5171 !cast<LoadSDNode>(RHS)->isVolatile() &&
5172 // Token chains must be identical.
5173 LHS.getOperand(0) == RHS.getOperand(0)) {
5174 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5175 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5177 // If this is an EXTLOAD, the VT's must match.
5178 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5179 // FIXME: this conflates two src values, discarding one. This is not
5180 // the right thing to do, but nothing uses srcvalues now. When they do,
5181 // turn SrcValue into a list of locations.
5183 if (TheSelect->getOpcode() == ISD::SELECT) {
5184 // Check that the condition doesn't reach either load. If so, folding
5185 // this will induce a cycle into the DAG.
5186 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5187 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val)) {
5188 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5189 TheSelect->getOperand(0), LLD->getBasePtr(),
5193 // Check that the condition doesn't reach either load. If so, folding
5194 // this will induce a cycle into the DAG.
5195 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5196 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5197 !LLD->isPredecessorOf(TheSelect->getOperand(1).Val) &&
5198 !RLD->isPredecessorOf(TheSelect->getOperand(1).Val)) {
5199 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5200 TheSelect->getOperand(0),
5201 TheSelect->getOperand(1),
5202 LLD->getBasePtr(), RLD->getBasePtr(),
5203 TheSelect->getOperand(4));
5209 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5210 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5211 Addr,LLD->getSrcValue(),
5212 LLD->getSrcValueOffset(),
5214 LLD->getAlignment());
5216 Load = DAG.getExtLoad(LLD->getExtensionType(),
5217 TheSelect->getValueType(0),
5218 LLD->getChain(), Addr, LLD->getSrcValue(),
5219 LLD->getSrcValueOffset(),
5222 LLD->getAlignment());
5224 // Users of the select now use the result of the load.
5225 CombineTo(TheSelect, Load);
5227 // Users of the old loads now use the new load's chain. We know the
5228 // old-load value is dead now.
5229 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5230 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5240 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5241 SDOperand N2, SDOperand N3,
5242 ISD::CondCode CC, bool NotExtCompare) {
5244 MVT VT = N2.getValueType();
5245 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5246 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5247 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5249 // Determine if the condition we're dealing with is constant
5250 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
5251 if (SCC.Val) AddToWorkList(SCC.Val);
5252 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5254 // fold select_cc true, x, y -> x
5255 if (SCCC && !SCCC->isNullValue())
5257 // fold select_cc false, x, y -> y
5258 if (SCCC && SCCC->isNullValue())
5261 // Check to see if we can simplify the select into an fabs node
5262 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5263 // Allow either -0.0 or 0.0
5264 if (CFP->getValueAPF().isZero()) {
5265 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5266 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5267 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5268 N2 == N3.getOperand(0))
5269 return DAG.getNode(ISD::FABS, VT, N0);
5271 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5272 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5273 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5274 N2.getOperand(0) == N3)
5275 return DAG.getNode(ISD::FABS, VT, N3);
5279 // Check to see if we can perform the "gzip trick", transforming
5280 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5281 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5282 N0.getValueType().isInteger() &&
5283 N2.getValueType().isInteger() &&
5284 (N1C->isNullValue() || // (a < 0) ? b : 0
5285 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5286 MVT XType = N0.getValueType();
5287 MVT AType = N2.getValueType();
5288 if (XType.bitsGE(AType)) {
5289 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5290 // single-bit constant.
5291 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5292 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5293 ShCtV = XType.getSizeInBits()-ShCtV-1;
5294 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5295 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5296 AddToWorkList(Shift.Val);
5297 if (XType.bitsGT(AType)) {
5298 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5299 AddToWorkList(Shift.Val);
5301 return DAG.getNode(ISD::AND, AType, Shift, N2);
5303 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5304 DAG.getConstant(XType.getSizeInBits()-1,
5305 TLI.getShiftAmountTy()));
5306 AddToWorkList(Shift.Val);
5307 if (XType.bitsGT(AType)) {
5308 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5309 AddToWorkList(Shift.Val);
5311 return DAG.getNode(ISD::AND, AType, Shift, N2);
5315 // fold select C, 16, 0 -> shl C, 4
5316 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5317 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5319 // If the caller doesn't want us to simplify this into a zext of a compare,
5321 if (NotExtCompare && N2C->getAPIntValue() == 1)
5324 // Get a SetCC of the condition
5325 // FIXME: Should probably make sure that setcc is legal if we ever have a
5326 // target where it isn't.
5327 SDOperand Temp, SCC;
5328 // cast from setcc result type to select result type
5329 if (AfterLegalize) {
5330 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5331 if (N2.getValueType().bitsLT(SCC.getValueType()))
5332 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5334 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5336 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5337 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5339 AddToWorkList(SCC.Val);
5340 AddToWorkList(Temp.Val);
5342 if (N2C->getAPIntValue() == 1)
5344 // shl setcc result by log2 n2c
5345 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5346 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5347 TLI.getShiftAmountTy()));
5350 // Check to see if this is the equivalent of setcc
5351 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5352 // otherwise, go ahead with the folds.
5353 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5354 MVT XType = N0.getValueType();
5355 if (!AfterLegalize ||
5356 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
5357 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5358 if (Res.getValueType() != VT)
5359 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5363 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5364 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5366 TLI.isOperationLegal(ISD::CTLZ, XType))) {
5367 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5368 return DAG.getNode(ISD::SRL, XType, Ctlz,
5369 DAG.getConstant(Log2_32(XType.getSizeInBits()),
5370 TLI.getShiftAmountTy()));
5372 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5373 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5374 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5376 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5377 DAG.getConstant(~0ULL, XType));
5378 return DAG.getNode(ISD::SRL, XType,
5379 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5380 DAG.getConstant(XType.getSizeInBits()-1,
5381 TLI.getShiftAmountTy()));
5383 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5384 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5385 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5386 DAG.getConstant(XType.getSizeInBits()-1,
5387 TLI.getShiftAmountTy()));
5388 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5392 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5393 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5394 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5395 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5396 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
5397 MVT XType = N0.getValueType();
5398 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5399 DAG.getConstant(XType.getSizeInBits()-1,
5400 TLI.getShiftAmountTy()));
5401 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5402 AddToWorkList(Shift.Val);
5403 AddToWorkList(Add.Val);
5404 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5406 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5407 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5408 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5409 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5410 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5411 MVT XType = N0.getValueType();
5412 if (SubC->isNullValue() && XType.isInteger()) {
5413 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5414 DAG.getConstant(XType.getSizeInBits()-1,
5415 TLI.getShiftAmountTy()));
5416 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5417 AddToWorkList(Shift.Val);
5418 AddToWorkList(Add.Val);
5419 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5427 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5428 SDOperand DAGCombiner::SimplifySetCC(MVT VT, SDOperand N0,
5429 SDOperand N1, ISD::CondCode Cond,
5430 bool foldBooleans) {
5431 TargetLowering::DAGCombinerInfo
5432 DagCombineInfo(DAG, !AfterLegalize, false, this);
5433 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5436 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5437 /// return a DAG expression to select that will generate the same value by
5438 /// multiplying by a magic number. See:
5439 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5440 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5441 std::vector<SDNode*> Built;
5442 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5444 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5450 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5451 /// return a DAG expression to select that will generate the same value by
5452 /// multiplying by a magic number. See:
5453 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5454 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5455 std::vector<SDNode*> Built;
5456 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5458 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5464 /// FindBaseOffset - Return true if base is known not to alias with anything
5465 /// but itself. Provides base object and offset as results.
5466 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5467 // Assume it is a primitive operation.
5468 Base = Ptr; Offset = 0;
5470 // If it's an adding a simple constant then integrate the offset.
5471 if (Base.getOpcode() == ISD::ADD) {
5472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5473 Base = Base.getOperand(0);
5474 Offset += C->getValue();
5478 // If it's any of the following then it can't alias with anything but itself.
5479 return isa<FrameIndexSDNode>(Base) ||
5480 isa<ConstantPoolSDNode>(Base) ||
5481 isa<GlobalAddressSDNode>(Base);
5484 /// isAlias - Return true if there is any possibility that the two addresses
5486 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5487 const Value *SrcValue1, int SrcValueOffset1,
5488 SDOperand Ptr2, int64_t Size2,
5489 const Value *SrcValue2, int SrcValueOffset2)
5491 // If they are the same then they must be aliases.
5492 if (Ptr1 == Ptr2) return true;
5494 // Gather base node and offset information.
5495 SDOperand Base1, Base2;
5496 int64_t Offset1, Offset2;
5497 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5498 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5500 // If they have a same base address then...
5501 if (Base1 == Base2) {
5502 // Check to see if the addresses overlap.
5503 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5506 // If we know both bases then they can't alias.
5507 if (KnownBase1 && KnownBase2) return false;
5509 if (CombinerGlobalAA) {
5510 // Use alias analysis information.
5511 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5512 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5513 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
5514 AliasAnalysis::AliasResult AAResult =
5515 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5516 if (AAResult == AliasAnalysis::NoAlias)
5520 // Otherwise we have to assume they alias.
5524 /// FindAliasInfo - Extracts the relevant alias information from the memory
5525 /// node. Returns true if the operand was a load.
5526 bool DAGCombiner::FindAliasInfo(SDNode *N,
5527 SDOperand &Ptr, int64_t &Size,
5528 const Value *&SrcValue, int &SrcValueOffset) {
5529 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5530 Ptr = LD->getBasePtr();
5531 Size = LD->getMemoryVT().getSizeInBits() >> 3;
5532 SrcValue = LD->getSrcValue();
5533 SrcValueOffset = LD->getSrcValueOffset();
5535 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5536 Ptr = ST->getBasePtr();
5537 Size = ST->getMemoryVT().getSizeInBits() >> 3;
5538 SrcValue = ST->getSrcValue();
5539 SrcValueOffset = ST->getSrcValueOffset();
5541 assert(0 && "FindAliasInfo expected a memory operand");
5547 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5548 /// looking for aliasing nodes and adding them to the Aliases vector.
5549 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5550 SmallVector<SDOperand, 8> &Aliases) {
5551 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5552 std::set<SDNode *> Visited; // Visited node set.
5554 // Get alias information for node.
5557 const Value *SrcValue;
5559 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5562 Chains.push_back(OriginalChain);
5564 // Look at each chain and determine if it is an alias. If so, add it to the
5565 // aliases list. If not, then continue up the chain looking for the next
5567 while (!Chains.empty()) {
5568 SDOperand Chain = Chains.back();
5571 // Don't bother if we've been before.
5572 if (Visited.find(Chain.Val) != Visited.end()) continue;
5573 Visited.insert(Chain.Val);
5575 switch (Chain.getOpcode()) {
5576 case ISD::EntryToken:
5577 // Entry token is ideal chain operand, but handled in FindBetterChain.
5582 // Get alias information for Chain.
5585 const Value *OpSrcValue;
5586 int OpSrcValueOffset;
5587 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5588 OpSrcValue, OpSrcValueOffset);
5590 // If chain is alias then stop here.
5591 if (!(IsLoad && IsOpLoad) &&
5592 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5593 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5594 Aliases.push_back(Chain);
5596 // Look further up the chain.
5597 Chains.push_back(Chain.getOperand(0));
5598 // Clean up old chain.
5599 AddToWorkList(Chain.Val);
5604 case ISD::TokenFactor:
5605 // We have to check each of the operands of the token factor, so we queue
5606 // then up. Adding the operands to the queue (stack) in reverse order
5607 // maintains the original order and increases the likelihood that getNode
5608 // will find a matching token factor (CSE.)
5609 for (unsigned n = Chain.getNumOperands(); n;)
5610 Chains.push_back(Chain.getOperand(--n));
5611 // Eliminate the token factor if we can.
5612 AddToWorkList(Chain.Val);
5616 // For all other instructions we will just have to take what we can get.
5617 Aliases.push_back(Chain);
5623 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5624 /// for a better chain (aliasing node.)
5625 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5626 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5628 // Accumulate all the aliases to this node.
5629 GatherAllAliases(N, OldChain, Aliases);
5631 if (Aliases.size() == 0) {
5632 // If no operands then chain to entry token.
5633 return DAG.getEntryNode();
5634 } else if (Aliases.size() == 1) {
5635 // If a single operand then chain to it. We don't need to revisit it.
5639 // Construct a custom tailored token factor.
5640 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5641 &Aliases[0], Aliases.size());
5643 // Make sure the old chain gets cleaned up.
5644 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5649 // SelectionDAG::Combine - This is the entry point for the file.
5651 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5652 /// run - This is the main entry point to this class.
5654 DAGCombiner(*this, AA).Run(RunningAfterLegalize);