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");
42 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
43 cl::desc("Pop up a window to show dags before the first "
46 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
47 cl::desc("Pop up a window to show dags before the second "
50 static const bool ViewDAGCombine1 = false;
51 static const bool ViewDAGCombine2 = false;
55 CombinerAA("combiner-alias-analysis", cl::Hidden,
56 cl::desc("Turn on alias analysis during testing"));
59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60 cl::desc("Include global information in alias analysis"));
62 //------------------------------ DAGCombiner ---------------------------------//
64 class VISIBILITY_HIDDEN DAGCombiner {
69 // Worklist of all of the nodes that need to be simplified.
70 std::vector<SDNode*> WorkList;
72 // AA - Used for DAG load/store alias analysis.
75 /// AddUsersToWorkList - When an instruction is simplified, add all users of
76 /// the instruction to the work lists because they might get more simplified
79 void AddUsersToWorkList(SDNode *N) {
80 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
82 AddToWorkList(UI->getUser());
85 /// visit - call the node-specific routine that knows how to fold each
86 /// particular type of node.
87 SDOperand visit(SDNode *N);
90 /// AddToWorkList - Add to the work list making sure it's instance is at the
91 /// the back (next to be processed.)
92 void AddToWorkList(SDNode *N) {
93 removeFromWorkList(N);
94 WorkList.push_back(N);
97 /// removeFromWorkList - remove all instances of N from the worklist.
99 void removeFromWorkList(SDNode *N) {
100 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
104 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
107 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
108 return CombineTo(N, &Res, 1, AddTo);
111 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
113 SDOperand To[] = { Res0, Res1 };
114 return CombineTo(N, To, 2, AddTo);
119 /// SimplifyDemandedBits - Check the specified integer node value to see if
120 /// it can be simplified or if things it uses can be simplified by bit
121 /// propagation. If so, return true.
122 bool SimplifyDemandedBits(SDOperand Op) {
123 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
124 return SimplifyDemandedBits(Op, Demanded);
127 bool SimplifyDemandedBits(SDOperand Op, const APInt &Demanded);
129 bool CombineToPreIndexedLoadStore(SDNode *N);
130 bool CombineToPostIndexedLoadStore(SDNode *N);
133 /// combine - call the node-specific routine that knows how to fold each
134 /// particular type of node. If that doesn't do anything, try the
135 /// target-specific DAG combines.
136 SDOperand combine(SDNode *N);
138 // Visitation implementation - Implement dag node combining for different
139 // node types. The semantics are as follows:
141 // SDOperand.Val == 0 - No change was made
142 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
143 // otherwise - N should be replaced by the returned Operand.
145 SDOperand visitTokenFactor(SDNode *N);
146 SDOperand visitMERGE_VALUES(SDNode *N);
147 SDOperand visitADD(SDNode *N);
148 SDOperand visitSUB(SDNode *N);
149 SDOperand visitADDC(SDNode *N);
150 SDOperand visitADDE(SDNode *N);
151 SDOperand visitMUL(SDNode *N);
152 SDOperand visitSDIV(SDNode *N);
153 SDOperand visitUDIV(SDNode *N);
154 SDOperand visitSREM(SDNode *N);
155 SDOperand visitUREM(SDNode *N);
156 SDOperand visitMULHU(SDNode *N);
157 SDOperand visitMULHS(SDNode *N);
158 SDOperand visitSMUL_LOHI(SDNode *N);
159 SDOperand visitUMUL_LOHI(SDNode *N);
160 SDOperand visitSDIVREM(SDNode *N);
161 SDOperand visitUDIVREM(SDNode *N);
162 SDOperand visitAND(SDNode *N);
163 SDOperand visitOR(SDNode *N);
164 SDOperand visitXOR(SDNode *N);
165 SDOperand SimplifyVBinOp(SDNode *N);
166 SDOperand visitSHL(SDNode *N);
167 SDOperand visitSRA(SDNode *N);
168 SDOperand visitSRL(SDNode *N);
169 SDOperand visitCTLZ(SDNode *N);
170 SDOperand visitCTTZ(SDNode *N);
171 SDOperand visitCTPOP(SDNode *N);
172 SDOperand visitSELECT(SDNode *N);
173 SDOperand visitSELECT_CC(SDNode *N);
174 SDOperand visitSETCC(SDNode *N);
175 SDOperand visitSIGN_EXTEND(SDNode *N);
176 SDOperand visitZERO_EXTEND(SDNode *N);
177 SDOperand visitANY_EXTEND(SDNode *N);
178 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
179 SDOperand visitTRUNCATE(SDNode *N);
180 SDOperand visitBIT_CONVERT(SDNode *N);
181 SDOperand visitBUILD_PAIR(SDNode *N);
182 SDOperand visitFADD(SDNode *N);
183 SDOperand visitFSUB(SDNode *N);
184 SDOperand visitFMUL(SDNode *N);
185 SDOperand visitFDIV(SDNode *N);
186 SDOperand visitFREM(SDNode *N);
187 SDOperand visitFCOPYSIGN(SDNode *N);
188 SDOperand visitSINT_TO_FP(SDNode *N);
189 SDOperand visitUINT_TO_FP(SDNode *N);
190 SDOperand visitFP_TO_SINT(SDNode *N);
191 SDOperand visitFP_TO_UINT(SDNode *N);
192 SDOperand visitFP_ROUND(SDNode *N);
193 SDOperand visitFP_ROUND_INREG(SDNode *N);
194 SDOperand visitFP_EXTEND(SDNode *N);
195 SDOperand visitFNEG(SDNode *N);
196 SDOperand visitFABS(SDNode *N);
197 SDOperand visitBRCOND(SDNode *N);
198 SDOperand visitBR_CC(SDNode *N);
199 SDOperand visitLOAD(SDNode *N);
200 SDOperand visitSTORE(SDNode *N);
201 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
202 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
203 SDOperand visitBUILD_VECTOR(SDNode *N);
204 SDOperand visitCONCAT_VECTORS(SDNode *N);
205 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
207 SDOperand XformToShuffleWithZero(SDNode *N);
208 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
210 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
212 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
213 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
214 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
215 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
216 SDOperand N3, ISD::CondCode CC,
217 bool NotExtCompare = false);
218 SDOperand SimplifySetCC(MVT VT, SDOperand N0, SDOperand N1,
219 ISD::CondCode Cond, bool foldBooleans = true);
220 SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
222 SDOperand CombineConsecutiveLoads(SDNode *N, MVT VT);
223 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT);
224 SDOperand BuildSDIV(SDNode *N);
225 SDOperand BuildUDIV(SDNode *N);
226 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
227 SDOperand ReduceLoadWidth(SDNode *N);
229 SDOperand GetDemandedBits(SDOperand V, const APInt &Mask);
231 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
232 /// looking for aliasing nodes and adding them to the Aliases vector.
233 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
234 SmallVector<SDOperand, 8> &Aliases);
236 /// isAlias - Return true if there is any possibility that the two addresses
238 bool isAlias(SDOperand Ptr1, int64_t Size1,
239 const Value *SrcValue1, int SrcValueOffset1,
240 SDOperand Ptr2, int64_t Size2,
241 const Value *SrcValue2, int SrcValueOffset2);
243 /// FindAliasInfo - Extracts the relevant alias information from the memory
244 /// node. Returns true if the operand was a load.
245 bool FindAliasInfo(SDNode *N,
246 SDOperand &Ptr, int64_t &Size,
247 const Value *&SrcValue, int &SrcValueOffset);
249 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
250 /// looking for a better chain (aliasing node.)
251 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
254 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
256 TLI(D.getTargetLoweringInfo()),
257 AfterLegalize(false),
260 /// Run - runs the dag combiner on all nodes in the work list
261 void Run(bool RunningAfterLegalize);
267 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
268 /// nodes from the worklist.
269 class VISIBILITY_HIDDEN WorkListRemover :
270 public SelectionDAG::DAGUpdateListener {
273 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
275 virtual void NodeDeleted(SDNode *N, SDNode *E) {
276 DC.removeFromWorkList(N);
279 virtual void NodeUpdated(SDNode *N) {
285 //===----------------------------------------------------------------------===//
286 // TargetLowering::DAGCombinerInfo implementation
287 //===----------------------------------------------------------------------===//
289 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
290 ((DAGCombiner*)DC)->AddToWorkList(N);
293 SDOperand TargetLowering::DAGCombinerInfo::
294 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
295 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
298 SDOperand TargetLowering::DAGCombinerInfo::
299 CombineTo(SDNode *N, SDOperand Res) {
300 return ((DAGCombiner*)DC)->CombineTo(N, Res);
304 SDOperand TargetLowering::DAGCombinerInfo::
305 CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
306 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
310 //===----------------------------------------------------------------------===//
312 //===----------------------------------------------------------------------===//
314 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
315 /// specified expression for the same cost as the expression itself, or 2 if we
316 /// can compute the negated form more cheaply than the expression itself.
317 static char isNegatibleForFree(SDOperand Op, bool AfterLegalize,
318 unsigned Depth = 0) {
319 // No compile time optimizations on this type.
320 if (Op.getValueType() == MVT::ppcf128)
323 // fneg is removable even if it has multiple uses.
324 if (Op.getOpcode() == ISD::FNEG) return 2;
326 // Don't allow anything with multiple uses.
327 if (!Op.hasOneUse()) return 0;
329 // Don't recurse exponentially.
330 if (Depth > 6) return 0;
332 switch (Op.getOpcode()) {
333 default: return false;
334 case ISD::ConstantFP:
335 // Don't invert constant FP values after legalize. The negated constant
336 // isn't necessarily legal.
337 return AfterLegalize ? 0 : 1;
339 // FIXME: determine better conditions for this xform.
340 if (!UnsafeFPMath) return 0;
343 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
346 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
348 // We can't turn -(A-B) into B-A when we honor signed zeros.
349 if (!UnsafeFPMath) return 0;
356 if (HonorSignDependentRoundingFPMath()) return 0;
358 // -(X*Y) -> (-X * Y) or (X*-Y)
359 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
362 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
367 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
371 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
372 /// returns the newly negated expression.
373 static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
374 bool AfterLegalize, unsigned Depth = 0) {
375 // fneg is removable even if it has multiple uses.
376 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
378 // Don't allow anything with multiple uses.
379 assert(Op.hasOneUse() && "Unknown reuse!");
381 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
382 switch (Op.getOpcode()) {
383 default: assert(0 && "Unknown code");
384 case ISD::ConstantFP: {
385 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
387 return DAG.getConstantFP(V, Op.getValueType());
390 // FIXME: determine better conditions for this xform.
391 assert(UnsafeFPMath);
394 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
395 return DAG.getNode(ISD::FSUB, Op.getValueType(),
396 GetNegatedExpression(Op.getOperand(0), DAG,
397 AfterLegalize, Depth+1),
400 return DAG.getNode(ISD::FSUB, Op.getValueType(),
401 GetNegatedExpression(Op.getOperand(1), DAG,
402 AfterLegalize, Depth+1),
405 // We can't turn -(A-B) into B-A when we honor signed zeros.
406 assert(UnsafeFPMath);
409 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
410 if (N0CFP->getValueAPF().isZero())
411 return Op.getOperand(1);
414 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
419 assert(!HonorSignDependentRoundingFPMath());
422 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
423 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
424 GetNegatedExpression(Op.getOperand(0), DAG,
425 AfterLegalize, Depth+1),
429 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
431 GetNegatedExpression(Op.getOperand(1), DAG,
432 AfterLegalize, Depth+1));
436 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
437 GetNegatedExpression(Op.getOperand(0), DAG,
438 AfterLegalize, Depth+1));
440 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
441 GetNegatedExpression(Op.getOperand(0), DAG,
442 AfterLegalize, Depth+1),
448 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
449 // that selects between the values 1 and 0, making it equivalent to a setcc.
450 // Also, set the incoming LHS, RHS, and CC references to the appropriate
451 // nodes based on the type of node we are checking. This simplifies life a
452 // bit for the callers.
453 static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
455 if (N.getOpcode() == ISD::SETCC) {
456 LHS = N.getOperand(0);
457 RHS = N.getOperand(1);
458 CC = N.getOperand(2);
461 if (N.getOpcode() == ISD::SELECT_CC &&
462 N.getOperand(2).getOpcode() == ISD::Constant &&
463 N.getOperand(3).getOpcode() == ISD::Constant &&
464 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
465 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
466 LHS = N.getOperand(0);
467 RHS = N.getOperand(1);
468 CC = N.getOperand(4);
474 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
475 // one use. If this is true, it allows the users to invert the operation for
476 // free when it is profitable to do so.
477 static bool isOneUseSetCC(SDOperand N) {
478 SDOperand N0, N1, N2;
479 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
484 SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
485 MVT VT = N0.getValueType();
486 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
487 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
488 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
489 if (isa<ConstantSDNode>(N1)) {
490 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
491 AddToWorkList(OpNode.Val);
492 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
493 } else if (N0.hasOneUse()) {
494 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
495 AddToWorkList(OpNode.Val);
496 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
499 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
500 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
501 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
502 if (isa<ConstantSDNode>(N0)) {
503 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
504 AddToWorkList(OpNode.Val);
505 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
506 } else if (N1.hasOneUse()) {
507 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
508 AddToWorkList(OpNode.Val);
509 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
515 SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
517 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
519 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
520 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
521 DOUT << " and " << NumTo-1 << " other values\n";
522 WorkListRemover DeadNodes(*this);
523 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
526 // Push the new nodes and any users onto the worklist
527 for (unsigned i = 0, e = NumTo; i != e; ++i) {
528 AddToWorkList(To[i].Val);
529 AddUsersToWorkList(To[i].Val);
533 // Nodes can be reintroduced into the worklist. Make sure we do not
534 // process a node that has been replaced.
535 removeFromWorkList(N);
537 // Finally, since the node is now dead, remove it from the graph.
539 return SDOperand(N, 0);
542 /// SimplifyDemandedBits - Check the specified integer node value to see if
543 /// it can be simplified or if things it uses can be simplified by bit
544 /// propagation. If so, return true.
545 bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, const APInt &Demanded) {
546 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
547 APInt KnownZero, KnownOne;
548 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
552 AddToWorkList(Op.Val);
554 // Replace the old value with the new one.
556 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
557 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
560 // Replace all uses. If any nodes become isomorphic to other nodes and
561 // are deleted, make sure to remove them from our worklist.
562 WorkListRemover DeadNodes(*this);
563 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
565 // Push the new node and any (possibly new) users onto the worklist.
566 AddToWorkList(TLO.New.Val);
567 AddUsersToWorkList(TLO.New.Val);
569 // Finally, if the node is now dead, remove it from the graph. The node
570 // may not be dead if the replacement process recursively simplified to
571 // something else needing this node.
572 if (TLO.Old.Val->use_empty()) {
573 removeFromWorkList(TLO.Old.Val);
575 // If the operands of this node are only used by the node, they will now
576 // be dead. Make sure to visit them first to delete dead nodes early.
577 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
578 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
579 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
581 DAG.DeleteNode(TLO.Old.Val);
586 //===----------------------------------------------------------------------===//
587 // Main DAG Combiner implementation
588 //===----------------------------------------------------------------------===//
590 void DAGCombiner::Run(bool RunningAfterLegalize) {
591 // set the instance variable, so that the various visit routines may use it.
592 AfterLegalize = RunningAfterLegalize;
594 // Add all the dag nodes to the worklist.
595 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
596 E = DAG.allnodes_end(); I != E; ++I)
597 WorkList.push_back(I);
599 // Create a dummy node (which is not added to allnodes), that adds a reference
600 // to the root node, preventing it from being deleted, and tracking any
601 // changes of the root.
602 HandleSDNode Dummy(DAG.getRoot());
604 // The root of the dag may dangle to deleted nodes until the dag combiner is
605 // done. Set it to null to avoid confusion.
606 DAG.setRoot(SDOperand());
608 // while the worklist isn't empty, inspect the node on the end of it and
609 // try and combine it.
610 while (!WorkList.empty()) {
611 SDNode *N = WorkList.back();
614 // If N has no uses, it is dead. Make sure to revisit all N's operands once
615 // N is deleted from the DAG, since they too may now be dead or may have a
616 // reduced number of uses, allowing other xforms.
617 if (N->use_empty() && N != &Dummy) {
618 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
619 AddToWorkList(N->getOperand(i).Val);
625 SDOperand RV = combine(N);
632 // If we get back the same node we passed in, rather than a new node or
633 // zero, we know that the node must have defined multiple values and
634 // CombineTo was used. Since CombineTo takes care of the worklist
635 // mechanics for us, we have no work to do in this case.
639 assert(N->getOpcode() != ISD::DELETED_NODE &&
640 RV.Val->getOpcode() != ISD::DELETED_NODE &&
641 "Node was deleted but visit returned new node!");
643 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
644 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
646 WorkListRemover DeadNodes(*this);
647 if (N->getNumValues() == RV.Val->getNumValues())
648 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
650 assert(N->getValueType(0) == RV.getValueType() &&
651 N->getNumValues() == 1 && "Type mismatch");
653 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
656 // Push the new node and any users onto the worklist
657 AddToWorkList(RV.Val);
658 AddUsersToWorkList(RV.Val);
660 // Add any uses of the old node to the worklist in case this node is the
661 // last one that uses them. They may become dead after this node is
663 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
664 AddToWorkList(N->getOperand(i).Val);
666 // Nodes can be reintroduced into the worklist. Make sure we do not
667 // process a node that has been replaced.
668 removeFromWorkList(N);
670 // Finally, since the node is now dead, remove it from the graph.
674 // If the root changed (e.g. it was a dead load, update the root).
675 DAG.setRoot(Dummy.getValue());
678 SDOperand DAGCombiner::visit(SDNode *N) {
679 switch(N->getOpcode()) {
681 case ISD::TokenFactor: return visitTokenFactor(N);
682 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
683 case ISD::ADD: return visitADD(N);
684 case ISD::SUB: return visitSUB(N);
685 case ISD::ADDC: return visitADDC(N);
686 case ISD::ADDE: return visitADDE(N);
687 case ISD::MUL: return visitMUL(N);
688 case ISD::SDIV: return visitSDIV(N);
689 case ISD::UDIV: return visitUDIV(N);
690 case ISD::SREM: return visitSREM(N);
691 case ISD::UREM: return visitUREM(N);
692 case ISD::MULHU: return visitMULHU(N);
693 case ISD::MULHS: return visitMULHS(N);
694 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
695 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
696 case ISD::SDIVREM: return visitSDIVREM(N);
697 case ISD::UDIVREM: return visitUDIVREM(N);
698 case ISD::AND: return visitAND(N);
699 case ISD::OR: return visitOR(N);
700 case ISD::XOR: return visitXOR(N);
701 case ISD::SHL: return visitSHL(N);
702 case ISD::SRA: return visitSRA(N);
703 case ISD::SRL: return visitSRL(N);
704 case ISD::CTLZ: return visitCTLZ(N);
705 case ISD::CTTZ: return visitCTTZ(N);
706 case ISD::CTPOP: return visitCTPOP(N);
707 case ISD::SELECT: return visitSELECT(N);
708 case ISD::SELECT_CC: return visitSELECT_CC(N);
709 case ISD::SETCC: return visitSETCC(N);
710 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
711 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
712 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
713 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
714 case ISD::TRUNCATE: return visitTRUNCATE(N);
715 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
716 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
717 case ISD::FADD: return visitFADD(N);
718 case ISD::FSUB: return visitFSUB(N);
719 case ISD::FMUL: return visitFMUL(N);
720 case ISD::FDIV: return visitFDIV(N);
721 case ISD::FREM: return visitFREM(N);
722 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
723 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
724 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
725 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
726 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
727 case ISD::FP_ROUND: return visitFP_ROUND(N);
728 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
729 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
730 case ISD::FNEG: return visitFNEG(N);
731 case ISD::FABS: return visitFABS(N);
732 case ISD::BRCOND: return visitBRCOND(N);
733 case ISD::BR_CC: return visitBR_CC(N);
734 case ISD::LOAD: return visitLOAD(N);
735 case ISD::STORE: return visitSTORE(N);
736 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
737 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
738 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
739 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
740 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
745 SDOperand DAGCombiner::combine(SDNode *N) {
747 SDOperand RV = visit(N);
749 // If nothing happened, try a target-specific DAG combine.
751 assert(N->getOpcode() != ISD::DELETED_NODE &&
752 "Node was deleted but visit returned NULL!");
754 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
755 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
757 // Expose the DAG combiner to the target combiner impls.
758 TargetLowering::DAGCombinerInfo
759 DagCombineInfo(DAG, !AfterLegalize, false, this);
761 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
765 // If N is a commutative binary node, try commuting it to enable more
768 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
769 N->getNumValues() == 1) {
770 SDOperand N0 = N->getOperand(0);
771 SDOperand N1 = N->getOperand(1);
772 // Constant operands are canonicalized to RHS.
773 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
774 SDOperand Ops[] = { N1, N0 };
775 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
778 return SDOperand(CSENode, 0);
785 /// getInputChainForNode - Given a node, return its input chain if it has one,
786 /// otherwise return a null sd operand.
787 static SDOperand getInputChainForNode(SDNode *N) {
788 if (unsigned NumOps = N->getNumOperands()) {
789 if (N->getOperand(0).getValueType() == MVT::Other)
790 return N->getOperand(0);
791 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
792 return N->getOperand(NumOps-1);
793 for (unsigned i = 1; i < NumOps-1; ++i)
794 if (N->getOperand(i).getValueType() == MVT::Other)
795 return N->getOperand(i);
797 return SDOperand(0, 0);
800 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
801 // If N has two operands, where one has an input chain equal to the other,
802 // the 'other' chain is redundant.
803 if (N->getNumOperands() == 2) {
804 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
805 return N->getOperand(0);
806 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
807 return N->getOperand(1);
810 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
811 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
812 SmallPtrSet<SDNode*, 16> SeenOps;
813 bool Changed = false; // If we should replace this token factor.
815 // Start out with this token factor.
818 // Iterate through token factors. The TFs grows when new token factors are
820 for (unsigned i = 0; i < TFs.size(); ++i) {
823 // Check each of the operands.
824 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
825 SDOperand Op = TF->getOperand(i);
827 switch (Op.getOpcode()) {
828 case ISD::EntryToken:
829 // Entry tokens don't need to be added to the list. They are
834 case ISD::TokenFactor:
835 if ((CombinerAA || Op.hasOneUse()) &&
836 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
837 // Queue up for processing.
838 TFs.push_back(Op.Val);
839 // Clean up in case the token factor is removed.
840 AddToWorkList(Op.Val);
847 // Only add if it isn't already in the list.
848 if (SeenOps.insert(Op.Val))
859 // If we've change things around then replace token factor.
862 // The entry token is the only possible outcome.
863 Result = DAG.getEntryNode();
865 // New and improved token factor.
866 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
869 // Don't add users to work list.
870 return CombineTo(N, Result, false);
876 /// MERGE_VALUES can always be eliminated.
877 SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
878 WorkListRemover DeadNodes(*this);
879 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
880 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
882 removeFromWorkList(N);
884 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
889 SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
890 MVT VT = N0.getValueType();
891 SDOperand N00 = N0.getOperand(0);
892 SDOperand N01 = N0.getOperand(1);
893 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
894 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
895 isa<ConstantSDNode>(N00.getOperand(1))) {
896 N0 = DAG.getNode(ISD::ADD, VT,
897 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
898 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
899 return DAG.getNode(ISD::ADD, VT, N0, N1);
905 SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
907 MVT VT = N->getValueType(0);
908 unsigned Opc = N->getOpcode();
909 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
910 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
911 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
912 ISD::CondCode CC = ISD::SETCC_INVALID;
914 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
916 SDOperand CCOp = Slct.getOperand(0);
917 if (CCOp.getOpcode() == ISD::SETCC)
918 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
921 bool DoXform = false;
923 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
925 if (LHS.getOpcode() == ISD::Constant &&
926 cast<ConstantSDNode>(LHS)->isNullValue())
928 else if (CC != ISD::SETCC_INVALID &&
929 RHS.getOpcode() == ISD::Constant &&
930 cast<ConstantSDNode>(RHS)->isNullValue()) {
932 SDOperand Op0 = Slct.getOperand(0);
933 bool isInt = (isSlctCC ? Op0.getValueType() :
934 Op0.getOperand(0).getValueType()).isInteger();
935 CC = ISD::getSetCCInverse(CC, isInt);
941 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
943 return DAG.getSelectCC(OtherOp, Result,
944 Slct.getOperand(0), Slct.getOperand(1), CC);
945 SDOperand CCOp = Slct.getOperand(0);
947 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
948 CCOp.getOperand(1), CC);
949 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
954 SDOperand DAGCombiner::visitADD(SDNode *N) {
955 SDOperand N0 = N->getOperand(0);
956 SDOperand N1 = N->getOperand(1);
957 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
958 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
959 MVT VT = N0.getValueType();
963 SDOperand FoldedVOp = SimplifyVBinOp(N);
964 if (FoldedVOp.Val) return FoldedVOp;
967 // fold (add x, undef) -> undef
968 if (N0.getOpcode() == ISD::UNDEF)
970 if (N1.getOpcode() == ISD::UNDEF)
972 // fold (add c1, c2) -> c1+c2
974 return DAG.getConstant(N0C->getAPIntValue() + N1C->getAPIntValue(), VT);
975 // canonicalize constant to RHS
977 return DAG.getNode(ISD::ADD, VT, N1, N0);
978 // fold (add x, 0) -> x
979 if (N1C && N1C->isNullValue())
981 // fold ((c1-A)+c2) -> (c1+c2)-A
982 if (N1C && N0.getOpcode() == ISD::SUB)
983 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
984 return DAG.getNode(ISD::SUB, VT,
985 DAG.getConstant(N1C->getAPIntValue()+
986 N0C->getAPIntValue(), VT),
989 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
992 // fold ((0-A) + B) -> B-A
993 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
994 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
995 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
996 // fold (A + (0-B)) -> A-B
997 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
998 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
999 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
1000 // fold (A+(B-A)) -> B
1001 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1002 return N1.getOperand(0);
1004 if (!VT.isVector() && SimplifyDemandedBits(SDOperand(N, 0)))
1005 return SDOperand(N, 0);
1007 // fold (a+b) -> (a|b) iff a and b share no bits.
1008 if (VT.isInteger() && !VT.isVector()) {
1009 APInt LHSZero, LHSOne;
1010 APInt RHSZero, RHSOne;
1011 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1012 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1013 if (LHSZero.getBoolValue()) {
1014 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1016 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1017 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1018 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1019 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1020 return DAG.getNode(ISD::OR, VT, N0, N1);
1024 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1025 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
1026 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
1027 if (Result.Val) return Result;
1029 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
1030 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
1031 if (Result.Val) return Result;
1034 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1035 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
1036 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
1037 if (Result.Val) return Result;
1039 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1040 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1041 if (Result.Val) return Result;
1047 SDOperand DAGCombiner::visitADDC(SDNode *N) {
1048 SDOperand N0 = N->getOperand(0);
1049 SDOperand N1 = N->getOperand(1);
1050 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1051 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1052 MVT VT = N0.getValueType();
1054 // If the flag result is dead, turn this into an ADD.
1055 if (N->hasNUsesOfValue(0, 1))
1056 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1057 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1059 // canonicalize constant to RHS.
1061 SDOperand Ops[] = { N1, N0 };
1062 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1065 // fold (addc x, 0) -> x + no carry out
1066 if (N1C && N1C->isNullValue())
1067 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1069 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1070 APInt LHSZero, LHSOne;
1071 APInt RHSZero, RHSOne;
1072 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1073 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1074 if (LHSZero.getBoolValue()) {
1075 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1077 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1078 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1079 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1080 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1081 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1082 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1088 SDOperand DAGCombiner::visitADDE(SDNode *N) {
1089 SDOperand N0 = N->getOperand(0);
1090 SDOperand N1 = N->getOperand(1);
1091 SDOperand CarryIn = N->getOperand(2);
1092 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1093 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1094 //MVT VT = N0.getValueType();
1096 // canonicalize constant to RHS
1098 SDOperand Ops[] = { N1, N0, CarryIn };
1099 return DAG.getNode(ISD::ADDE, N->getVTList(), Ops, 3);
1102 // fold (adde x, y, false) -> (addc x, y)
1103 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
1104 SDOperand Ops[] = { N1, N0 };
1105 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1113 SDOperand DAGCombiner::visitSUB(SDNode *N) {
1114 SDOperand N0 = N->getOperand(0);
1115 SDOperand N1 = N->getOperand(1);
1116 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1117 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1118 MVT VT = N0.getValueType();
1121 if (VT.isVector()) {
1122 SDOperand FoldedVOp = SimplifyVBinOp(N);
1123 if (FoldedVOp.Val) return FoldedVOp;
1126 // fold (sub x, x) -> 0
1128 return DAG.getConstant(0, N->getValueType(0));
1129 // fold (sub c1, c2) -> c1-c2
1131 return DAG.getNode(ISD::SUB, VT, N0, N1);
1132 // fold (sub x, c) -> (add x, -c)
1134 return DAG.getNode(ISD::ADD, VT, N0,
1135 DAG.getConstant(-N1C->getAPIntValue(), VT));
1136 // fold (A+B)-A -> B
1137 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1138 return N0.getOperand(1);
1139 // fold (A+B)-B -> A
1140 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1141 return N0.getOperand(0);
1142 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1143 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1144 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1145 if (Result.Val) return Result;
1147 // If either operand of a sub is undef, the result is undef
1148 if (N0.getOpcode() == ISD::UNDEF)
1150 if (N1.getOpcode() == ISD::UNDEF)
1156 SDOperand DAGCombiner::visitMUL(SDNode *N) {
1157 SDOperand N0 = N->getOperand(0);
1158 SDOperand N1 = N->getOperand(1);
1159 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1160 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1161 MVT VT = N0.getValueType();
1164 if (VT.isVector()) {
1165 SDOperand FoldedVOp = SimplifyVBinOp(N);
1166 if (FoldedVOp.Val) return FoldedVOp;
1169 // fold (mul x, undef) -> 0
1170 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1171 return DAG.getConstant(0, VT);
1172 // fold (mul c1, c2) -> c1*c2
1174 return DAG.getNode(ISD::MUL, VT, N0, N1);
1175 // canonicalize constant to RHS
1177 return DAG.getNode(ISD::MUL, VT, N1, N0);
1178 // fold (mul x, 0) -> 0
1179 if (N1C && N1C->isNullValue())
1181 // fold (mul x, -1) -> 0-x
1182 if (N1C && N1C->isAllOnesValue())
1183 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1184 // fold (mul x, (1 << c)) -> x << c
1185 if (N1C && N1C->getAPIntValue().isPowerOf2())
1186 return DAG.getNode(ISD::SHL, VT, N0,
1187 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1188 TLI.getShiftAmountTy()));
1189 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1190 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1191 // FIXME: If the input is something that is easily negated (e.g. a
1192 // single-use add), we should put the negate there.
1193 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1194 DAG.getNode(ISD::SHL, VT, N0,
1195 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1196 TLI.getShiftAmountTy())));
1199 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1200 if (N1C && N0.getOpcode() == ISD::SHL &&
1201 isa<ConstantSDNode>(N0.getOperand(1))) {
1202 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1203 AddToWorkList(C3.Val);
1204 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1207 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1210 SDOperand Sh(0,0), Y(0,0);
1211 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1212 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1213 N0.Val->hasOneUse()) {
1215 } else if (N1.getOpcode() == ISD::SHL &&
1216 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1220 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1221 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1224 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1225 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1226 isa<ConstantSDNode>(N0.getOperand(1))) {
1227 return DAG.getNode(ISD::ADD, VT,
1228 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1229 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1233 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1240 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1241 SDOperand N0 = N->getOperand(0);
1242 SDOperand N1 = N->getOperand(1);
1243 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1244 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1245 MVT VT = N->getValueType(0);
1248 if (VT.isVector()) {
1249 SDOperand FoldedVOp = SimplifyVBinOp(N);
1250 if (FoldedVOp.Val) return FoldedVOp;
1253 // fold (sdiv c1, c2) -> c1/c2
1254 if (N0C && N1C && !N1C->isNullValue())
1255 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1256 // fold (sdiv X, 1) -> X
1257 if (N1C && N1C->getSignExtended() == 1LL)
1259 // fold (sdiv X, -1) -> 0-X
1260 if (N1C && N1C->isAllOnesValue())
1261 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1262 // If we know the sign bits of both operands are zero, strength reduce to a
1263 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1264 if (!VT.isVector()) {
1265 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1266 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1268 // fold (sdiv X, pow2) -> simple ops after legalize
1269 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1270 (isPowerOf2_64(N1C->getSignExtended()) ||
1271 isPowerOf2_64(-N1C->getSignExtended()))) {
1272 // If dividing by powers of two is cheap, then don't perform the following
1274 if (TLI.isPow2DivCheap())
1276 int64_t pow2 = N1C->getSignExtended();
1277 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1278 unsigned lg2 = Log2_64(abs2);
1279 // Splat the sign bit into the register
1280 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1281 DAG.getConstant(VT.getSizeInBits()-1,
1282 TLI.getShiftAmountTy()));
1283 AddToWorkList(SGN.Val);
1284 // Add (N0 < 0) ? abs2 - 1 : 0;
1285 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1286 DAG.getConstant(VT.getSizeInBits()-lg2,
1287 TLI.getShiftAmountTy()));
1288 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1289 AddToWorkList(SRL.Val);
1290 AddToWorkList(ADD.Val); // Divide by pow2
1291 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1292 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1293 // If we're dividing by a positive value, we're done. Otherwise, we must
1294 // negate the result.
1297 AddToWorkList(SRA.Val);
1298 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1300 // if integer divide is expensive and we satisfy the requirements, emit an
1301 // alternate sequence.
1302 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1303 !TLI.isIntDivCheap()) {
1304 SDOperand Op = BuildSDIV(N);
1305 if (Op.Val) return Op;
1309 if (N0.getOpcode() == ISD::UNDEF)
1310 return DAG.getConstant(0, VT);
1311 // X / undef -> undef
1312 if (N1.getOpcode() == ISD::UNDEF)
1318 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1319 SDOperand N0 = N->getOperand(0);
1320 SDOperand N1 = N->getOperand(1);
1321 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1322 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1323 MVT VT = N->getValueType(0);
1326 if (VT.isVector()) {
1327 SDOperand FoldedVOp = SimplifyVBinOp(N);
1328 if (FoldedVOp.Val) return FoldedVOp;
1331 // fold (udiv c1, c2) -> c1/c2
1332 if (N0C && N1C && !N1C->isNullValue())
1333 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1334 // fold (udiv x, (1 << c)) -> x >>u c
1335 if (N1C && N1C->getAPIntValue().isPowerOf2())
1336 return DAG.getNode(ISD::SRL, VT, N0,
1337 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1338 TLI.getShiftAmountTy()));
1339 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1340 if (N1.getOpcode() == ISD::SHL) {
1341 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1342 if (SHC->getAPIntValue().isPowerOf2()) {
1343 MVT ADDVT = N1.getOperand(1).getValueType();
1344 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1345 DAG.getConstant(SHC->getAPIntValue()
1348 AddToWorkList(Add.Val);
1349 return DAG.getNode(ISD::SRL, VT, N0, Add);
1353 // fold (udiv x, c) -> alternate
1354 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1355 SDOperand Op = BuildUDIV(N);
1356 if (Op.Val) return Op;
1360 if (N0.getOpcode() == ISD::UNDEF)
1361 return DAG.getConstant(0, VT);
1362 // X / undef -> undef
1363 if (N1.getOpcode() == ISD::UNDEF)
1369 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1370 SDOperand N0 = N->getOperand(0);
1371 SDOperand N1 = N->getOperand(1);
1372 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1373 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1374 MVT VT = N->getValueType(0);
1376 // fold (srem c1, c2) -> c1%c2
1377 if (N0C && N1C && !N1C->isNullValue())
1378 return DAG.getNode(ISD::SREM, VT, N0, N1);
1379 // If we know the sign bits of both operands are zero, strength reduce to a
1380 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1381 if (!VT.isVector()) {
1382 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1383 return DAG.getNode(ISD::UREM, VT, N0, N1);
1386 // If X/C can be simplified by the division-by-constant logic, lower
1387 // X%C to the equivalent of X-X/C*C.
1388 if (N1C && !N1C->isNullValue()) {
1389 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1390 AddToWorkList(Div.Val);
1391 SDOperand OptimizedDiv = combine(Div.Val);
1392 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1393 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1394 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1395 AddToWorkList(Mul.Val);
1401 if (N0.getOpcode() == ISD::UNDEF)
1402 return DAG.getConstant(0, VT);
1403 // X % undef -> undef
1404 if (N1.getOpcode() == ISD::UNDEF)
1410 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1411 SDOperand N0 = N->getOperand(0);
1412 SDOperand N1 = N->getOperand(1);
1413 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1414 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1415 MVT VT = N->getValueType(0);
1417 // fold (urem c1, c2) -> c1%c2
1418 if (N0C && N1C && !N1C->isNullValue())
1419 return DAG.getNode(ISD::UREM, VT, N0, N1);
1420 // fold (urem x, pow2) -> (and x, pow2-1)
1421 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1422 return DAG.getNode(ISD::AND, VT, N0,
1423 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1424 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1425 if (N1.getOpcode() == ISD::SHL) {
1426 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1427 if (SHC->getAPIntValue().isPowerOf2()) {
1429 DAG.getNode(ISD::ADD, VT, N1,
1430 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1432 AddToWorkList(Add.Val);
1433 return DAG.getNode(ISD::AND, VT, N0, Add);
1438 // If X/C can be simplified by the division-by-constant logic, lower
1439 // X%C to the equivalent of X-X/C*C.
1440 if (N1C && !N1C->isNullValue()) {
1441 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1442 SDOperand OptimizedDiv = combine(Div.Val);
1443 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1444 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1445 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1446 AddToWorkList(Mul.Val);
1452 if (N0.getOpcode() == ISD::UNDEF)
1453 return DAG.getConstant(0, VT);
1454 // X % undef -> undef
1455 if (N1.getOpcode() == ISD::UNDEF)
1461 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1462 SDOperand N0 = N->getOperand(0);
1463 SDOperand N1 = N->getOperand(1);
1464 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1465 MVT VT = N->getValueType(0);
1467 // fold (mulhs x, 0) -> 0
1468 if (N1C && N1C->isNullValue())
1470 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1471 if (N1C && N1C->getAPIntValue() == 1)
1472 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1473 DAG.getConstant(N0.getValueType().getSizeInBits()-1,
1474 TLI.getShiftAmountTy()));
1475 // fold (mulhs x, undef) -> 0
1476 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1477 return DAG.getConstant(0, VT);
1482 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1483 SDOperand N0 = N->getOperand(0);
1484 SDOperand N1 = N->getOperand(1);
1485 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1486 MVT VT = N->getValueType(0);
1488 // fold (mulhu x, 0) -> 0
1489 if (N1C && N1C->isNullValue())
1491 // fold (mulhu x, 1) -> 0
1492 if (N1C && N1C->getAPIntValue() == 1)
1493 return DAG.getConstant(0, N0.getValueType());
1494 // fold (mulhu x, undef) -> 0
1495 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1496 return DAG.getConstant(0, VT);
1501 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1502 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1503 /// that are being performed. Return true if a simplification was made.
1505 SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1507 // If the high half is not needed, just compute the low half.
1508 bool HiExists = N->hasAnyUseOfValue(1);
1511 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1512 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1513 N->getNumOperands());
1514 return CombineTo(N, Res, Res);
1517 // If the low half is not needed, just compute the high half.
1518 bool LoExists = N->hasAnyUseOfValue(0);
1521 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1522 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1523 N->getNumOperands());
1524 return CombineTo(N, Res, Res);
1527 // If both halves are used, return as it is.
1528 if (LoExists && HiExists)
1531 // If the two computed results can be simplified separately, separate them.
1533 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1534 N->op_begin(), N->getNumOperands());
1535 AddToWorkList(Lo.Val);
1536 SDOperand LoOpt = combine(Lo.Val);
1537 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
1539 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1540 return CombineTo(N, LoOpt, LoOpt);
1544 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1545 N->op_begin(), N->getNumOperands());
1546 AddToWorkList(Hi.Val);
1547 SDOperand HiOpt = combine(Hi.Val);
1548 if (HiOpt.Val && HiOpt != Hi &&
1550 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1551 return CombineTo(N, HiOpt, HiOpt);
1556 SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1557 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1558 if (Res.Val) return Res;
1563 SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1564 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1565 if (Res.Val) return Res;
1570 SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
1571 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1572 if (Res.Val) return Res;
1577 SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
1578 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1579 if (Res.Val) return Res;
1584 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1585 /// two operands of the same opcode, try to simplify it.
1586 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1587 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1588 MVT VT = N0.getValueType();
1589 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1591 // For each of OP in AND/OR/XOR:
1592 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1593 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1594 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1595 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1596 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1597 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1598 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1599 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1600 N0.getOperand(0).getValueType(),
1601 N0.getOperand(0), N1.getOperand(0));
1602 AddToWorkList(ORNode.Val);
1603 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1606 // For each of OP in SHL/SRL/SRA/AND...
1607 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1608 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1609 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1610 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1611 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1612 N0.getOperand(1) == N1.getOperand(1)) {
1613 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1614 N0.getOperand(0).getValueType(),
1615 N0.getOperand(0), N1.getOperand(0));
1616 AddToWorkList(ORNode.Val);
1617 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1623 SDOperand DAGCombiner::visitAND(SDNode *N) {
1624 SDOperand N0 = N->getOperand(0);
1625 SDOperand N1 = N->getOperand(1);
1626 SDOperand LL, LR, RL, RR, CC0, CC1;
1627 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1628 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1629 MVT VT = N1.getValueType();
1630 unsigned BitWidth = VT.getSizeInBits();
1633 if (VT.isVector()) {
1634 SDOperand FoldedVOp = SimplifyVBinOp(N);
1635 if (FoldedVOp.Val) return FoldedVOp;
1638 // fold (and x, undef) -> 0
1639 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1640 return DAG.getConstant(0, VT);
1641 // fold (and c1, c2) -> c1&c2
1643 return DAG.getNode(ISD::AND, VT, N0, N1);
1644 // canonicalize constant to RHS
1646 return DAG.getNode(ISD::AND, VT, N1, N0);
1647 // fold (and x, -1) -> x
1648 if (N1C && N1C->isAllOnesValue())
1650 // if (and x, c) is known to be zero, return 0
1651 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
1652 APInt::getAllOnesValue(BitWidth)))
1653 return DAG.getConstant(0, VT);
1655 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1658 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1659 if (N1C && N0.getOpcode() == ISD::OR)
1660 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1661 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1663 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1664 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1665 SDOperand N0Op0 = N0.getOperand(0);
1666 APInt Mask = ~N1C->getAPIntValue();
1667 Mask.trunc(N0Op0.getValueSizeInBits());
1668 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1669 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1672 // Replace uses of the AND with uses of the Zero extend node.
1675 // We actually want to replace all uses of the any_extend with the
1676 // zero_extend, to avoid duplicating things. This will later cause this
1677 // AND to be folded.
1678 CombineTo(N0.Val, Zext);
1679 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1682 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1683 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1684 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1685 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1687 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1688 LL.getValueType().isInteger()) {
1689 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1690 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1691 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1692 AddToWorkList(ORNode.Val);
1693 return DAG.getSetCC(VT, ORNode, LR, Op1);
1695 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1696 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1697 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1698 AddToWorkList(ANDNode.Val);
1699 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1701 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1702 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1703 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1704 AddToWorkList(ORNode.Val);
1705 return DAG.getSetCC(VT, ORNode, LR, Op1);
1708 // canonicalize equivalent to ll == rl
1709 if (LL == RR && LR == RL) {
1710 Op1 = ISD::getSetCCSwappedOperands(Op1);
1713 if (LL == RL && LR == RR) {
1714 bool isInteger = LL.getValueType().isInteger();
1715 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1716 if (Result != ISD::SETCC_INVALID)
1717 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1721 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1722 if (N0.getOpcode() == N1.getOpcode()) {
1723 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1724 if (Tmp.Val) return Tmp;
1727 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1728 // fold (and (sra)) -> (and (srl)) when possible.
1729 if (!VT.isVector() &&
1730 SimplifyDemandedBits(SDOperand(N, 0)))
1731 return SDOperand(N, 0);
1732 // fold (zext_inreg (extload x)) -> (zextload x)
1733 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1734 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1735 MVT EVT = LN0->getMemoryVT();
1736 // If we zero all the possible extended bits, then we can turn this into
1737 // a zextload if we are running before legalize or the operation is legal.
1738 unsigned BitWidth = N1.getValueSizeInBits();
1739 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1740 BitWidth - EVT.getSizeInBits())) &&
1741 ((!AfterLegalize && !LN0->isVolatile()) ||
1742 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1743 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1744 LN0->getBasePtr(), LN0->getSrcValue(),
1745 LN0->getSrcValueOffset(), EVT,
1747 LN0->getAlignment());
1749 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1750 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1753 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1754 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1756 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1757 MVT EVT = LN0->getMemoryVT();
1758 // If we zero all the possible extended bits, then we can turn this into
1759 // a zextload if we are running before legalize or the operation is legal.
1760 unsigned BitWidth = N1.getValueSizeInBits();
1761 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1762 BitWidth - EVT.getSizeInBits())) &&
1763 ((!AfterLegalize && !LN0->isVolatile()) ||
1764 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1765 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1766 LN0->getBasePtr(), LN0->getSrcValue(),
1767 LN0->getSrcValueOffset(), EVT,
1769 LN0->getAlignment());
1771 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1772 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1776 // fold (and (load x), 255) -> (zextload x, i8)
1777 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1778 if (N1C && N0.getOpcode() == ISD::LOAD) {
1779 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1780 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1781 LN0->isUnindexed() && N0.hasOneUse() &&
1782 // Do not change the width of a volatile load.
1783 !LN0->isVolatile()) {
1784 MVT EVT = MVT::Other;
1785 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1786 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1787 EVT = MVT::getIntegerVT(ActiveBits);
1789 MVT LoadedVT = LN0->getMemoryVT();
1790 // Do not generate loads of extended integer types since these can be
1791 // expensive (and would be wrong if the type is not byte sized).
1792 if (EVT != MVT::Other && LoadedVT.bitsGT(EVT) && EVT.isSimple() &&
1793 EVT.isByteSized() && // Exclude MVT::i1, which is simple.
1794 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1795 MVT PtrType = N0.getOperand(1).getValueType();
1796 // For big endian targets, we need to add an offset to the pointer to
1797 // load the correct bytes. For little endian systems, we merely need to
1798 // read fewer bytes from the same pointer.
1799 unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
1800 unsigned EVTStoreBytes = EVT.getStoreSizeInBits()/8;
1801 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1802 unsigned Alignment = LN0->getAlignment();
1803 SDOperand NewPtr = LN0->getBasePtr();
1804 if (TLI.isBigEndian()) {
1805 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1806 DAG.getConstant(PtrOff, PtrType));
1807 Alignment = MinAlign(Alignment, PtrOff);
1809 AddToWorkList(NewPtr.Val);
1811 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1812 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1813 LN0->isVolatile(), Alignment);
1815 CombineTo(N0.Val, Load, Load.getValue(1));
1816 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1824 SDOperand DAGCombiner::visitOR(SDNode *N) {
1825 SDOperand N0 = N->getOperand(0);
1826 SDOperand N1 = N->getOperand(1);
1827 SDOperand LL, LR, RL, RR, CC0, CC1;
1828 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1829 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1830 MVT VT = N1.getValueType();
1833 if (VT.isVector()) {
1834 SDOperand FoldedVOp = SimplifyVBinOp(N);
1835 if (FoldedVOp.Val) return FoldedVOp;
1838 // fold (or x, undef) -> -1
1839 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1840 return DAG.getConstant(~0ULL, VT);
1841 // fold (or c1, c2) -> c1|c2
1843 return DAG.getNode(ISD::OR, VT, N0, N1);
1844 // canonicalize constant to RHS
1846 return DAG.getNode(ISD::OR, VT, N1, N0);
1847 // fold (or x, 0) -> x
1848 if (N1C && N1C->isNullValue())
1850 // fold (or x, -1) -> -1
1851 if (N1C && N1C->isAllOnesValue())
1853 // fold (or x, c) -> c iff (x & ~c) == 0
1854 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1857 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1860 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1861 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1862 isa<ConstantSDNode>(N0.getOperand(1))) {
1863 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1864 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1866 DAG.getConstant(N1C->getAPIntValue() |
1867 C1->getAPIntValue(), VT));
1869 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1870 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1871 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1872 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1874 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1875 LL.getValueType().isInteger()) {
1876 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1877 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1878 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1879 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1880 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1881 AddToWorkList(ORNode.Val);
1882 return DAG.getSetCC(VT, ORNode, LR, Op1);
1884 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1885 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1886 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1887 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1888 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1889 AddToWorkList(ANDNode.Val);
1890 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1893 // canonicalize equivalent to ll == rl
1894 if (LL == RR && LR == RL) {
1895 Op1 = ISD::getSetCCSwappedOperands(Op1);
1898 if (LL == RL && LR == RR) {
1899 bool isInteger = LL.getValueType().isInteger();
1900 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1901 if (Result != ISD::SETCC_INVALID)
1902 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1906 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1907 if (N0.getOpcode() == N1.getOpcode()) {
1908 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1909 if (Tmp.Val) return Tmp;
1912 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1913 if (N0.getOpcode() == ISD::AND &&
1914 N1.getOpcode() == ISD::AND &&
1915 N0.getOperand(1).getOpcode() == ISD::Constant &&
1916 N1.getOperand(1).getOpcode() == ISD::Constant &&
1917 // Don't increase # computations.
1918 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1919 // We can only do this xform if we know that bits from X that are set in C2
1920 // but not in C1 are already zero. Likewise for Y.
1921 const APInt &LHSMask =
1922 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1923 const APInt &RHSMask =
1924 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
1926 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1927 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1928 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1929 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1934 // See if this is some rotate idiom.
1935 if (SDNode *Rot = MatchRotate(N0, N1))
1936 return SDOperand(Rot, 0);
1942 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1943 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1944 if (Op.getOpcode() == ISD::AND) {
1945 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1946 Mask = Op.getOperand(1);
1947 Op = Op.getOperand(0);
1953 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1961 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1962 // idioms for rotate, and if the target supports rotation instructions, generate
1964 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1965 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
1966 MVT VT = LHS.getValueType();
1967 if (!TLI.isTypeLegal(VT)) return 0;
1969 // The target must have at least one rotate flavor.
1970 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1971 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1972 if (!HasROTL && !HasROTR) return 0;
1974 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1975 SDOperand LHSShift; // The shift.
1976 SDOperand LHSMask; // AND value if any.
1977 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1978 return 0; // Not part of a rotate.
1980 SDOperand RHSShift; // The shift.
1981 SDOperand RHSMask; // AND value if any.
1982 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1983 return 0; // Not part of a rotate.
1985 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1986 return 0; // Not shifting the same value.
1988 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1989 return 0; // Shifts must disagree.
1991 // Canonicalize shl to left side in a shl/srl pair.
1992 if (RHSShift.getOpcode() == ISD::SHL) {
1993 std::swap(LHS, RHS);
1994 std::swap(LHSShift, RHSShift);
1995 std::swap(LHSMask , RHSMask );
1998 unsigned OpSizeInBits = VT.getSizeInBits();
1999 SDOperand LHSShiftArg = LHSShift.getOperand(0);
2000 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
2001 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
2003 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2004 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2005 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2006 RHSShiftAmt.getOpcode() == ISD::Constant) {
2007 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
2008 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
2009 if ((LShVal + RShVal) != OpSizeInBits)
2014 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
2016 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
2018 // If there is an AND of either shifted operand, apply it to the result.
2019 if (LHSMask.Val || RHSMask.Val) {
2020 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2023 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2024 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2027 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2028 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2031 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2037 // If there is a mask here, and we have a variable shift, we can't be sure
2038 // that we're masking out the right stuff.
2039 if (LHSMask.Val || RHSMask.Val)
2042 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2043 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2044 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2045 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2046 if (ConstantSDNode *SUBC =
2047 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2048 if (SUBC->getAPIntValue() == OpSizeInBits) {
2050 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2052 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2057 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2058 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2059 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2060 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2061 if (ConstantSDNode *SUBC =
2062 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2063 if (SUBC->getAPIntValue() == OpSizeInBits) {
2065 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2067 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2072 // Look for sign/zext/any-extended cases:
2073 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2074 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2075 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2076 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2077 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2078 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2079 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2080 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2081 if (RExtOp0.getOpcode() == ISD::SUB &&
2082 RExtOp0.getOperand(1) == LExtOp0) {
2083 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2085 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2086 // (rotl x, (sub 32, y))
2087 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2088 if (SUBC->getAPIntValue() == OpSizeInBits) {
2090 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2092 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2095 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2096 RExtOp0 == LExtOp0.getOperand(1)) {
2097 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2099 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2100 // (rotr x, (sub 32, y))
2101 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2102 if (SUBC->getAPIntValue() == OpSizeInBits) {
2104 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2106 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2116 SDOperand DAGCombiner::visitXOR(SDNode *N) {
2117 SDOperand N0 = N->getOperand(0);
2118 SDOperand N1 = N->getOperand(1);
2119 SDOperand LHS, RHS, CC;
2120 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2121 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2122 MVT VT = N0.getValueType();
2125 if (VT.isVector()) {
2126 SDOperand FoldedVOp = SimplifyVBinOp(N);
2127 if (FoldedVOp.Val) return FoldedVOp;
2130 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2131 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2132 return DAG.getConstant(0, VT);
2133 // fold (xor x, undef) -> undef
2134 if (N0.getOpcode() == ISD::UNDEF)
2136 if (N1.getOpcode() == ISD::UNDEF)
2138 // fold (xor c1, c2) -> c1^c2
2140 return DAG.getNode(ISD::XOR, VT, N0, N1);
2141 // canonicalize constant to RHS
2143 return DAG.getNode(ISD::XOR, VT, N1, N0);
2144 // fold (xor x, 0) -> x
2145 if (N1C && N1C->isNullValue())
2148 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2151 // fold !(x cc y) -> (x !cc y)
2152 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2153 bool isInt = LHS.getValueType().isInteger();
2154 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2156 if (N0.getOpcode() == ISD::SETCC)
2157 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2158 if (N0.getOpcode() == ISD::SELECT_CC)
2159 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2160 assert(0 && "Unhandled SetCC Equivalent!");
2163 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2164 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2165 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2166 SDOperand V = N0.getOperand(0);
2167 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
2168 DAG.getConstant(1, V.getValueType()));
2169 AddToWorkList(V.Val);
2170 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2173 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2174 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2175 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2176 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2177 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2178 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2179 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2180 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2181 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2182 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2185 // fold !(x or y) -> (!x and !y) iff x or y are constants
2186 if (N1C && N1C->isAllOnesValue() &&
2187 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2188 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2189 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2190 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2191 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2192 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2193 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2194 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2197 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2198 if (N1C && N0.getOpcode() == ISD::XOR) {
2199 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2200 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2202 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2203 DAG.getConstant(N1C->getAPIntValue()^
2204 N00C->getAPIntValue(), VT));
2206 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2207 DAG.getConstant(N1C->getAPIntValue()^
2208 N01C->getAPIntValue(), VT));
2210 // fold (xor x, x) -> 0
2212 if (!VT.isVector()) {
2213 return DAG.getConstant(0, VT);
2214 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2215 // Produce a vector of zeros.
2216 SDOperand El = DAG.getConstant(0, VT.getVectorElementType());
2217 std::vector<SDOperand> Ops(VT.getVectorNumElements(), El);
2218 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2222 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2223 if (N0.getOpcode() == N1.getOpcode()) {
2224 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2225 if (Tmp.Val) return Tmp;
2228 // Simplify the expression using non-local knowledge.
2229 if (!VT.isVector() &&
2230 SimplifyDemandedBits(SDOperand(N, 0)))
2231 return SDOperand(N, 0);
2236 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2237 /// the shift amount is a constant.
2238 SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2239 SDNode *LHS = N->getOperand(0).Val;
2240 if (!LHS->hasOneUse()) return SDOperand();
2242 // We want to pull some binops through shifts, so that we have (and (shift))
2243 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2244 // thing happens with address calculations, so it's important to canonicalize
2246 bool HighBitSet = false; // Can we transform this if the high bit is set?
2248 switch (LHS->getOpcode()) {
2249 default: return SDOperand();
2252 HighBitSet = false; // We can only transform sra if the high bit is clear.
2255 HighBitSet = true; // We can only transform sra if the high bit is set.
2258 if (N->getOpcode() != ISD::SHL)
2259 return SDOperand(); // only shl(add) not sr[al](add).
2260 HighBitSet = false; // We can only transform sra if the high bit is clear.
2264 // We require the RHS of the binop to be a constant as well.
2265 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2266 if (!BinOpCst) return SDOperand();
2269 // FIXME: disable this for unless the input to the binop is a shift by a
2270 // constant. If it is not a shift, it pessimizes some common cases like:
2272 //void foo(int *X, int i) { X[i & 1235] = 1; }
2273 //int bar(int *X, int i) { return X[i & 255]; }
2274 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2275 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2276 BinOpLHSVal->getOpcode() != ISD::SRA &&
2277 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2278 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2281 MVT VT = N->getValueType(0);
2283 // If this is a signed shift right, and the high bit is modified
2284 // by the logical operation, do not perform the transformation.
2285 // The highBitSet boolean indicates the value of the high bit of
2286 // the constant which would cause it to be modified for this
2288 if (N->getOpcode() == ISD::SRA) {
2289 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2290 if (BinOpRHSSignSet != HighBitSet)
2294 // Fold the constants, shifting the binop RHS by the shift amount.
2295 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2296 LHS->getOperand(1), N->getOperand(1));
2298 // Create the new shift.
2299 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2302 // Create the new binop.
2303 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2307 SDOperand DAGCombiner::visitSHL(SDNode *N) {
2308 SDOperand N0 = N->getOperand(0);
2309 SDOperand N1 = N->getOperand(1);
2310 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2311 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2312 MVT VT = N0.getValueType();
2313 unsigned OpSizeInBits = VT.getSizeInBits();
2315 // fold (shl c1, c2) -> c1<<c2
2317 return DAG.getNode(ISD::SHL, VT, N0, N1);
2318 // fold (shl 0, x) -> 0
2319 if (N0C && N0C->isNullValue())
2321 // fold (shl x, c >= size(x)) -> undef
2322 if (N1C && N1C->getValue() >= OpSizeInBits)
2323 return DAG.getNode(ISD::UNDEF, VT);
2324 // fold (shl x, 0) -> x
2325 if (N1C && N1C->isNullValue())
2327 // if (shl x, c) is known to be zero, return 0
2328 if (DAG.MaskedValueIsZero(SDOperand(N, 0),
2329 APInt::getAllOnesValue(VT.getSizeInBits())))
2330 return DAG.getConstant(0, VT);
2331 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2332 return SDOperand(N, 0);
2333 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2334 if (N1C && N0.getOpcode() == ISD::SHL &&
2335 N0.getOperand(1).getOpcode() == ISD::Constant) {
2336 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2337 uint64_t c2 = N1C->getValue();
2338 if (c1 + c2 > OpSizeInBits)
2339 return DAG.getConstant(0, VT);
2340 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2341 DAG.getConstant(c1 + c2, N1.getValueType()));
2343 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2344 // (srl (and x, -1 << c1), c1-c2)
2345 if (N1C && N0.getOpcode() == ISD::SRL &&
2346 N0.getOperand(1).getOpcode() == ISD::Constant) {
2347 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2348 uint64_t c2 = N1C->getValue();
2349 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2350 DAG.getConstant(~0ULL << c1, VT));
2352 return DAG.getNode(ISD::SHL, VT, Mask,
2353 DAG.getConstant(c2-c1, N1.getValueType()));
2355 return DAG.getNode(ISD::SRL, VT, Mask,
2356 DAG.getConstant(c1-c2, N1.getValueType()));
2358 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2359 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2360 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2361 DAG.getConstant(~0ULL << N1C->getValue(), VT));
2363 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2366 SDOperand DAGCombiner::visitSRA(SDNode *N) {
2367 SDOperand N0 = N->getOperand(0);
2368 SDOperand N1 = N->getOperand(1);
2369 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2370 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2371 MVT VT = N0.getValueType();
2373 // fold (sra c1, c2) -> c1>>c2
2375 return DAG.getNode(ISD::SRA, VT, N0, N1);
2376 // fold (sra 0, x) -> 0
2377 if (N0C && N0C->isNullValue())
2379 // fold (sra -1, x) -> -1
2380 if (N0C && N0C->isAllOnesValue())
2382 // fold (sra x, c >= size(x)) -> undef
2383 if (N1C && N1C->getValue() >= VT.getSizeInBits())
2384 return DAG.getNode(ISD::UNDEF, VT);
2385 // fold (sra x, 0) -> x
2386 if (N1C && N1C->isNullValue())
2388 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2390 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2391 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getValue();
2392 MVT EVT = MVT::getIntegerVT(LowBits);
2393 if (EVT.isSimple() && // TODO: remove when apint codegen support lands.
2394 (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
2395 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2396 DAG.getValueType(EVT));
2399 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2400 if (N1C && N0.getOpcode() == ISD::SRA) {
2401 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2402 unsigned Sum = N1C->getValue() + C1->getValue();
2403 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
2404 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2405 DAG.getConstant(Sum, N1C->getValueType(0)));
2409 // fold sra (shl X, m), result_size - n
2410 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
2411 // result_size - n != m.
2412 // If truncate is free for the target sext(shl) is likely to result in better
2414 if (N0.getOpcode() == ISD::SHL) {
2415 // Get the two constanst of the shifts, CN0 = m, CN = n.
2416 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2418 // Determine what the truncate's result bitsize and type would be.
2419 unsigned VTValSize = VT.getSizeInBits();
2421 MVT::getIntegerVT(VTValSize - N1C->getValue());
2422 // Determine the residual right-shift amount.
2423 unsigned ShiftAmt = N1C->getValue() - N01C->getValue();
2425 // If the shift is not a no-op (in which case this should be just a sign
2426 // extend already), the truncated to type is legal, sign_extend is legal
2427 // on that type, and the the truncate to that type is both legal and free,
2428 // perform the transform.
2430 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
2431 TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
2432 TLI.isTruncateFree(VT, TruncVT)) {
2434 SDOperand Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2435 SDOperand Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2436 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2437 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
2442 // Simplify, based on bits shifted out of the LHS.
2443 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2444 return SDOperand(N, 0);
2447 // If the sign bit is known to be zero, switch this to a SRL.
2448 if (DAG.SignBitIsZero(N0))
2449 return DAG.getNode(ISD::SRL, VT, N0, N1);
2451 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2454 SDOperand DAGCombiner::visitSRL(SDNode *N) {
2455 SDOperand N0 = N->getOperand(0);
2456 SDOperand N1 = N->getOperand(1);
2457 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2458 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2459 MVT VT = N0.getValueType();
2460 unsigned OpSizeInBits = VT.getSizeInBits();
2462 // fold (srl c1, c2) -> c1 >>u c2
2464 return DAG.getNode(ISD::SRL, VT, N0, N1);
2465 // fold (srl 0, x) -> 0
2466 if (N0C && N0C->isNullValue())
2468 // fold (srl x, c >= size(x)) -> undef
2469 if (N1C && N1C->getValue() >= OpSizeInBits)
2470 return DAG.getNode(ISD::UNDEF, VT);
2471 // fold (srl x, 0) -> x
2472 if (N1C && N1C->isNullValue())
2474 // if (srl x, c) is known to be zero, return 0
2475 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
2476 APInt::getAllOnesValue(OpSizeInBits)))
2477 return DAG.getConstant(0, VT);
2479 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2480 if (N1C && N0.getOpcode() == ISD::SRL &&
2481 N0.getOperand(1).getOpcode() == ISD::Constant) {
2482 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2483 uint64_t c2 = N1C->getValue();
2484 if (c1 + c2 > OpSizeInBits)
2485 return DAG.getConstant(0, VT);
2486 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2487 DAG.getConstant(c1 + c2, N1.getValueType()));
2490 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2491 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2492 // Shifting in all undef bits?
2493 MVT SmallVT = N0.getOperand(0).getValueType();
2494 if (N1C->getValue() >= SmallVT.getSizeInBits())
2495 return DAG.getNode(ISD::UNDEF, VT);
2497 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2498 AddToWorkList(SmallShift.Val);
2499 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2502 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2503 // bit, which is unmodified by sra.
2504 if (N1C && N1C->getValue()+1 == VT.getSizeInBits()) {
2505 if (N0.getOpcode() == ISD::SRA)
2506 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2509 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2510 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2511 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2512 APInt KnownZero, KnownOne;
2513 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2514 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2516 // If any of the input bits are KnownOne, then the input couldn't be all
2517 // zeros, thus the result of the srl will always be zero.
2518 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2520 // If all of the bits input the to ctlz node are known to be zero, then
2521 // the result of the ctlz is "32" and the result of the shift is one.
2522 APInt UnknownBits = ~KnownZero & Mask;
2523 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2525 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2526 if ((UnknownBits & (UnknownBits-1)) == 0) {
2527 // Okay, we know that only that the single bit specified by UnknownBits
2528 // could be set on input to the CTLZ node. If this bit is set, the SRL
2529 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2530 // to an SRL,XOR pair, which is likely to simplify more.
2531 unsigned ShAmt = UnknownBits.countTrailingZeros();
2532 SDOperand Op = N0.getOperand(0);
2534 Op = DAG.getNode(ISD::SRL, VT, Op,
2535 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2536 AddToWorkList(Op.Val);
2538 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2542 // fold operands of srl based on knowledge that the low bits are not
2544 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2545 return SDOperand(N, 0);
2547 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2550 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2551 SDOperand N0 = N->getOperand(0);
2552 MVT VT = N->getValueType(0);
2554 // fold (ctlz c1) -> c2
2555 if (isa<ConstantSDNode>(N0))
2556 return DAG.getNode(ISD::CTLZ, VT, N0);
2560 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2561 SDOperand N0 = N->getOperand(0);
2562 MVT VT = N->getValueType(0);
2564 // fold (cttz c1) -> c2
2565 if (isa<ConstantSDNode>(N0))
2566 return DAG.getNode(ISD::CTTZ, VT, N0);
2570 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2571 SDOperand N0 = N->getOperand(0);
2572 MVT VT = N->getValueType(0);
2574 // fold (ctpop c1) -> c2
2575 if (isa<ConstantSDNode>(N0))
2576 return DAG.getNode(ISD::CTPOP, VT, N0);
2580 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2581 SDOperand N0 = N->getOperand(0);
2582 SDOperand N1 = N->getOperand(1);
2583 SDOperand N2 = N->getOperand(2);
2584 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2585 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2586 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2587 MVT VT = N->getValueType(0);
2588 MVT VT0 = N0.getValueType();
2590 // fold select C, X, X -> X
2593 // fold select true, X, Y -> X
2594 if (N0C && !N0C->isNullValue())
2596 // fold select false, X, Y -> Y
2597 if (N0C && N0C->isNullValue())
2599 // fold select C, 1, X -> C | X
2600 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2601 return DAG.getNode(ISD::OR, VT, N0, N2);
2602 // fold select C, 0, 1 -> ~C
2603 if (VT.isInteger() && VT0.isInteger() &&
2604 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2605 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2608 AddToWorkList(XORNode.Val);
2610 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2611 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2613 // fold select C, 0, X -> ~C & X
2614 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2615 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2616 AddToWorkList(XORNode.Val);
2617 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2619 // fold select C, X, 1 -> ~C | X
2620 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2621 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2622 AddToWorkList(XORNode.Val);
2623 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2625 // fold select C, X, 0 -> C & X
2626 // FIXME: this should check for C type == X type, not i1?
2627 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2628 return DAG.getNode(ISD::AND, VT, N0, N1);
2629 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2630 if (VT == MVT::i1 && N0 == N1)
2631 return DAG.getNode(ISD::OR, VT, N0, N2);
2632 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2633 if (VT == MVT::i1 && N0 == N2)
2634 return DAG.getNode(ISD::AND, VT, N0, N1);
2636 // If we can fold this based on the true/false value, do so.
2637 if (SimplifySelectOps(N, N1, N2))
2638 return SDOperand(N, 0); // Don't revisit N.
2640 // fold selects based on a setcc into other things, such as min/max/abs
2641 if (N0.getOpcode() == ISD::SETCC) {
2643 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2644 // having to say they don't support SELECT_CC on every type the DAG knows
2645 // about, since there is no way to mark an opcode illegal at all value types
2646 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2647 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2648 N1, N2, N0.getOperand(2));
2650 return SimplifySelect(N0, N1, N2);
2655 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2656 SDOperand N0 = N->getOperand(0);
2657 SDOperand N1 = N->getOperand(1);
2658 SDOperand N2 = N->getOperand(2);
2659 SDOperand N3 = N->getOperand(3);
2660 SDOperand N4 = N->getOperand(4);
2661 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2663 // fold select_cc lhs, rhs, x, x, cc -> x
2667 // Determine if the condition we're dealing with is constant
2668 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
2669 if (SCC.Val) AddToWorkList(SCC.Val);
2671 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2672 if (!SCCC->isNullValue())
2673 return N2; // cond always true -> true val
2675 return N3; // cond always false -> false val
2678 // Fold to a simpler select_cc
2679 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2680 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2681 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2684 // If we can fold this based on the true/false value, do so.
2685 if (SimplifySelectOps(N, N2, N3))
2686 return SDOperand(N, 0); // Don't revisit N.
2688 // fold select_cc into other things, such as min/max/abs
2689 return SimplifySelectCC(N0, N1, N2, N3, CC);
2692 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2693 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2694 cast<CondCodeSDNode>(N->getOperand(2))->get());
2697 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2698 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2699 // transformation. Returns true if extension are possible and the above
2700 // mentioned transformation is profitable.
2701 static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2703 SmallVector<SDNode*, 4> &ExtendNodes,
2704 TargetLowering &TLI) {
2705 bool HasCopyToRegUses = false;
2706 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2707 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2709 SDNode *User = UI->getUser();
2712 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2713 if (User->getOpcode() == ISD::SETCC) {
2714 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2715 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2716 // Sign bits will be lost after a zext.
2719 for (unsigned i = 0; i != 2; ++i) {
2720 SDOperand UseOp = User->getOperand(i);
2723 if (!isa<ConstantSDNode>(UseOp))
2728 ExtendNodes.push_back(User);
2730 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2731 SDOperand UseOp = User->getOperand(i);
2733 // If truncate from extended type to original load type is free
2734 // on this target, then it's ok to extend a CopyToReg.
2735 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2736 HasCopyToRegUses = true;
2744 if (HasCopyToRegUses) {
2745 bool BothLiveOut = false;
2746 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2748 SDNode *User = UI->getUser();
2749 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2750 SDOperand UseOp = User->getOperand(i);
2751 if (UseOp.Val == N && UseOp.ResNo == 0) {
2758 // Both unextended and extended values are live out. There had better be
2759 // good a reason for the transformation.
2760 return ExtendNodes.size();
2765 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2766 SDOperand N0 = N->getOperand(0);
2767 MVT VT = N->getValueType(0);
2769 // fold (sext c1) -> c1
2770 if (isa<ConstantSDNode>(N0))
2771 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2773 // fold (sext (sext x)) -> (sext x)
2774 // fold (sext (aext x)) -> (sext x)
2775 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2776 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2778 if (N0.getOpcode() == ISD::TRUNCATE) {
2779 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2780 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2781 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2782 if (NarrowLoad.Val) {
2783 if (NarrowLoad.Val != N0.Val)
2784 CombineTo(N0.Val, NarrowLoad);
2785 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2788 // See if the value being truncated is already sign extended. If so, just
2789 // eliminate the trunc/sext pair.
2790 SDOperand Op = N0.getOperand(0);
2791 unsigned OpBits = Op.getValueType().getSizeInBits();
2792 unsigned MidBits = N0.getValueType().getSizeInBits();
2793 unsigned DestBits = VT.getSizeInBits();
2794 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2796 if (OpBits == DestBits) {
2797 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2798 // bits, it is already ready.
2799 if (NumSignBits > DestBits-MidBits)
2801 } else if (OpBits < DestBits) {
2802 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2803 // bits, just sext from i32.
2804 if (NumSignBits > OpBits-MidBits)
2805 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2807 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2808 // bits, just truncate to i32.
2809 if (NumSignBits > OpBits-MidBits)
2810 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2813 // fold (sext (truncate x)) -> (sextinreg x).
2814 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2815 N0.getValueType())) {
2816 if (Op.getValueType().bitsLT(VT))
2817 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2818 else if (Op.getValueType().bitsGT(VT))
2819 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2820 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2821 DAG.getValueType(N0.getValueType()));
2825 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2826 if (ISD::isNON_EXTLoad(N0.Val) &&
2827 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2828 TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))) {
2829 bool DoXform = true;
2830 SmallVector<SDNode*, 4> SetCCs;
2831 if (!N0.hasOneUse())
2832 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2834 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2835 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2836 LN0->getBasePtr(), LN0->getSrcValue(),
2837 LN0->getSrcValueOffset(),
2840 LN0->getAlignment());
2841 CombineTo(N, ExtLoad);
2842 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2843 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2844 // Extend SetCC uses if necessary.
2845 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2846 SDNode *SetCC = SetCCs[i];
2847 SmallVector<SDOperand, 4> Ops;
2848 for (unsigned j = 0; j != 2; ++j) {
2849 SDOperand SOp = SetCC->getOperand(j);
2851 Ops.push_back(ExtLoad);
2853 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2855 Ops.push_back(SetCC->getOperand(2));
2856 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2857 &Ops[0], Ops.size()));
2859 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2863 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2864 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2865 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2866 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2867 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2868 MVT EVT = LN0->getMemoryVT();
2869 if ((!AfterLegalize && !LN0->isVolatile()) ||
2870 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2871 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2872 LN0->getBasePtr(), LN0->getSrcValue(),
2873 LN0->getSrcValueOffset(), EVT,
2875 LN0->getAlignment());
2876 CombineTo(N, ExtLoad);
2877 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2878 ExtLoad.getValue(1));
2879 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2883 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2884 if (N0.getOpcode() == ISD::SETCC) {
2886 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2887 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2888 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2889 if (SCC.Val) return SCC;
2892 // fold (sext x) -> (zext x) if the sign bit is known zero.
2893 if ((!AfterLegalize || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
2894 DAG.SignBitIsZero(N0))
2895 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2900 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2901 SDOperand N0 = N->getOperand(0);
2902 MVT VT = N->getValueType(0);
2904 // fold (zext c1) -> c1
2905 if (isa<ConstantSDNode>(N0))
2906 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2907 // fold (zext (zext x)) -> (zext x)
2908 // fold (zext (aext x)) -> (zext x)
2909 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2910 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2912 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2913 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2914 if (N0.getOpcode() == ISD::TRUNCATE) {
2915 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2916 if (NarrowLoad.Val) {
2917 if (NarrowLoad.Val != N0.Val)
2918 CombineTo(N0.Val, NarrowLoad);
2919 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2923 // fold (zext (truncate x)) -> (and x, mask)
2924 if (N0.getOpcode() == ISD::TRUNCATE &&
2925 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2926 SDOperand Op = N0.getOperand(0);
2927 if (Op.getValueType().bitsLT(VT)) {
2928 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2929 } else if (Op.getValueType().bitsGT(VT)) {
2930 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2932 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2935 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2936 if (N0.getOpcode() == ISD::AND &&
2937 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2938 N0.getOperand(1).getOpcode() == ISD::Constant) {
2939 SDOperand X = N0.getOperand(0).getOperand(0);
2940 if (X.getValueType().bitsLT(VT)) {
2941 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2942 } else if (X.getValueType().bitsGT(VT)) {
2943 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2945 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2946 Mask.zext(VT.getSizeInBits());
2947 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2950 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2951 if (ISD::isNON_EXTLoad(N0.Val) &&
2952 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2953 TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2954 bool DoXform = true;
2955 SmallVector<SDNode*, 4> SetCCs;
2956 if (!N0.hasOneUse())
2957 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2959 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2960 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2961 LN0->getBasePtr(), LN0->getSrcValue(),
2962 LN0->getSrcValueOffset(),
2965 LN0->getAlignment());
2966 CombineTo(N, ExtLoad);
2967 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2968 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2969 // Extend SetCC uses if necessary.
2970 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2971 SDNode *SetCC = SetCCs[i];
2972 SmallVector<SDOperand, 4> Ops;
2973 for (unsigned j = 0; j != 2; ++j) {
2974 SDOperand SOp = SetCC->getOperand(j);
2976 Ops.push_back(ExtLoad);
2978 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
2980 Ops.push_back(SetCC->getOperand(2));
2981 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2982 &Ops[0], Ops.size()));
2984 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2988 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2989 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2990 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2991 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2992 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2993 MVT EVT = LN0->getMemoryVT();
2994 if ((!AfterLegalize && !LN0->isVolatile()) ||
2995 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT)) {
2996 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2997 LN0->getBasePtr(), LN0->getSrcValue(),
2998 LN0->getSrcValueOffset(), EVT,
3000 LN0->getAlignment());
3001 CombineTo(N, ExtLoad);
3002 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3003 ExtLoad.getValue(1));
3004 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3008 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3009 if (N0.getOpcode() == ISD::SETCC) {
3011 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3012 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3013 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3014 if (SCC.Val) return SCC;
3020 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
3021 SDOperand N0 = N->getOperand(0);
3022 MVT VT = N->getValueType(0);
3024 // fold (aext c1) -> c1
3025 if (isa<ConstantSDNode>(N0))
3026 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
3027 // fold (aext (aext x)) -> (aext x)
3028 // fold (aext (zext x)) -> (zext x)
3029 // fold (aext (sext x)) -> (sext x)
3030 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3031 N0.getOpcode() == ISD::ZERO_EXTEND ||
3032 N0.getOpcode() == ISD::SIGN_EXTEND)
3033 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3035 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3036 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3037 if (N0.getOpcode() == ISD::TRUNCATE) {
3038 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
3039 if (NarrowLoad.Val) {
3040 if (NarrowLoad.Val != N0.Val)
3041 CombineTo(N0.Val, NarrowLoad);
3042 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3046 // fold (aext (truncate x))
3047 if (N0.getOpcode() == ISD::TRUNCATE) {
3048 SDOperand TruncOp = N0.getOperand(0);
3049 if (TruncOp.getValueType() == VT)
3050 return TruncOp; // x iff x size == zext size.
3051 if (TruncOp.getValueType().bitsGT(VT))
3052 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3053 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3056 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3057 if (N0.getOpcode() == ISD::AND &&
3058 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3059 N0.getOperand(1).getOpcode() == ISD::Constant) {
3060 SDOperand X = N0.getOperand(0).getOperand(0);
3061 if (X.getValueType().bitsLT(VT)) {
3062 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3063 } else if (X.getValueType().bitsGT(VT)) {
3064 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3066 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3067 Mask.zext(VT.getSizeInBits());
3068 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3071 // fold (aext (load x)) -> (aext (truncate (extload x)))
3072 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3073 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3074 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3075 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3076 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3077 LN0->getBasePtr(), LN0->getSrcValue(),
3078 LN0->getSrcValueOffset(),
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 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3089 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3090 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3091 if (N0.getOpcode() == ISD::LOAD &&
3092 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3094 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3095 MVT EVT = LN0->getMemoryVT();
3096 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3097 LN0->getChain(), LN0->getBasePtr(),
3099 LN0->getSrcValueOffset(), EVT,
3101 LN0->getAlignment());
3102 CombineTo(N, ExtLoad);
3103 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3104 ExtLoad.getValue(1));
3105 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3108 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3109 if (N0.getOpcode() == ISD::SETCC) {
3111 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3112 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3113 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3121 /// GetDemandedBits - See if the specified operand can be simplified with the
3122 /// knowledge that only the bits specified by Mask are used. If so, return the
3123 /// simpler operand, otherwise return a null SDOperand.
3124 SDOperand DAGCombiner::GetDemandedBits(SDOperand V, const APInt &Mask) {
3125 switch (V.getOpcode()) {
3129 // If the LHS or RHS don't contribute bits to the or, drop them.
3130 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3131 return V.getOperand(1);
3132 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3133 return V.getOperand(0);
3136 // Only look at single-use SRLs.
3137 if (!V.Val->hasOneUse())
3139 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3140 // See if we can recursively simplify the LHS.
3141 unsigned Amt = RHSC->getValue();
3142 APInt NewMask = Mask << Amt;
3143 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3144 if (SimplifyLHS.Val) {
3145 return DAG.getNode(ISD::SRL, V.getValueType(),
3146 SimplifyLHS, V.getOperand(1));
3153 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3154 /// bits and then truncated to a narrower type and where N is a multiple
3155 /// of number of bits of the narrower type, transform it to a narrower load
3156 /// from address + N / num of bits of new type. If the result is to be
3157 /// extended, also fold the extension to form a extending load.
3158 SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3159 unsigned Opc = N->getOpcode();
3160 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3161 SDOperand N0 = N->getOperand(0);
3162 MVT VT = N->getValueType(0);
3163 MVT EVT = N->getValueType(0);
3165 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3167 if (Opc == ISD::SIGN_EXTEND_INREG) {
3168 ExtType = ISD::SEXTLOAD;
3169 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3170 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3174 unsigned EVTBits = EVT.getSizeInBits();
3176 bool CombineSRL = false;
3177 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3178 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3179 ShAmt = N01->getValue();
3180 // Is the shift amount a multiple of size of VT?
3181 if ((ShAmt & (EVTBits-1)) == 0) {
3182 N0 = N0.getOperand(0);
3183 if (N0.getValueType().getSizeInBits() <= EVTBits)
3190 // Do not generate loads of extended integer types since these can be
3191 // expensive (and would be wrong if the type is not byte sized).
3192 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() && VT.isSimple() &&
3193 VT.isByteSized() && // Exclude MVT::i1, which is simple.
3194 // Do not change the width of a volatile load.
3195 !cast<LoadSDNode>(N0)->isVolatile()) {
3196 assert(N0.getValueType().getSizeInBits() > EVTBits &&
3197 "Cannot truncate to larger type!");
3198 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3199 MVT PtrType = N0.getOperand(1).getValueType();
3200 // For big endian targets, we need to adjust the offset to the pointer to
3201 // load the correct bytes.
3202 if (TLI.isBigEndian()) {
3203 unsigned LVTStoreBits = N0.getValueType().getStoreSizeInBits();
3204 unsigned EVTStoreBits = EVT.getStoreSizeInBits();
3205 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3207 uint64_t PtrOff = ShAmt / 8;
3208 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3209 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3210 DAG.getConstant(PtrOff, PtrType));
3211 AddToWorkList(NewPtr.Val);
3212 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3213 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3214 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3215 LN0->isVolatile(), NewAlign)
3216 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3217 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
3218 LN0->isVolatile(), NewAlign);
3221 WorkListRemover DeadNodes(*this);
3222 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3224 CombineTo(N->getOperand(0).Val, Load);
3226 CombineTo(N0.Val, Load, Load.getValue(1));
3228 if (Opc == ISD::SIGN_EXTEND_INREG)
3229 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3231 return DAG.getNode(Opc, VT, Load);
3233 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3240 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3241 SDOperand N0 = N->getOperand(0);
3242 SDOperand N1 = N->getOperand(1);
3243 MVT VT = N->getValueType(0);
3244 MVT EVT = cast<VTSDNode>(N1)->getVT();
3245 unsigned VTBits = VT.getSizeInBits();
3246 unsigned EVTBits = EVT.getSizeInBits();
3248 // fold (sext_in_reg c1) -> c1
3249 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3250 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3252 // If the input is already sign extended, just drop the extension.
3253 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
3256 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3257 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3258 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3259 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3262 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3263 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3264 return DAG.getZeroExtendInReg(N0, EVT);
3266 // fold operands of sext_in_reg based on knowledge that the top bits are not
3268 if (SimplifyDemandedBits(SDOperand(N, 0)))
3269 return SDOperand(N, 0);
3271 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3272 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3273 SDOperand NarrowLoad = ReduceLoadWidth(N);
3277 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3278 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3279 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3280 if (N0.getOpcode() == ISD::SRL) {
3281 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3282 if (ShAmt->getValue()+EVTBits <= VT.getSizeInBits()) {
3283 // We can turn this into an SRA iff the input to the SRL is already sign
3285 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3286 if (VT.getSizeInBits()-(ShAmt->getValue()+EVTBits) < InSignBits)
3287 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3291 // fold (sext_inreg (extload x)) -> (sextload x)
3292 if (ISD::isEXTLoad(N0.Val) &&
3293 ISD::isUNINDEXEDLoad(N0.Val) &&
3294 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3295 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3296 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3297 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3298 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3299 LN0->getBasePtr(), LN0->getSrcValue(),
3300 LN0->getSrcValueOffset(), EVT,
3302 LN0->getAlignment());
3303 CombineTo(N, ExtLoad);
3304 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3305 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3307 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3308 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3310 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3311 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3312 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3313 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3314 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3315 LN0->getBasePtr(), LN0->getSrcValue(),
3316 LN0->getSrcValueOffset(), EVT,
3318 LN0->getAlignment());
3319 CombineTo(N, ExtLoad);
3320 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3321 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3326 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3327 SDOperand N0 = N->getOperand(0);
3328 MVT VT = N->getValueType(0);
3331 if (N0.getValueType() == N->getValueType(0))
3333 // fold (truncate c1) -> c1
3334 if (isa<ConstantSDNode>(N0))
3335 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3336 // fold (truncate (truncate x)) -> (truncate x)
3337 if (N0.getOpcode() == ISD::TRUNCATE)
3338 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3339 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3340 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3341 N0.getOpcode() == ISD::ANY_EXTEND) {
3342 if (N0.getOperand(0).getValueType().bitsLT(VT))
3343 // if the source is smaller than the dest, we still need an extend
3344 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3345 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3346 // if the source is larger than the dest, than we just need the truncate
3347 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3349 // if the source and dest are the same type, we can drop both the extend
3351 return N0.getOperand(0);
3354 // See if we can simplify the input to this truncate through knowledge that
3355 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3358 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3359 VT.getSizeInBits()));
3361 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3363 // fold (truncate (load x)) -> (smaller load x)
3364 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3365 return ReduceLoadWidth(N);
3368 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3369 SDOperand Elt = N->getOperand(i);
3370 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3372 return Elt.getOperand(Elt.ResNo).Val;
3375 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3376 /// if load locations are consecutive.
3377 SDOperand DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT VT) {
3378 assert(N->getOpcode() == ISD::BUILD_PAIR);
3380 SDNode *LD1 = getBuildPairElt(N, 0);
3381 if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3383 MVT LD1VT = LD1->getValueType(0);
3384 SDNode *LD2 = getBuildPairElt(N, 1);
3385 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3386 if (ISD::isNON_EXTLoad(LD2) &&
3388 // If both are volatile this would reduce the number of volatile loads.
3389 // If one is volatile it might be ok, but play conservative and bail out.
3390 !cast<LoadSDNode>(LD1)->isVolatile() &&
3391 !cast<LoadSDNode>(LD2)->isVolatile() &&
3392 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
3393 LoadSDNode *LD = cast<LoadSDNode>(LD1);
3394 unsigned Align = LD->getAlignment();
3395 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
3396 getABITypeAlignment(VT.getTypeForMVT());
3397 if (NewAlign <= Align &&
3398 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT)))
3399 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(),
3400 LD->getSrcValue(), LD->getSrcValueOffset(),
3406 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3407 SDOperand N0 = N->getOperand(0);
3408 MVT VT = N->getValueType(0);
3410 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3411 // Only do this before legalize, since afterward the target may be depending
3412 // on the bitconvert.
3413 // First check to see if this is all constant.
3414 if (!AfterLegalize &&
3415 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3417 bool isSimple = true;
3418 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3419 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3420 N0.getOperand(i).getOpcode() != ISD::Constant &&
3421 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3426 MVT DestEltVT = N->getValueType(0).getVectorElementType();
3427 assert(!DestEltVT.isVector() &&
3428 "Element type of vector ValueType must not be vector!");
3430 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3434 // If the input is a constant, let getNode() fold it.
3435 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3436 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3437 if (Res.Val != N) return Res;
3440 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3441 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3443 // fold (conv (load x)) -> (load (conv*)x)
3444 // If the resultant load doesn't need a higher alignment than the original!
3445 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
3446 // Do not change the width of a volatile load.
3447 !cast<LoadSDNode>(N0)->isVolatile() &&
3448 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT))) {
3449 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3450 unsigned Align = TLI.getTargetMachine().getTargetData()->
3451 getABITypeAlignment(VT.getTypeForMVT());
3452 unsigned OrigAlign = LN0->getAlignment();
3453 if (Align <= OrigAlign) {
3454 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3455 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3456 LN0->isVolatile(), Align);
3458 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3464 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3465 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3466 // This often reduces constant pool loads.
3467 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3468 N0.Val->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3469 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3470 AddToWorkList(NewConv.Val);
3472 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3473 if (N0.getOpcode() == ISD::FNEG)
3474 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3475 assert(N0.getOpcode() == ISD::FABS);
3476 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3479 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3480 // Note that we don't handle copysign(x,cst) because this can always be folded
3481 // to an fneg or fabs.
3482 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
3483 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3484 VT.isInteger() && !VT.isVector()) {
3485 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3486 SDOperand X = DAG.getNode(ISD::BIT_CONVERT,
3487 MVT::getIntegerVT(OrigXWidth),
3489 AddToWorkList(X.Val);
3491 // If X has a different width than the result/lhs, sext it or truncate it.
3492 unsigned VTWidth = VT.getSizeInBits();
3493 if (OrigXWidth < VTWidth) {
3494 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3495 AddToWorkList(X.Val);
3496 } else if (OrigXWidth > VTWidth) {
3497 // To get the sign bit in the right place, we have to shift it right
3498 // before truncating.
3499 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3500 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3501 AddToWorkList(X.Val);
3502 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3503 AddToWorkList(X.Val);
3506 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3507 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3508 AddToWorkList(X.Val);
3510 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3511 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3512 AddToWorkList(Cst.Val);
3514 return DAG.getNode(ISD::OR, VT, X, Cst);
3517 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3518 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3519 SDOperand CombineLD = CombineConsecutiveLoads(N0.Val, VT);
3527 SDOperand DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3528 MVT VT = N->getValueType(0);
3529 return CombineConsecutiveLoads(N, VT);
3532 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3533 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3534 /// destination element value type.
3535 SDOperand DAGCombiner::
3536 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT DstEltVT) {
3537 MVT SrcEltVT = BV->getOperand(0).getValueType();
3539 // If this is already the right type, we're done.
3540 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3542 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3543 unsigned DstBitSize = DstEltVT.getSizeInBits();
3545 // If this is a conversion of N elements of one type to N elements of another
3546 // type, convert each element. This handles FP<->INT cases.
3547 if (SrcBitSize == DstBitSize) {
3548 SmallVector<SDOperand, 8> Ops;
3549 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3550 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3551 AddToWorkList(Ops.back().Val);
3553 MVT VT = MVT::getVectorVT(DstEltVT,
3554 BV->getValueType(0).getVectorNumElements());
3555 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3558 // Otherwise, we're growing or shrinking the elements. To avoid having to
3559 // handle annoying details of growing/shrinking FP values, we convert them to
3561 if (SrcEltVT.isFloatingPoint()) {
3562 // Convert the input float vector to a int vector where the elements are the
3564 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3565 MVT IntVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits());
3566 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3570 // Now we know the input is an integer vector. If the output is a FP type,
3571 // convert to integer first, then to FP of the right size.
3572 if (DstEltVT.isFloatingPoint()) {
3573 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3574 MVT TmpVT = MVT::getIntegerVT(DstEltVT.getSizeInBits());
3575 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3577 // Next, convert to FP elements of the same size.
3578 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3581 // Okay, we know the src/dst types are both integers of differing types.
3582 // Handling growing first.
3583 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
3584 if (SrcBitSize < DstBitSize) {
3585 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3587 SmallVector<SDOperand, 8> Ops;
3588 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3589 i += NumInputsPerOutput) {
3590 bool isLE = TLI.isLittleEndian();
3591 APInt NewBits = APInt(DstBitSize, 0);
3592 bool EltIsUndef = true;
3593 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3594 // Shift the previously computed bits over.
3595 NewBits <<= SrcBitSize;
3596 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3597 if (Op.getOpcode() == ISD::UNDEF) continue;
3601 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
3605 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3607 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3610 MVT VT = MVT::getVectorVT(DstEltVT, Ops.size());
3611 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3614 // Finally, this must be the case where we are shrinking elements: each input
3615 // turns into multiple outputs.
3616 bool isS2V = ISD::isScalarToVector(BV);
3617 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3618 MVT VT = MVT::getVectorVT(DstEltVT, NumOutputsPerInput*BV->getNumOperands());
3619 SmallVector<SDOperand, 8> Ops;
3620 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3621 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3622 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3623 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3626 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
3627 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3628 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3629 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3630 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3631 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3632 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
3633 OpVal = OpVal.lshr(DstBitSize);
3636 // For big endian targets, swap the order of the pieces of each element.
3637 if (TLI.isBigEndian())
3638 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3640 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3645 SDOperand DAGCombiner::visitFADD(SDNode *N) {
3646 SDOperand N0 = N->getOperand(0);
3647 SDOperand N1 = N->getOperand(1);
3648 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3649 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3650 MVT VT = N->getValueType(0);
3653 if (VT.isVector()) {
3654 SDOperand FoldedVOp = SimplifyVBinOp(N);
3655 if (FoldedVOp.Val) return FoldedVOp;
3658 // fold (fadd c1, c2) -> c1+c2
3659 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3660 return DAG.getNode(ISD::FADD, VT, N0, N1);
3661 // canonicalize constant to RHS
3662 if (N0CFP && !N1CFP)
3663 return DAG.getNode(ISD::FADD, VT, N1, N0);
3664 // fold (A + (-B)) -> A-B
3665 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3666 return DAG.getNode(ISD::FSUB, VT, N0,
3667 GetNegatedExpression(N1, DAG, AfterLegalize));
3668 // fold ((-A) + B) -> B-A
3669 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3670 return DAG.getNode(ISD::FSUB, VT, N1,
3671 GetNegatedExpression(N0, DAG, AfterLegalize));
3673 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3674 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3675 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3676 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3677 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3682 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3683 SDOperand N0 = N->getOperand(0);
3684 SDOperand N1 = N->getOperand(1);
3685 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3686 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3687 MVT VT = N->getValueType(0);
3690 if (VT.isVector()) {
3691 SDOperand FoldedVOp = SimplifyVBinOp(N);
3692 if (FoldedVOp.Val) return FoldedVOp;
3695 // fold (fsub c1, c2) -> c1-c2
3696 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3697 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3699 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3700 if (isNegatibleForFree(N1, AfterLegalize))
3701 return GetNegatedExpression(N1, DAG, AfterLegalize);
3702 return DAG.getNode(ISD::FNEG, VT, N1);
3704 // fold (A-(-B)) -> A+B
3705 if (isNegatibleForFree(N1, AfterLegalize))
3706 return DAG.getNode(ISD::FADD, VT, N0,
3707 GetNegatedExpression(N1, DAG, AfterLegalize));
3712 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3713 SDOperand N0 = N->getOperand(0);
3714 SDOperand N1 = N->getOperand(1);
3715 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3716 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3717 MVT VT = N->getValueType(0);
3720 if (VT.isVector()) {
3721 SDOperand FoldedVOp = SimplifyVBinOp(N);
3722 if (FoldedVOp.Val) return FoldedVOp;
3725 // fold (fmul c1, c2) -> c1*c2
3726 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3727 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3728 // canonicalize constant to RHS
3729 if (N0CFP && !N1CFP)
3730 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3731 // fold (fmul X, 2.0) -> (fadd X, X)
3732 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3733 return DAG.getNode(ISD::FADD, VT, N0, N0);
3734 // fold (fmul X, -1.0) -> (fneg X)
3735 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3736 return DAG.getNode(ISD::FNEG, VT, N0);
3739 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3740 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3741 // Both can be negated for free, check to see if at least one is cheaper
3743 if (LHSNeg == 2 || RHSNeg == 2)
3744 return DAG.getNode(ISD::FMUL, VT,
3745 GetNegatedExpression(N0, DAG, AfterLegalize),
3746 GetNegatedExpression(N1, DAG, AfterLegalize));
3750 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3751 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3752 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3753 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3754 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3759 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3760 SDOperand N0 = N->getOperand(0);
3761 SDOperand N1 = N->getOperand(1);
3762 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3763 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3764 MVT VT = N->getValueType(0);
3767 if (VT.isVector()) {
3768 SDOperand FoldedVOp = SimplifyVBinOp(N);
3769 if (FoldedVOp.Val) return FoldedVOp;
3772 // fold (fdiv c1, c2) -> c1/c2
3773 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3774 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3778 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3779 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3780 // Both can be negated for free, check to see if at least one is cheaper
3782 if (LHSNeg == 2 || RHSNeg == 2)
3783 return DAG.getNode(ISD::FDIV, VT,
3784 GetNegatedExpression(N0, DAG, AfterLegalize),
3785 GetNegatedExpression(N1, DAG, AfterLegalize));
3792 SDOperand DAGCombiner::visitFREM(SDNode *N) {
3793 SDOperand N0 = N->getOperand(0);
3794 SDOperand N1 = N->getOperand(1);
3795 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3796 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3797 MVT VT = N->getValueType(0);
3799 // fold (frem c1, c2) -> fmod(c1,c2)
3800 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3801 return DAG.getNode(ISD::FREM, VT, N0, N1);
3806 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3807 SDOperand N0 = N->getOperand(0);
3808 SDOperand N1 = N->getOperand(1);
3809 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3810 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3811 MVT VT = N->getValueType(0);
3813 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
3814 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3817 const APFloat& V = N1CFP->getValueAPF();
3818 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3819 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3820 if (!V.isNegative())
3821 return DAG.getNode(ISD::FABS, VT, N0);
3823 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3826 // copysign(fabs(x), y) -> copysign(x, y)
3827 // copysign(fneg(x), y) -> copysign(x, y)
3828 // copysign(copysign(x,z), y) -> copysign(x, y)
3829 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3830 N0.getOpcode() == ISD::FCOPYSIGN)
3831 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3833 // copysign(x, abs(y)) -> abs(x)
3834 if (N1.getOpcode() == ISD::FABS)
3835 return DAG.getNode(ISD::FABS, VT, N0);
3837 // copysign(x, copysign(y,z)) -> copysign(x, z)
3838 if (N1.getOpcode() == ISD::FCOPYSIGN)
3839 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3841 // copysign(x, fp_extend(y)) -> copysign(x, y)
3842 // copysign(x, fp_round(y)) -> copysign(x, y)
3843 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3844 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3851 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3852 SDOperand N0 = N->getOperand(0);
3853 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3854 MVT VT = N->getValueType(0);
3856 // fold (sint_to_fp c1) -> c1fp
3857 if (N0C && N0.getValueType() != MVT::ppcf128)
3858 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3862 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3863 SDOperand N0 = N->getOperand(0);
3864 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3865 MVT VT = N->getValueType(0);
3867 // fold (uint_to_fp c1) -> c1fp
3868 if (N0C && N0.getValueType() != MVT::ppcf128)
3869 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3873 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3874 SDOperand N0 = N->getOperand(0);
3875 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3876 MVT VT = N->getValueType(0);
3878 // fold (fp_to_sint c1fp) -> c1
3880 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3884 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3885 SDOperand N0 = N->getOperand(0);
3886 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3887 MVT VT = N->getValueType(0);
3889 // fold (fp_to_uint c1fp) -> c1
3890 if (N0CFP && VT != MVT::ppcf128)
3891 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3895 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3896 SDOperand N0 = N->getOperand(0);
3897 SDOperand N1 = N->getOperand(1);
3898 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3899 MVT VT = N->getValueType(0);
3901 // fold (fp_round c1fp) -> c1fp
3902 if (N0CFP && N0.getValueType() != MVT::ppcf128)
3903 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
3905 // fold (fp_round (fp_extend x)) -> x
3906 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3907 return N0.getOperand(0);
3909 // fold (fp_round (fp_round x)) -> (fp_round x)
3910 if (N0.getOpcode() == ISD::FP_ROUND) {
3911 // This is a value preserving truncation if both round's are.
3912 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3913 N0.Val->getConstantOperandVal(1) == 1;
3914 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3915 DAG.getIntPtrConstant(IsTrunc));
3918 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3919 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
3920 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
3921 AddToWorkList(Tmp.Val);
3922 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3928 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3929 SDOperand N0 = N->getOperand(0);
3930 MVT VT = N->getValueType(0);
3931 MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3932 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3934 // fold (fp_round_inreg c1fp) -> c1fp
3936 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
3937 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3942 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3943 SDOperand N0 = N->getOperand(0);
3944 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3945 MVT VT = N->getValueType(0);
3947 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
3948 if (N->hasOneUse() &&
3949 N->use_begin()->getSDOperand().getOpcode() == ISD::FP_ROUND)
3952 // fold (fp_extend c1fp) -> c1fp
3953 if (N0CFP && VT != MVT::ppcf128)
3954 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
3956 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3958 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3959 SDOperand In = N0.getOperand(0);
3960 if (In.getValueType() == VT) return In;
3961 if (VT.bitsLT(In.getValueType()))
3962 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3963 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3966 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
3967 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3968 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3969 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3970 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3971 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3972 LN0->getBasePtr(), LN0->getSrcValue(),
3973 LN0->getSrcValueOffset(),
3976 LN0->getAlignment());
3977 CombineTo(N, ExtLoad);
3978 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3979 DAG.getIntPtrConstant(1)),
3980 ExtLoad.getValue(1));
3981 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3987 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3988 SDOperand N0 = N->getOperand(0);
3990 if (isNegatibleForFree(N0, AfterLegalize))
3991 return GetNegatedExpression(N0, DAG, AfterLegalize);
3993 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
3994 // constant pool values.
3995 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3996 N0.getOperand(0).getValueType().isInteger() &&
3997 !N0.getOperand(0).getValueType().isVector()) {
3998 SDOperand Int = N0.getOperand(0);
3999 MVT IntVT = Int.getValueType();
4000 if (IntVT.isInteger() && !IntVT.isVector()) {
4001 Int = DAG.getNode(ISD::XOR, IntVT, Int,
4002 DAG.getConstant(IntVT.getIntegerVTSignBit(), IntVT));
4003 AddToWorkList(Int.Val);
4004 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4011 SDOperand DAGCombiner::visitFABS(SDNode *N) {
4012 SDOperand N0 = N->getOperand(0);
4013 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4014 MVT VT = N->getValueType(0);
4016 // fold (fabs c1) -> fabs(c1)
4017 if (N0CFP && VT != MVT::ppcf128)
4018 return DAG.getNode(ISD::FABS, VT, N0);
4019 // fold (fabs (fabs x)) -> (fabs x)
4020 if (N0.getOpcode() == ISD::FABS)
4021 return N->getOperand(0);
4022 // fold (fabs (fneg x)) -> (fabs x)
4023 // fold (fabs (fcopysign x, y)) -> (fabs x)
4024 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4025 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
4027 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4028 // constant pool values.
4029 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
4030 N0.getOperand(0).getValueType().isInteger() &&
4031 !N0.getOperand(0).getValueType().isVector()) {
4032 SDOperand Int = N0.getOperand(0);
4033 MVT IntVT = Int.getValueType();
4034 if (IntVT.isInteger() && !IntVT.isVector()) {
4035 Int = DAG.getNode(ISD::AND, IntVT, Int,
4036 DAG.getConstant(~IntVT.getIntegerVTSignBit(), IntVT));
4037 AddToWorkList(Int.Val);
4038 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4045 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
4046 SDOperand Chain = N->getOperand(0);
4047 SDOperand N1 = N->getOperand(1);
4048 SDOperand N2 = N->getOperand(2);
4049 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4051 // never taken branch, fold to chain
4052 if (N1C && N1C->isNullValue())
4054 // unconditional branch
4055 if (N1C && N1C->getAPIntValue() == 1)
4056 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
4057 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4059 if (N1.getOpcode() == ISD::SETCC &&
4060 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
4061 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
4062 N1.getOperand(0), N1.getOperand(1), N2);
4067 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4069 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
4070 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4071 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4073 // Use SimplifySetCC to simplify SETCC's.
4074 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
4075 if (Simp.Val) AddToWorkList(Simp.Val);
4077 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
4079 // fold br_cc true, dest -> br dest (unconditional branch)
4080 if (SCCC && !SCCC->isNullValue())
4081 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
4083 // fold br_cc false, dest -> unconditional fall through
4084 if (SCCC && SCCC->isNullValue())
4085 return N->getOperand(0);
4087 // fold to a simpler setcc
4088 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
4089 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
4090 Simp.getOperand(2), Simp.getOperand(0),
4091 Simp.getOperand(1), N->getOperand(4));
4096 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4097 /// pre-indexed load / store when the base pointer is an add or subtract
4098 /// and it has other uses besides the load / store. After the
4099 /// transformation, the new indexed load / store has effectively folded
4100 /// the add / subtract in and all of its other uses are redirected to the
4101 /// new load / store.
4102 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4109 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4110 if (LD->isIndexed())
4112 VT = LD->getMemoryVT();
4113 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4114 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4116 Ptr = LD->getBasePtr();
4117 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4118 if (ST->isIndexed())
4120 VT = ST->getMemoryVT();
4121 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4122 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4124 Ptr = ST->getBasePtr();
4129 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4130 // out. There is no reason to make this a preinc/predec.
4131 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4132 Ptr.Val->hasOneUse())
4135 // Ask the target to do addressing mode selection.
4138 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4139 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4141 // Don't create a indexed load / store with zero offset.
4142 if (isa<ConstantSDNode>(Offset) &&
4143 cast<ConstantSDNode>(Offset)->isNullValue())
4146 // Try turning it into a pre-indexed load / store except when:
4147 // 1) The new base ptr is a frame index.
4148 // 2) If N is a store and the new base ptr is either the same as or is a
4149 // predecessor of the value being stored.
4150 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4151 // that would create a cycle.
4152 // 4) All uses are load / store ops that use it as old base ptr.
4154 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4155 // (plus the implicit offset) to a register to preinc anyway.
4156 if (isa<FrameIndexSDNode>(BasePtr))
4161 SDOperand Val = cast<StoreSDNode>(N)->getValue();
4162 if (Val == BasePtr || BasePtr.Val->isPredecessorOf(Val.Val))
4166 // Now check for #3 and #4.
4167 bool RealUse = false;
4168 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4169 E = Ptr.Val->use_end(); I != E; ++I) {
4170 SDNode *Use = I->getUser();
4173 if (Use->isPredecessorOf(N))
4176 if (!((Use->getOpcode() == ISD::LOAD &&
4177 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4178 (Use->getOpcode() == ISD::STORE &&
4179 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4187 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4189 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4192 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4193 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4195 WorkListRemover DeadNodes(*this);
4197 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4199 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4202 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4206 // Finally, since the node is now dead, remove it from the graph.
4209 // Replace the uses of Ptr with uses of the updated base value.
4210 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4212 removeFromWorkList(Ptr.Val);
4213 DAG.DeleteNode(Ptr.Val);
4218 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4219 /// add / sub of the base pointer node into a post-indexed load / store.
4220 /// The transformation folded the add / subtract into the new indexed
4221 /// load / store effectively and all of its uses are redirected to the
4222 /// new load / store.
4223 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4230 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4231 if (LD->isIndexed())
4233 VT = LD->getMemoryVT();
4234 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4235 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4237 Ptr = LD->getBasePtr();
4238 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4239 if (ST->isIndexed())
4241 VT = ST->getMemoryVT();
4242 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4243 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4245 Ptr = ST->getBasePtr();
4250 if (Ptr.Val->hasOneUse())
4253 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4254 E = Ptr.Val->use_end(); I != E; ++I) {
4255 SDNode *Op = I->getUser();
4257 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4262 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4263 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4265 std::swap(BasePtr, Offset);
4268 // Don't create a indexed load / store with zero offset.
4269 if (isa<ConstantSDNode>(Offset) &&
4270 cast<ConstantSDNode>(Offset)->isNullValue())
4273 // Try turning it into a post-indexed load / store except when
4274 // 1) All uses are load / store ops that use it as base ptr.
4275 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4276 // nor a successor of N. Otherwise, if Op is folded that would
4280 bool TryNext = false;
4281 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4282 EE = BasePtr.Val->use_end(); II != EE; ++II) {
4283 SDNode *Use = II->getUser();
4287 // If all the uses are load / store addresses, then don't do the
4289 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4290 bool RealUse = false;
4291 for (SDNode::use_iterator III = Use->use_begin(),
4292 EEE = Use->use_end(); III != EEE; ++III) {
4293 SDNode *UseUse = III->getUser();
4294 if (!((UseUse->getOpcode() == ISD::LOAD &&
4295 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
4296 (UseUse->getOpcode() == ISD::STORE &&
4297 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
4311 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4312 SDOperand Result = isLoad
4313 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4314 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4317 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4318 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4320 WorkListRemover DeadNodes(*this);
4322 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4324 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4327 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4331 // Finally, since the node is now dead, remove it from the graph.
4334 // Replace the uses of Use with uses of the updated base value.
4335 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4336 Result.getValue(isLoad ? 1 : 0),
4338 removeFromWorkList(Op);
4347 /// InferAlignment - If we can infer some alignment information from this
4348 /// pointer, return it.
4349 static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4350 // If this is a direct reference to a stack slot, use information about the
4351 // stack slot's alignment.
4352 int FrameIdx = 1 << 31;
4353 int64_t FrameOffset = 0;
4354 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4355 FrameIdx = FI->getIndex();
4356 } else if (Ptr.getOpcode() == ISD::ADD &&
4357 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4358 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4359 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4360 FrameOffset = Ptr.getConstantOperandVal(1);
4363 if (FrameIdx != (1 << 31)) {
4364 // FIXME: Handle FI+CST.
4365 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4366 if (MFI.isFixedObjectIndex(FrameIdx)) {
4367 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4369 // The alignment of the frame index can be determined from its offset from
4370 // the incoming frame position. If the frame object is at offset 32 and
4371 // the stack is guaranteed to be 16-byte aligned, then we know that the
4372 // object is 16-byte aligned.
4373 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4374 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4376 // Finally, the frame object itself may have a known alignment. Factor
4377 // the alignment + offset into a new alignment. For example, if we know
4378 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4379 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4380 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4381 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4383 return std::max(Align, FIInfoAlign);
4390 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4391 LoadSDNode *LD = cast<LoadSDNode>(N);
4392 SDOperand Chain = LD->getChain();
4393 SDOperand Ptr = LD->getBasePtr();
4395 // Try to infer better alignment information than the load already has.
4396 if (LD->isUnindexed()) {
4397 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4398 if (Align > LD->getAlignment())
4399 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4400 Chain, Ptr, LD->getSrcValue(),
4401 LD->getSrcValueOffset(), LD->getMemoryVT(),
4402 LD->isVolatile(), Align);
4407 // If load is not volatile and there are no uses of the loaded value (and
4408 // the updated indexed value in case of indexed loads), change uses of the
4409 // chain value into uses of the chain input (i.e. delete the dead load).
4410 if (!LD->isVolatile()) {
4411 if (N->getValueType(1) == MVT::Other) {
4413 if (N->hasNUsesOfValue(0, 0)) {
4414 // It's not safe to use the two value CombineTo variant here. e.g.
4415 // v1, chain2 = load chain1, loc
4416 // v2, chain3 = load chain2, loc
4418 // Now we replace use of chain2 with chain1. This makes the second load
4419 // isomorphic to the one we are deleting, and thus makes this load live.
4420 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4421 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4423 WorkListRemover DeadNodes(*this);
4424 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
4425 if (N->use_empty()) {
4426 removeFromWorkList(N);
4429 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4433 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4434 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4435 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4436 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4437 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4438 DOUT << " and 2 other values\n";
4439 WorkListRemover DeadNodes(*this);
4440 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
4441 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
4442 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
4444 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
4445 removeFromWorkList(N);
4447 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4452 // If this load is directly stored, replace the load value with the stored
4454 // TODO: Handle store large -> read small portion.
4455 // TODO: Handle TRUNCSTORE/LOADEXT
4456 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4457 !LD->isVolatile()) {
4458 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4459 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4460 if (PrevST->getBasePtr() == Ptr &&
4461 PrevST->getValue().getValueType() == N->getValueType(0))
4462 return CombineTo(N, Chain.getOperand(1), Chain);
4467 // Walk up chain skipping non-aliasing memory nodes.
4468 SDOperand BetterChain = FindBetterChain(N, Chain);
4470 // If there is a better chain.
4471 if (Chain != BetterChain) {
4474 // Replace the chain to void dependency.
4475 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4476 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
4477 LD->getSrcValue(), LD->getSrcValueOffset(),
4478 LD->isVolatile(), LD->getAlignment());
4480 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4481 LD->getValueType(0),
4482 BetterChain, Ptr, LD->getSrcValue(),
4483 LD->getSrcValueOffset(),
4486 LD->getAlignment());
4489 // Create token factor to keep old chain connected.
4490 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4491 Chain, ReplLoad.getValue(1));
4493 // Replace uses with load result and token factor. Don't add users
4495 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4499 // Try transforming N to an indexed load.
4500 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4501 return SDOperand(N, 0);
4507 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4508 StoreSDNode *ST = cast<StoreSDNode>(N);
4509 SDOperand Chain = ST->getChain();
4510 SDOperand Value = ST->getValue();
4511 SDOperand Ptr = ST->getBasePtr();
4513 // Try to infer better alignment information than the store already has.
4514 if (ST->isUnindexed()) {
4515 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4516 if (Align > ST->getAlignment())
4517 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4518 ST->getSrcValueOffset(), ST->getMemoryVT(),
4519 ST->isVolatile(), Align);
4523 // If this is a store of a bit convert, store the input value if the
4524 // resultant store does not need a higher alignment than the original.
4525 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
4526 ST->isUnindexed()) {
4527 unsigned Align = ST->getAlignment();
4528 MVT SVT = Value.getOperand(0).getValueType();
4529 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4530 getABITypeAlignment(SVT.getTypeForMVT());
4531 if (Align <= OrigAlign &&
4532 ((!AfterLegalize && !ST->isVolatile()) ||
4533 TLI.isOperationLegal(ISD::STORE, SVT)))
4534 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4535 ST->getSrcValueOffset(), ST->isVolatile(), Align);
4538 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4539 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4540 // NOTE: If the original store is volatile, this transform must not increase
4541 // the number of stores. For example, on x86-32 an f64 can be stored in one
4542 // processor operation but an i64 (which is not legal) requires two. So the
4543 // transform should not be done in this case.
4544 if (Value.getOpcode() != ISD::TargetConstantFP) {
4546 switch (CFP->getValueType(0).getSimpleVT()) {
4547 default: assert(0 && "Unknown FP type");
4548 case MVT::f80: // We don't do this for these yet.
4553 if ((!AfterLegalize && !ST->isVolatile()) ||
4554 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4555 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4556 convertToAPInt().getZExtValue(), MVT::i32);
4557 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4558 ST->getSrcValueOffset(), ST->isVolatile(),
4559 ST->getAlignment());
4563 if ((!AfterLegalize && !ST->isVolatile()) ||
4564 TLI.isOperationLegal(ISD::STORE, MVT::i64)) {
4565 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4566 getZExtValue(), MVT::i64);
4567 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4568 ST->getSrcValueOffset(), ST->isVolatile(),
4569 ST->getAlignment());
4570 } else if (!ST->isVolatile() &&
4571 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4572 // Many FP stores are not made apparent until after legalize, e.g. for
4573 // argument passing. Since this is so common, custom legalize the
4574 // 64-bit integer store into two 32-bit stores.
4575 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
4576 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4577 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
4578 if (TLI.isBigEndian()) std::swap(Lo, Hi);
4580 int SVOffset = ST->getSrcValueOffset();
4581 unsigned Alignment = ST->getAlignment();
4582 bool isVolatile = ST->isVolatile();
4584 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4585 ST->getSrcValueOffset(),
4586 isVolatile, ST->getAlignment());
4587 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4588 DAG.getConstant(4, Ptr.getValueType()));
4590 Alignment = MinAlign(Alignment, 4U);
4591 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4592 SVOffset, isVolatile, Alignment);
4593 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4601 // Walk up chain skipping non-aliasing memory nodes.
4602 SDOperand BetterChain = FindBetterChain(N, Chain);
4604 // If there is a better chain.
4605 if (Chain != BetterChain) {
4606 // Replace the chain to avoid dependency.
4607 SDOperand ReplStore;
4608 if (ST->isTruncatingStore()) {
4609 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4610 ST->getSrcValue(),ST->getSrcValueOffset(),
4612 ST->isVolatile(), ST->getAlignment());
4614 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4615 ST->getSrcValue(), ST->getSrcValueOffset(),
4616 ST->isVolatile(), ST->getAlignment());
4619 // Create token to keep both nodes around.
4621 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4623 // Don't add users to work list.
4624 return CombineTo(N, Token, false);
4628 // Try transforming N to an indexed store.
4629 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4630 return SDOperand(N, 0);
4632 // FIXME: is there such a thing as a truncating indexed store?
4633 if (ST->isTruncatingStore() && ST->isUnindexed() &&
4634 Value.getValueType().isInteger()) {
4635 // See if we can simplify the input to this truncstore with knowledge that
4636 // only the low bits are being used. For example:
4637 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4639 GetDemandedBits(Value,
4640 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4641 ST->getMemoryVT().getSizeInBits()));
4642 AddToWorkList(Value.Val);
4644 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4645 ST->getSrcValueOffset(), ST->getMemoryVT(),
4646 ST->isVolatile(), ST->getAlignment());
4648 // Otherwise, see if we can simplify the operation with
4649 // SimplifyDemandedBits, which only works if the value has a single use.
4650 if (SimplifyDemandedBits(Value,
4651 APInt::getLowBitsSet(
4652 Value.getValueSizeInBits(),
4653 ST->getMemoryVT().getSizeInBits())))
4654 return SDOperand(N, 0);
4657 // If this is a load followed by a store to the same location, then the store
4659 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
4660 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
4661 ST->isUnindexed() && !ST->isVolatile() &&
4662 // There can't be any side effects between the load and store, such as
4664 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
4665 // The store is dead, remove it.
4670 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4671 // truncating store. We can do this even if this is already a truncstore.
4672 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4673 && Value.Val->hasOneUse() && ST->isUnindexed() &&
4674 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4675 ST->getMemoryVT())) {
4676 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4677 ST->getSrcValueOffset(), ST->getMemoryVT(),
4678 ST->isVolatile(), ST->getAlignment());
4684 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4685 SDOperand InVec = N->getOperand(0);
4686 SDOperand InVal = N->getOperand(1);
4687 SDOperand EltNo = N->getOperand(2);
4689 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4690 // vector with the inserted element.
4691 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4692 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4693 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4694 if (Elt < Ops.size())
4696 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4697 &Ops[0], Ops.size());
4703 SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4704 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
4705 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
4706 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
4708 // Perform only after legalization to ensure build_vector / vector_shuffle
4709 // optimizations have already been done.
4710 if (!AfterLegalize) return SDOperand();
4712 SDOperand InVec = N->getOperand(0);
4713 SDOperand EltNo = N->getOperand(1);
4715 if (isa<ConstantSDNode>(EltNo)) {
4716 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4717 bool NewLoad = false;
4718 MVT VT = InVec.getValueType();
4719 MVT EVT = VT.getVectorElementType();
4721 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4722 MVT BCVT = InVec.getOperand(0).getValueType();
4723 if (!BCVT.isVector() || EVT.bitsGT(BCVT.getVectorElementType()))
4725 InVec = InVec.getOperand(0);
4726 EVT = BCVT.getVectorElementType();
4730 LoadSDNode *LN0 = NULL;
4731 if (ISD::isNormalLoad(InVec.Val))
4732 LN0 = cast<LoadSDNode>(InVec);
4733 else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4734 InVec.getOperand(0).getValueType() == EVT &&
4735 ISD::isNormalLoad(InVec.getOperand(0).Val)) {
4736 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4737 } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
4738 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
4740 // (load $addr+1*size)
4741 unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2).
4742 getOperand(Elt))->getValue();
4743 unsigned NumElems = InVec.getOperand(2).getNumOperands();
4744 InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
4745 if (InVec.getOpcode() == ISD::BIT_CONVERT)
4746 InVec = InVec.getOperand(0);
4747 if (ISD::isNormalLoad(InVec.Val)) {
4748 LN0 = cast<LoadSDNode>(InVec);
4749 Elt = (Idx < NumElems) ? Idx : Idx - NumElems;
4752 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
4755 unsigned Align = LN0->getAlignment();
4757 // Check the resultant load doesn't need a higher alignment than the
4759 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4760 getABITypeAlignment(LVT.getTypeForMVT());
4761 if (NewAlign > Align || !TLI.isOperationLegal(ISD::LOAD, LVT))
4766 SDOperand NewPtr = LN0->getBasePtr();
4768 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
4769 MVT PtrType = NewPtr.getValueType();
4770 if (TLI.isBigEndian())
4771 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
4772 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
4773 DAG.getConstant(PtrOff, PtrType));
4775 return DAG.getLoad(LVT, LN0->getChain(), NewPtr,
4776 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4777 LN0->isVolatile(), Align);
4783 SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4784 unsigned NumInScalars = N->getNumOperands();
4785 MVT VT = N->getValueType(0);
4786 unsigned NumElts = VT.getVectorNumElements();
4787 MVT EltType = VT.getVectorElementType();
4789 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4790 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4791 // at most two distinct vectors, turn this into a shuffle node.
4792 SDOperand VecIn1, VecIn2;
4793 for (unsigned i = 0; i != NumInScalars; ++i) {
4794 // Ignore undef inputs.
4795 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4797 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4798 // constant index, bail out.
4799 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4800 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4801 VecIn1 = VecIn2 = SDOperand(0, 0);
4805 // If the input vector type disagrees with the result of the build_vector,
4806 // we can't make a shuffle.
4807 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4808 if (ExtractedFromVec.getValueType() != VT) {
4809 VecIn1 = VecIn2 = SDOperand(0, 0);
4813 // Otherwise, remember this. We allow up to two distinct input vectors.
4814 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4817 if (VecIn1.Val == 0) {
4818 VecIn1 = ExtractedFromVec;
4819 } else if (VecIn2.Val == 0) {
4820 VecIn2 = ExtractedFromVec;
4823 VecIn1 = VecIn2 = SDOperand(0, 0);
4828 // If everything is good, we can make a shuffle operation.
4830 SmallVector<SDOperand, 8> BuildVecIndices;
4831 for (unsigned i = 0; i != NumInScalars; ++i) {
4832 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4833 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4837 SDOperand Extract = N->getOperand(i);
4839 // If extracting from the first vector, just use the index directly.
4840 if (Extract.getOperand(0) == VecIn1) {
4841 BuildVecIndices.push_back(Extract.getOperand(1));
4845 // Otherwise, use InIdx + VecSize
4846 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
4847 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
4850 // Add count and size info.
4851 MVT BuildVecVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
4853 // Return the new VECTOR_SHUFFLE node.
4859 // Use an undef build_vector as input for the second operand.
4860 std::vector<SDOperand> UnOps(NumInScalars,
4861 DAG.getNode(ISD::UNDEF,
4863 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4864 &UnOps[0], UnOps.size());
4865 AddToWorkList(Ops[1].Val);
4867 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4868 &BuildVecIndices[0], BuildVecIndices.size());
4869 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4875 SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4876 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4877 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4878 // inputs come from at most two distinct vectors, turn this into a shuffle
4881 // If we only have one input vector, we don't need to do any concatenation.
4882 if (N->getNumOperands() == 1) {
4883 return N->getOperand(0);
4889 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4890 SDOperand ShufMask = N->getOperand(2);
4891 unsigned NumElts = ShufMask.getNumOperands();
4893 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4894 bool isIdentity = true;
4895 for (unsigned i = 0; i != NumElts; ++i) {
4896 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4897 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4902 if (isIdentity) return N->getOperand(0);
4904 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4906 for (unsigned i = 0; i != NumElts; ++i) {
4907 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4908 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4913 if (isIdentity) return N->getOperand(1);
4915 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4917 bool isUnary = true;
4918 bool isSplat = true;
4920 unsigned BaseIdx = 0;
4921 for (unsigned i = 0; i != NumElts; ++i)
4922 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4923 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4924 int V = (Idx < NumElts) ? 0 : 1;
4938 SDOperand N0 = N->getOperand(0);
4939 SDOperand N1 = N->getOperand(1);
4940 // Normalize unary shuffle so the RHS is undef.
4941 if (isUnary && VecNum == 1)
4944 // If it is a splat, check if the argument vector is a build_vector with
4945 // all scalar elements the same.
4949 // If this is a bit convert that changes the element type of the vector but
4950 // not the number of vector elements, look through it. Be careful not to
4951 // look though conversions that change things like v4f32 to v2f64.
4952 if (V->getOpcode() == ISD::BIT_CONVERT) {
4953 SDOperand ConvInput = V->getOperand(0);
4954 if (ConvInput.getValueType().getVectorNumElements() == NumElts)
4958 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4959 unsigned NumElems = V->getNumOperands();
4960 if (NumElems > BaseIdx) {
4962 bool AllSame = true;
4963 for (unsigned i = 0; i != NumElems; ++i) {
4964 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4965 Base = V->getOperand(i);
4969 // Splat of <u, u, u, u>, return <u, u, u, u>
4972 for (unsigned i = 0; i != NumElems; ++i) {
4973 if (V->getOperand(i) != Base) {
4978 // Splat of <x, x, x, x>, return <x, x, x, x>
4985 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4987 if (isUnary || N0 == N1) {
4988 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4990 SmallVector<SDOperand, 8> MappedOps;
4991 for (unsigned i = 0; i != NumElts; ++i) {
4992 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4993 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4994 MappedOps.push_back(ShufMask.getOperand(i));
4997 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4998 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
5001 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
5002 &MappedOps[0], MappedOps.size());
5003 AddToWorkList(ShufMask.Val);
5004 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
5006 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
5013 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5014 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5015 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5016 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5017 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5018 SDOperand LHS = N->getOperand(0);
5019 SDOperand RHS = N->getOperand(1);
5020 if (N->getOpcode() == ISD::AND) {
5021 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5022 RHS = RHS.getOperand(0);
5023 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5024 std::vector<SDOperand> IdxOps;
5025 unsigned NumOps = RHS.getNumOperands();
5026 unsigned NumElts = NumOps;
5027 MVT EVT = RHS.getValueType().getVectorElementType();
5028 for (unsigned i = 0; i != NumElts; ++i) {
5029 SDOperand Elt = RHS.getOperand(i);
5030 if (!isa<ConstantSDNode>(Elt))
5032 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5033 IdxOps.push_back(DAG.getConstant(i, EVT));
5034 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5035 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
5040 // Let's see if the target supports this vector_shuffle.
5041 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
5044 // Return the new VECTOR_SHUFFLE node.
5045 MVT VT = MVT::getVectorVT(EVT, NumElts);
5046 std::vector<SDOperand> Ops;
5047 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
5049 AddToWorkList(LHS.Val);
5050 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
5051 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5052 &ZeroOps[0], ZeroOps.size()));
5053 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5054 &IdxOps[0], IdxOps.size()));
5055 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
5056 &Ops[0], Ops.size());
5057 if (VT != LHS.getValueType()) {
5058 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
5066 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5067 SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
5068 // After legalize, the target may be depending on adds and other
5069 // binary ops to provide legal ways to construct constants or other
5070 // things. Simplifying them may result in a loss of legality.
5071 if (AfterLegalize) return SDOperand();
5073 MVT VT = N->getValueType(0);
5074 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5076 MVT EltType = VT.getVectorElementType();
5077 SDOperand LHS = N->getOperand(0);
5078 SDOperand RHS = N->getOperand(1);
5079 SDOperand Shuffle = XformToShuffleWithZero(N);
5080 if (Shuffle.Val) return Shuffle;
5082 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5084 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5085 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5086 SmallVector<SDOperand, 8> Ops;
5087 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5088 SDOperand LHSOp = LHS.getOperand(i);
5089 SDOperand RHSOp = RHS.getOperand(i);
5090 // If these two elements can't be folded, bail out.
5091 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5092 LHSOp.getOpcode() != ISD::Constant &&
5093 LHSOp.getOpcode() != ISD::ConstantFP) ||
5094 (RHSOp.getOpcode() != ISD::UNDEF &&
5095 RHSOp.getOpcode() != ISD::Constant &&
5096 RHSOp.getOpcode() != ISD::ConstantFP))
5098 // Can't fold divide by zero.
5099 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5100 N->getOpcode() == ISD::FDIV) {
5101 if ((RHSOp.getOpcode() == ISD::Constant &&
5102 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
5103 (RHSOp.getOpcode() == ISD::ConstantFP &&
5104 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
5107 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
5108 AddToWorkList(Ops.back().Val);
5109 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5110 Ops.back().getOpcode() == ISD::Constant ||
5111 Ops.back().getOpcode() == ISD::ConstantFP) &&
5112 "Scalar binop didn't fold!");
5115 if (Ops.size() == LHS.getNumOperands()) {
5116 MVT VT = LHS.getValueType();
5117 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
5124 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
5125 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5127 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
5128 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5129 // If we got a simplified select_cc node back from SimplifySelectCC, then
5130 // break it down into a new SETCC node, and a new SELECT node, and then return
5131 // the SELECT node, since we were called with a SELECT node.
5133 // Check to see if we got a select_cc back (to turn into setcc/select).
5134 // Otherwise, just return whatever node we got back, like fabs.
5135 if (SCC.getOpcode() == ISD::SELECT_CC) {
5136 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5137 SCC.getOperand(0), SCC.getOperand(1),
5139 AddToWorkList(SETCC.Val);
5140 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5141 SCC.getOperand(3), SETCC);
5148 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5149 /// are the two values being selected between, see if we can simplify the
5150 /// select. Callers of this should assume that TheSelect is deleted if this
5151 /// returns true. As such, they should return the appropriate thing (e.g. the
5152 /// node) back to the top-level of the DAG combiner loop to avoid it being
5155 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
5158 // If this is a select from two identical things, try to pull the operation
5159 // through the select.
5160 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5161 // If this is a load and the token chain is identical, replace the select
5162 // of two loads with a load through a select of the address to load from.
5163 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5164 // constants have been dropped into the constant pool.
5165 if (LHS.getOpcode() == ISD::LOAD &&
5166 // Do not let this transformation reduce the number of volatile loads.
5167 !cast<LoadSDNode>(LHS)->isVolatile() &&
5168 !cast<LoadSDNode>(RHS)->isVolatile() &&
5169 // Token chains must be identical.
5170 LHS.getOperand(0) == RHS.getOperand(0)) {
5171 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5172 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5174 // If this is an EXTLOAD, the VT's must match.
5175 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5176 // FIXME: this conflates two src values, discarding one. This is not
5177 // the right thing to do, but nothing uses srcvalues now. When they do,
5178 // turn SrcValue into a list of locations.
5180 if (TheSelect->getOpcode() == ISD::SELECT) {
5181 // Check that the condition doesn't reach either load. If so, folding
5182 // this will induce a cycle into the DAG.
5183 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5184 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val)) {
5185 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5186 TheSelect->getOperand(0), LLD->getBasePtr(),
5190 // Check that the condition doesn't reach either load. If so, folding
5191 // this will induce a cycle into the DAG.
5192 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5193 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5194 !LLD->isPredecessorOf(TheSelect->getOperand(1).Val) &&
5195 !RLD->isPredecessorOf(TheSelect->getOperand(1).Val)) {
5196 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5197 TheSelect->getOperand(0),
5198 TheSelect->getOperand(1),
5199 LLD->getBasePtr(), RLD->getBasePtr(),
5200 TheSelect->getOperand(4));
5206 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5207 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5208 Addr,LLD->getSrcValue(),
5209 LLD->getSrcValueOffset(),
5211 LLD->getAlignment());
5213 Load = DAG.getExtLoad(LLD->getExtensionType(),
5214 TheSelect->getValueType(0),
5215 LLD->getChain(), Addr, LLD->getSrcValue(),
5216 LLD->getSrcValueOffset(),
5219 LLD->getAlignment());
5221 // Users of the select now use the result of the load.
5222 CombineTo(TheSelect, Load);
5224 // Users of the old loads now use the new load's chain. We know the
5225 // old-load value is dead now.
5226 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5227 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5237 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5238 SDOperand N2, SDOperand N3,
5239 ISD::CondCode CC, bool NotExtCompare) {
5241 MVT VT = N2.getValueType();
5242 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5243 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5244 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5246 // Determine if the condition we're dealing with is constant
5247 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
5248 if (SCC.Val) AddToWorkList(SCC.Val);
5249 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5251 // fold select_cc true, x, y -> x
5252 if (SCCC && !SCCC->isNullValue())
5254 // fold select_cc false, x, y -> y
5255 if (SCCC && SCCC->isNullValue())
5258 // Check to see if we can simplify the select into an fabs node
5259 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5260 // Allow either -0.0 or 0.0
5261 if (CFP->getValueAPF().isZero()) {
5262 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5263 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5264 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5265 N2 == N3.getOperand(0))
5266 return DAG.getNode(ISD::FABS, VT, N0);
5268 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5269 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5270 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5271 N2.getOperand(0) == N3)
5272 return DAG.getNode(ISD::FABS, VT, N3);
5276 // Check to see if we can perform the "gzip trick", transforming
5277 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5278 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5279 N0.getValueType().isInteger() &&
5280 N2.getValueType().isInteger() &&
5281 (N1C->isNullValue() || // (a < 0) ? b : 0
5282 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5283 MVT XType = N0.getValueType();
5284 MVT AType = N2.getValueType();
5285 if (XType.bitsGE(AType)) {
5286 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5287 // single-bit constant.
5288 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5289 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5290 ShCtV = XType.getSizeInBits()-ShCtV-1;
5291 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5292 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5293 AddToWorkList(Shift.Val);
5294 if (XType.bitsGT(AType)) {
5295 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5296 AddToWorkList(Shift.Val);
5298 return DAG.getNode(ISD::AND, AType, Shift, N2);
5300 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5301 DAG.getConstant(XType.getSizeInBits()-1,
5302 TLI.getShiftAmountTy()));
5303 AddToWorkList(Shift.Val);
5304 if (XType.bitsGT(AType)) {
5305 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5306 AddToWorkList(Shift.Val);
5308 return DAG.getNode(ISD::AND, AType, Shift, N2);
5312 // fold select C, 16, 0 -> shl C, 4
5313 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5314 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5316 // If the caller doesn't want us to simplify this into a zext of a compare,
5318 if (NotExtCompare && N2C->getAPIntValue() == 1)
5321 // Get a SetCC of the condition
5322 // FIXME: Should probably make sure that setcc is legal if we ever have a
5323 // target where it isn't.
5324 SDOperand Temp, SCC;
5325 // cast from setcc result type to select result type
5326 if (AfterLegalize) {
5327 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5328 if (N2.getValueType().bitsLT(SCC.getValueType()))
5329 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5331 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5333 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5334 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5336 AddToWorkList(SCC.Val);
5337 AddToWorkList(Temp.Val);
5339 if (N2C->getAPIntValue() == 1)
5341 // shl setcc result by log2 n2c
5342 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5343 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5344 TLI.getShiftAmountTy()));
5347 // Check to see if this is the equivalent of setcc
5348 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5349 // otherwise, go ahead with the folds.
5350 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5351 MVT XType = N0.getValueType();
5352 if (!AfterLegalize ||
5353 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
5354 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5355 if (Res.getValueType() != VT)
5356 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5360 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5361 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5363 TLI.isOperationLegal(ISD::CTLZ, XType))) {
5364 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5365 return DAG.getNode(ISD::SRL, XType, Ctlz,
5366 DAG.getConstant(Log2_32(XType.getSizeInBits()),
5367 TLI.getShiftAmountTy()));
5369 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5370 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5371 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5373 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5374 DAG.getConstant(~0ULL, XType));
5375 return DAG.getNode(ISD::SRL, XType,
5376 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5377 DAG.getConstant(XType.getSizeInBits()-1,
5378 TLI.getShiftAmountTy()));
5380 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5381 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5382 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5383 DAG.getConstant(XType.getSizeInBits()-1,
5384 TLI.getShiftAmountTy()));
5385 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5389 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5390 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5391 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5392 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5393 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
5394 MVT XType = N0.getValueType();
5395 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5396 DAG.getConstant(XType.getSizeInBits()-1,
5397 TLI.getShiftAmountTy()));
5398 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5399 AddToWorkList(Shift.Val);
5400 AddToWorkList(Add.Val);
5401 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5403 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5404 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5405 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5406 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5407 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5408 MVT XType = N0.getValueType();
5409 if (SubC->isNullValue() && XType.isInteger()) {
5410 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5411 DAG.getConstant(XType.getSizeInBits()-1,
5412 TLI.getShiftAmountTy()));
5413 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5414 AddToWorkList(Shift.Val);
5415 AddToWorkList(Add.Val);
5416 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5424 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5425 SDOperand DAGCombiner::SimplifySetCC(MVT VT, SDOperand N0,
5426 SDOperand N1, ISD::CondCode Cond,
5427 bool foldBooleans) {
5428 TargetLowering::DAGCombinerInfo
5429 DagCombineInfo(DAG, !AfterLegalize, false, this);
5430 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5433 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5434 /// return a DAG expression to select that will generate the same value by
5435 /// multiplying by a magic number. See:
5436 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5437 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5438 std::vector<SDNode*> Built;
5439 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5441 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5447 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5448 /// return a DAG expression to select that will generate the same value by
5449 /// multiplying by a magic number. See:
5450 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5451 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5452 std::vector<SDNode*> Built;
5453 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5455 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5461 /// FindBaseOffset - Return true if base is known not to alias with anything
5462 /// but itself. Provides base object and offset as results.
5463 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5464 // Assume it is a primitive operation.
5465 Base = Ptr; Offset = 0;
5467 // If it's an adding a simple constant then integrate the offset.
5468 if (Base.getOpcode() == ISD::ADD) {
5469 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5470 Base = Base.getOperand(0);
5471 Offset += C->getValue();
5475 // If it's any of the following then it can't alias with anything but itself.
5476 return isa<FrameIndexSDNode>(Base) ||
5477 isa<ConstantPoolSDNode>(Base) ||
5478 isa<GlobalAddressSDNode>(Base);
5481 /// isAlias - Return true if there is any possibility that the two addresses
5483 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5484 const Value *SrcValue1, int SrcValueOffset1,
5485 SDOperand Ptr2, int64_t Size2,
5486 const Value *SrcValue2, int SrcValueOffset2)
5488 // If they are the same then they must be aliases.
5489 if (Ptr1 == Ptr2) return true;
5491 // Gather base node and offset information.
5492 SDOperand Base1, Base2;
5493 int64_t Offset1, Offset2;
5494 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5495 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5497 // If they have a same base address then...
5498 if (Base1 == Base2) {
5499 // Check to see if the addresses overlap.
5500 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5503 // If we know both bases then they can't alias.
5504 if (KnownBase1 && KnownBase2) return false;
5506 if (CombinerGlobalAA) {
5507 // Use alias analysis information.
5508 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5509 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5510 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
5511 AliasAnalysis::AliasResult AAResult =
5512 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5513 if (AAResult == AliasAnalysis::NoAlias)
5517 // Otherwise we have to assume they alias.
5521 /// FindAliasInfo - Extracts the relevant alias information from the memory
5522 /// node. Returns true if the operand was a load.
5523 bool DAGCombiner::FindAliasInfo(SDNode *N,
5524 SDOperand &Ptr, int64_t &Size,
5525 const Value *&SrcValue, int &SrcValueOffset) {
5526 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5527 Ptr = LD->getBasePtr();
5528 Size = LD->getMemoryVT().getSizeInBits() >> 3;
5529 SrcValue = LD->getSrcValue();
5530 SrcValueOffset = LD->getSrcValueOffset();
5532 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5533 Ptr = ST->getBasePtr();
5534 Size = ST->getMemoryVT().getSizeInBits() >> 3;
5535 SrcValue = ST->getSrcValue();
5536 SrcValueOffset = ST->getSrcValueOffset();
5538 assert(0 && "FindAliasInfo expected a memory operand");
5544 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5545 /// looking for aliasing nodes and adding them to the Aliases vector.
5546 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5547 SmallVector<SDOperand, 8> &Aliases) {
5548 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5549 std::set<SDNode *> Visited; // Visited node set.
5551 // Get alias information for node.
5554 const Value *SrcValue;
5556 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5559 Chains.push_back(OriginalChain);
5561 // Look at each chain and determine if it is an alias. If so, add it to the
5562 // aliases list. If not, then continue up the chain looking for the next
5564 while (!Chains.empty()) {
5565 SDOperand Chain = Chains.back();
5568 // Don't bother if we've been before.
5569 if (Visited.find(Chain.Val) != Visited.end()) continue;
5570 Visited.insert(Chain.Val);
5572 switch (Chain.getOpcode()) {
5573 case ISD::EntryToken:
5574 // Entry token is ideal chain operand, but handled in FindBetterChain.
5579 // Get alias information for Chain.
5582 const Value *OpSrcValue;
5583 int OpSrcValueOffset;
5584 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5585 OpSrcValue, OpSrcValueOffset);
5587 // If chain is alias then stop here.
5588 if (!(IsLoad && IsOpLoad) &&
5589 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5590 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5591 Aliases.push_back(Chain);
5593 // Look further up the chain.
5594 Chains.push_back(Chain.getOperand(0));
5595 // Clean up old chain.
5596 AddToWorkList(Chain.Val);
5601 case ISD::TokenFactor:
5602 // We have to check each of the operands of the token factor, so we queue
5603 // then up. Adding the operands to the queue (stack) in reverse order
5604 // maintains the original order and increases the likelihood that getNode
5605 // will find a matching token factor (CSE.)
5606 for (unsigned n = Chain.getNumOperands(); n;)
5607 Chains.push_back(Chain.getOperand(--n));
5608 // Eliminate the token factor if we can.
5609 AddToWorkList(Chain.Val);
5613 // For all other instructions we will just have to take what we can get.
5614 Aliases.push_back(Chain);
5620 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5621 /// for a better chain (aliasing node.)
5622 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5623 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5625 // Accumulate all the aliases to this node.
5626 GatherAllAliases(N, OldChain, Aliases);
5628 if (Aliases.size() == 0) {
5629 // If no operands then chain to entry token.
5630 return DAG.getEntryNode();
5631 } else if (Aliases.size() == 1) {
5632 // If a single operand then chain to it. We don't need to revisit it.
5636 // Construct a custom tailored token factor.
5637 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5638 &Aliases[0], Aliases.size());
5640 // Make sure the old chain gets cleaned up.
5641 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5646 // SelectionDAG::Combine - This is the entry point for the file.
5648 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5649 if (!RunningAfterLegalize && ViewDAGCombine1)
5651 if (RunningAfterLegalize && ViewDAGCombine2)
5653 /// run - This is the main entry point to this class.
5655 DAGCombiner(*this, AA).Run(RunningAfterLegalize);