1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Nate Begeman and is distributed under the
6 // University of Illinois Open Source 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 // FIXME: Missing folds
14 // sdiv, udiv, srem, urem (X, const) where X is an integer can be expanded into
15 // a sequence of multiplies, shifts, and adds. This should be controlled by
16 // some kind of hint from the target that int div is expensive.
17 // various folds of mulh[s,u] by constants such as -1, powers of 2, etc.
19 // FIXME: select C, pow2, pow2 -> something smart
20 // FIXME: trunc(select X, Y, Z) -> select X, trunc(Y), trunc(Z)
21 // FIXME: Dead stores -> nuke
22 // FIXME: shr X, (and Y,31) -> shr X, Y (TRICKY!)
23 // FIXME: mul (x, const) -> shifts + adds
24 // FIXME: undef values
25 // FIXME: divide by zero is currently left unfolded. do we want to turn this
27 // FIXME: select ne (select cc, 1, 0), 0, true, false -> select cc, true, false
29 //===----------------------------------------------------------------------===//
31 #define DEBUG_TYPE "dagcombine"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/Analysis/AliasAnalysis.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/MathExtras.h"
47 STATISTIC(NodesCombined , "Number of dag nodes combined");
48 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
49 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
54 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
55 cl::desc("Pop up a window to show dags before the first "
58 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
59 cl::desc("Pop up a window to show dags before the second "
62 static const bool ViewDAGCombine1 = false;
63 static const bool ViewDAGCombine2 = false;
67 CombinerAA("combiner-alias-analysis", cl::Hidden,
68 cl::desc("Turn on alias analysis during testing"));
71 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
72 cl::desc("Include global information in alias analysis"));
74 //------------------------------ DAGCombiner ---------------------------------//
76 class VISIBILITY_HIDDEN DAGCombiner {
81 // Worklist of all of the nodes that need to be simplified.
82 std::vector<SDNode*> WorkList;
84 // AA - Used for DAG load/store alias analysis.
87 /// AddUsersToWorkList - When an instruction is simplified, add all users of
88 /// the instruction to the work lists because they might get more simplified
91 void AddUsersToWorkList(SDNode *N) {
92 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
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),
105 /// AddToWorkList - Add to the work list making sure it's instance is at the
106 /// the back (next to be processed.)
107 void AddToWorkList(SDNode *N) {
108 removeFromWorkList(N);
109 WorkList.push_back(N);
112 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
114 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
116 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
117 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
118 DOUT << " and " << NumTo-1 << " other values\n";
119 std::vector<SDNode*> NowDead;
120 DAG.ReplaceAllUsesWith(N, To, &NowDead);
123 // Push the new nodes and any users onto the worklist
124 for (unsigned i = 0, e = NumTo; i != e; ++i) {
125 AddToWorkList(To[i].Val);
126 AddUsersToWorkList(To[i].Val);
130 // Nodes can be reintroduced into the worklist. Make sure we do not
131 // process a node that has been replaced.
132 removeFromWorkList(N);
133 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
134 removeFromWorkList(NowDead[i]);
136 // Finally, since the node is now dead, remove it from the graph.
138 return SDOperand(N, 0);
141 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
142 return CombineTo(N, &Res, 1, AddTo);
145 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
147 SDOperand To[] = { Res0, Res1 };
148 return CombineTo(N, To, 2, AddTo);
152 /// SimplifyDemandedBits - Check the specified integer node value to see if
153 /// it can be simplified or if things it uses can be simplified by bit
154 /// propagation. If so, return true.
155 bool SimplifyDemandedBits(SDOperand Op) {
156 TargetLowering::TargetLoweringOpt TLO(DAG);
157 uint64_t KnownZero, KnownOne;
158 uint64_t Demanded = MVT::getIntVTBitMask(Op.getValueType());
159 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
163 AddToWorkList(Op.Val);
165 // Replace the old value with the new one.
167 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
168 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
171 std::vector<SDNode*> NowDead;
172 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, NowDead);
174 // Push the new node and any (possibly new) users onto the worklist.
175 AddToWorkList(TLO.New.Val);
176 AddUsersToWorkList(TLO.New.Val);
178 // Nodes can end up on the worklist more than once. Make sure we do
179 // not process a node that has been replaced.
180 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
181 removeFromWorkList(NowDead[i]);
183 // Finally, if the node is now dead, remove it from the graph. The node
184 // may not be dead if the replacement process recursively simplified to
185 // something else needing this node.
186 if (TLO.Old.Val->use_empty()) {
187 removeFromWorkList(TLO.Old.Val);
189 // If the operands of this node are only used by the node, they will now
190 // be dead. Make sure to visit them first to delete dead nodes early.
191 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
192 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
193 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
195 DAG.DeleteNode(TLO.Old.Val);
200 bool CombineToPreIndexedLoadStore(SDNode *N);
201 bool CombineToPostIndexedLoadStore(SDNode *N);
204 /// visit - call the node-specific routine that knows how to fold each
205 /// particular type of node.
206 SDOperand visit(SDNode *N);
208 // Visitation implementation - Implement dag node combining for different
209 // node types. The semantics are as follows:
211 // SDOperand.Val == 0 - No change was made
212 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
213 // otherwise - N should be replaced by the returned Operand.
215 SDOperand visitTokenFactor(SDNode *N);
216 SDOperand visitADD(SDNode *N);
217 SDOperand visitSUB(SDNode *N);
218 SDOperand visitADDC(SDNode *N);
219 SDOperand visitADDE(SDNode *N);
220 SDOperand visitMUL(SDNode *N);
221 SDOperand visitSDIV(SDNode *N);
222 SDOperand visitUDIV(SDNode *N);
223 SDOperand visitSREM(SDNode *N);
224 SDOperand visitUREM(SDNode *N);
225 SDOperand visitMULHU(SDNode *N);
226 SDOperand visitMULHS(SDNode *N);
227 SDOperand visitAND(SDNode *N);
228 SDOperand visitOR(SDNode *N);
229 SDOperand visitXOR(SDNode *N);
230 SDOperand SimplifyVBinOp(SDNode *N);
231 SDOperand visitSHL(SDNode *N);
232 SDOperand visitSRA(SDNode *N);
233 SDOperand visitSRL(SDNode *N);
234 SDOperand visitCTLZ(SDNode *N);
235 SDOperand visitCTTZ(SDNode *N);
236 SDOperand visitCTPOP(SDNode *N);
237 SDOperand visitSELECT(SDNode *N);
238 SDOperand visitSELECT_CC(SDNode *N);
239 SDOperand visitSETCC(SDNode *N);
240 SDOperand visitSIGN_EXTEND(SDNode *N);
241 SDOperand visitZERO_EXTEND(SDNode *N);
242 SDOperand visitANY_EXTEND(SDNode *N);
243 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
244 SDOperand visitTRUNCATE(SDNode *N);
245 SDOperand visitBIT_CONVERT(SDNode *N);
246 SDOperand visitFADD(SDNode *N);
247 SDOperand visitFSUB(SDNode *N);
248 SDOperand visitFMUL(SDNode *N);
249 SDOperand visitFDIV(SDNode *N);
250 SDOperand visitFREM(SDNode *N);
251 SDOperand visitFCOPYSIGN(SDNode *N);
252 SDOperand visitSINT_TO_FP(SDNode *N);
253 SDOperand visitUINT_TO_FP(SDNode *N);
254 SDOperand visitFP_TO_SINT(SDNode *N);
255 SDOperand visitFP_TO_UINT(SDNode *N);
256 SDOperand visitFP_ROUND(SDNode *N);
257 SDOperand visitFP_ROUND_INREG(SDNode *N);
258 SDOperand visitFP_EXTEND(SDNode *N);
259 SDOperand visitFNEG(SDNode *N);
260 SDOperand visitFABS(SDNode *N);
261 SDOperand visitBRCOND(SDNode *N);
262 SDOperand visitBR_CC(SDNode *N);
263 SDOperand visitLOAD(SDNode *N);
264 SDOperand visitSTORE(SDNode *N);
265 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
266 SDOperand visitBUILD_VECTOR(SDNode *N);
267 SDOperand visitCONCAT_VECTORS(SDNode *N);
268 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
270 SDOperand XformToShuffleWithZero(SDNode *N);
271 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
273 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
274 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
275 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
276 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
277 SDOperand N3, ISD::CondCode CC,
278 bool NotExtCompare = false);
279 SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
280 ISD::CondCode Cond, bool foldBooleans = true);
281 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT::ValueType);
282 SDOperand BuildSDIV(SDNode *N);
283 SDOperand BuildUDIV(SDNode *N);
284 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
285 SDOperand ReduceLoadWidth(SDNode *N);
287 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
288 /// looking for aliasing nodes and adding them to the Aliases vector.
289 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
290 SmallVector<SDOperand, 8> &Aliases);
292 /// isAlias - Return true if there is any possibility that the two addresses
294 bool isAlias(SDOperand Ptr1, int64_t Size1,
295 const Value *SrcValue1, int SrcValueOffset1,
296 SDOperand Ptr2, int64_t Size2,
297 const Value *SrcValue2, int SrcValueOffset2);
299 /// FindAliasInfo - Extracts the relevant alias information from the memory
300 /// node. Returns true if the operand was a load.
301 bool FindAliasInfo(SDNode *N,
302 SDOperand &Ptr, int64_t &Size,
303 const Value *&SrcValue, int &SrcValueOffset);
305 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
306 /// looking for a better chain (aliasing node.)
307 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
310 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
312 TLI(D.getTargetLoweringInfo()),
313 AfterLegalize(false),
316 /// Run - runs the dag combiner on all nodes in the work list
317 void Run(bool RunningAfterLegalize);
321 //===----------------------------------------------------------------------===//
322 // TargetLowering::DAGCombinerInfo implementation
323 //===----------------------------------------------------------------------===//
325 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
326 ((DAGCombiner*)DC)->AddToWorkList(N);
329 SDOperand TargetLowering::DAGCombinerInfo::
330 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
331 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
334 SDOperand TargetLowering::DAGCombinerInfo::
335 CombineTo(SDNode *N, SDOperand Res) {
336 return ((DAGCombiner*)DC)->CombineTo(N, Res);
340 SDOperand TargetLowering::DAGCombinerInfo::
341 CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
342 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
346 //===----------------------------------------------------------------------===//
348 //===----------------------------------------------------------------------===//
350 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
351 /// specified expression for the same cost as the expression itself, or 2 if we
352 /// can compute the negated form more cheaply than the expression itself.
353 static char isNegatibleForFree(SDOperand Op, unsigned Depth = 0) {
354 // fneg is removable even if it has multiple uses.
355 if (Op.getOpcode() == ISD::FNEG) return 2;
357 // Don't allow anything with multiple uses.
358 if (!Op.hasOneUse()) return 0;
360 // Don't recurse exponentially.
361 if (Depth > 6) return 0;
363 switch (Op.getOpcode()) {
364 default: return false;
365 case ISD::ConstantFP:
368 // FIXME: determine better conditions for this xform.
369 if (!UnsafeFPMath) return 0;
372 if (char V = isNegatibleForFree(Op.getOperand(0), Depth+1))
375 return isNegatibleForFree(Op.getOperand(1), Depth+1);
377 // We can't turn -(A-B) into B-A when we honor signed zeros.
378 if (!UnsafeFPMath) return 0;
385 if (HonorSignDependentRoundingFPMath()) return 0;
387 // -(X*Y) -> (-X * Y) or (X*-Y)
388 if (char V = isNegatibleForFree(Op.getOperand(0), Depth+1))
391 return isNegatibleForFree(Op.getOperand(1), Depth+1);
396 return isNegatibleForFree(Op.getOperand(0), Depth+1);
400 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
401 /// returns the newly negated expression.
402 static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
403 unsigned Depth = 0) {
404 // fneg is removable even if it has multiple uses.
405 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
407 // Don't allow anything with multiple uses.
408 assert(Op.hasOneUse() && "Unknown reuse!");
410 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
411 switch (Op.getOpcode()) {
412 default: assert(0 && "Unknown code");
413 case ISD::ConstantFP:
414 return DAG.getConstantFP(-cast<ConstantFPSDNode>(Op)->getValue(),
417 // FIXME: determine better conditions for this xform.
418 assert(UnsafeFPMath);
421 if (isNegatibleForFree(Op.getOperand(0), Depth+1))
422 return DAG.getNode(ISD::FSUB, Op.getValueType(),
423 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1),
426 return DAG.getNode(ISD::FSUB, Op.getValueType(),
427 GetNegatedExpression(Op.getOperand(1), DAG, Depth+1),
430 // We can't turn -(A-B) into B-A when we honor signed zeros.
431 assert(UnsafeFPMath);
434 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
439 assert(!HonorSignDependentRoundingFPMath());
442 if (isNegatibleForFree(Op.getOperand(0), Depth+1))
443 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
444 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1),
448 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
450 GetNegatedExpression(Op.getOperand(1), DAG, Depth+1));
455 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
456 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1));
461 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
462 // that selects between the values 1 and 0, making it equivalent to a setcc.
463 // Also, set the incoming LHS, RHS, and CC references to the appropriate
464 // nodes based on the type of node we are checking. This simplifies life a
465 // bit for the callers.
466 static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
468 if (N.getOpcode() == ISD::SETCC) {
469 LHS = N.getOperand(0);
470 RHS = N.getOperand(1);
471 CC = N.getOperand(2);
474 if (N.getOpcode() == ISD::SELECT_CC &&
475 N.getOperand(2).getOpcode() == ISD::Constant &&
476 N.getOperand(3).getOpcode() == ISD::Constant &&
477 cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
478 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
479 LHS = N.getOperand(0);
480 RHS = N.getOperand(1);
481 CC = N.getOperand(4);
487 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
488 // one use. If this is true, it allows the users to invert the operation for
489 // free when it is profitable to do so.
490 static bool isOneUseSetCC(SDOperand N) {
491 SDOperand N0, N1, N2;
492 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
497 SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
498 MVT::ValueType VT = N0.getValueType();
499 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
500 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
501 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
502 if (isa<ConstantSDNode>(N1)) {
503 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
504 AddToWorkList(OpNode.Val);
505 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
506 } else if (N0.hasOneUse()) {
507 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
508 AddToWorkList(OpNode.Val);
509 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
512 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
513 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
514 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
515 if (isa<ConstantSDNode>(N0)) {
516 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
517 AddToWorkList(OpNode.Val);
518 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
519 } else if (N1.hasOneUse()) {
520 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
521 AddToWorkList(OpNode.Val);
522 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
528 //===----------------------------------------------------------------------===//
529 // Main DAG Combiner implementation
530 //===----------------------------------------------------------------------===//
532 void DAGCombiner::Run(bool RunningAfterLegalize) {
533 // set the instance variable, so that the various visit routines may use it.
534 AfterLegalize = RunningAfterLegalize;
536 // Add all the dag nodes to the worklist.
537 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
538 E = DAG.allnodes_end(); I != E; ++I)
539 WorkList.push_back(I);
541 // Create a dummy node (which is not added to allnodes), that adds a reference
542 // to the root node, preventing it from being deleted, and tracking any
543 // changes of the root.
544 HandleSDNode Dummy(DAG.getRoot());
546 // The root of the dag may dangle to deleted nodes until the dag combiner is
547 // done. Set it to null to avoid confusion.
548 DAG.setRoot(SDOperand());
550 /// DagCombineInfo - Expose the DAG combiner to the target combiner impls.
551 TargetLowering::DAGCombinerInfo
552 DagCombineInfo(DAG, !RunningAfterLegalize, false, this);
554 // while the worklist isn't empty, inspect the node on the end of it and
555 // try and combine it.
556 while (!WorkList.empty()) {
557 SDNode *N = WorkList.back();
560 // If N has no uses, it is dead. Make sure to revisit all N's operands once
561 // N is deleted from the DAG, since they too may now be dead or may have a
562 // reduced number of uses, allowing other xforms.
563 if (N->use_empty() && N != &Dummy) {
564 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
565 AddToWorkList(N->getOperand(i).Val);
571 SDOperand RV = visit(N);
573 // If nothing happened, try a target-specific DAG combine.
575 assert(N->getOpcode() != ISD::DELETED_NODE &&
576 "Node was deleted but visit returned NULL!");
577 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
578 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode()))
579 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
584 // If we get back the same node we passed in, rather than a new node or
585 // zero, we know that the node must have defined multiple values and
586 // CombineTo was used. Since CombineTo takes care of the worklist
587 // mechanics for us, we have no work to do in this case.
589 assert(N->getOpcode() != ISD::DELETED_NODE &&
590 RV.Val->getOpcode() != ISD::DELETED_NODE &&
591 "Node was deleted but visit returned new node!");
593 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
594 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
596 std::vector<SDNode*> NowDead;
597 if (N->getNumValues() == RV.Val->getNumValues())
598 DAG.ReplaceAllUsesWith(N, RV.Val, &NowDead);
600 assert(N->getValueType(0) == RV.getValueType() && "Type mismatch");
602 DAG.ReplaceAllUsesWith(N, &OpV, &NowDead);
605 // Push the new node and any users onto the worklist
606 AddToWorkList(RV.Val);
607 AddUsersToWorkList(RV.Val);
609 // Nodes can be reintroduced into the worklist. Make sure we do not
610 // process a node that has been replaced.
611 removeFromWorkList(N);
612 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
613 removeFromWorkList(NowDead[i]);
615 // Finally, since the node is now dead, remove it from the graph.
621 // If the root changed (e.g. it was a dead load, update the root).
622 DAG.setRoot(Dummy.getValue());
625 SDOperand DAGCombiner::visit(SDNode *N) {
626 switch(N->getOpcode()) {
628 case ISD::TokenFactor: return visitTokenFactor(N);
629 case ISD::ADD: return visitADD(N);
630 case ISD::SUB: return visitSUB(N);
631 case ISD::ADDC: return visitADDC(N);
632 case ISD::ADDE: return visitADDE(N);
633 case ISD::MUL: return visitMUL(N);
634 case ISD::SDIV: return visitSDIV(N);
635 case ISD::UDIV: return visitUDIV(N);
636 case ISD::SREM: return visitSREM(N);
637 case ISD::UREM: return visitUREM(N);
638 case ISD::MULHU: return visitMULHU(N);
639 case ISD::MULHS: return visitMULHS(N);
640 case ISD::AND: return visitAND(N);
641 case ISD::OR: return visitOR(N);
642 case ISD::XOR: return visitXOR(N);
643 case ISD::SHL: return visitSHL(N);
644 case ISD::SRA: return visitSRA(N);
645 case ISD::SRL: return visitSRL(N);
646 case ISD::CTLZ: return visitCTLZ(N);
647 case ISD::CTTZ: return visitCTTZ(N);
648 case ISD::CTPOP: return visitCTPOP(N);
649 case ISD::SELECT: return visitSELECT(N);
650 case ISD::SELECT_CC: return visitSELECT_CC(N);
651 case ISD::SETCC: return visitSETCC(N);
652 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
653 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
654 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
655 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
656 case ISD::TRUNCATE: return visitTRUNCATE(N);
657 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
658 case ISD::FADD: return visitFADD(N);
659 case ISD::FSUB: return visitFSUB(N);
660 case ISD::FMUL: return visitFMUL(N);
661 case ISD::FDIV: return visitFDIV(N);
662 case ISD::FREM: return visitFREM(N);
663 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
664 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
665 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
666 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
667 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
668 case ISD::FP_ROUND: return visitFP_ROUND(N);
669 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
670 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
671 case ISD::FNEG: return visitFNEG(N);
672 case ISD::FABS: return visitFABS(N);
673 case ISD::BRCOND: return visitBRCOND(N);
674 case ISD::BR_CC: return visitBR_CC(N);
675 case ISD::LOAD: return visitLOAD(N);
676 case ISD::STORE: return visitSTORE(N);
677 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
678 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
679 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
680 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
685 /// getInputChainForNode - Given a node, return its input chain if it has one,
686 /// otherwise return a null sd operand.
687 static SDOperand getInputChainForNode(SDNode *N) {
688 if (unsigned NumOps = N->getNumOperands()) {
689 if (N->getOperand(0).getValueType() == MVT::Other)
690 return N->getOperand(0);
691 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
692 return N->getOperand(NumOps-1);
693 for (unsigned i = 1; i < NumOps-1; ++i)
694 if (N->getOperand(i).getValueType() == MVT::Other)
695 return N->getOperand(i);
697 return SDOperand(0, 0);
700 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
701 // If N has two operands, where one has an input chain equal to the other,
702 // the 'other' chain is redundant.
703 if (N->getNumOperands() == 2) {
704 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
705 return N->getOperand(0);
706 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
707 return N->getOperand(1);
710 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
711 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
712 SmallPtrSet<SDNode*, 16> SeenOps;
713 bool Changed = false; // If we should replace this token factor.
715 // Start out with this token factor.
718 // Iterate through token factors. The TFs grows when new token factors are
720 for (unsigned i = 0; i < TFs.size(); ++i) {
723 // Check each of the operands.
724 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
725 SDOperand Op = TF->getOperand(i);
727 switch (Op.getOpcode()) {
728 case ISD::EntryToken:
729 // Entry tokens don't need to be added to the list. They are
734 case ISD::TokenFactor:
735 if ((CombinerAA || Op.hasOneUse()) &&
736 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
737 // Queue up for processing.
738 TFs.push_back(Op.Val);
739 // Clean up in case the token factor is removed.
740 AddToWorkList(Op.Val);
747 // Only add if it isn't already in the list.
748 if (SeenOps.insert(Op.Val))
759 // If we've change things around then replace token factor.
761 if (Ops.size() == 0) {
762 // The entry token is the only possible outcome.
763 Result = DAG.getEntryNode();
765 // New and improved token factor.
766 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
769 // Don't add users to work list.
770 return CombineTo(N, Result, false);
777 SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
778 MVT::ValueType VT = N0.getValueType();
779 SDOperand N00 = N0.getOperand(0);
780 SDOperand N01 = N0.getOperand(1);
781 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
782 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
783 isa<ConstantSDNode>(N00.getOperand(1))) {
784 N0 = DAG.getNode(ISD::ADD, VT,
785 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
786 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
787 return DAG.getNode(ISD::ADD, VT, N0, N1);
793 SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
795 MVT::ValueType VT = N->getValueType(0);
796 unsigned Opc = N->getOpcode();
797 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
798 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
799 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
800 ISD::CondCode CC = ISD::SETCC_INVALID;
802 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
804 SDOperand CCOp = Slct.getOperand(0);
805 if (CCOp.getOpcode() == ISD::SETCC)
806 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
809 bool DoXform = false;
811 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
813 if (LHS.getOpcode() == ISD::Constant &&
814 cast<ConstantSDNode>(LHS)->isNullValue())
816 else if (CC != ISD::SETCC_INVALID &&
817 RHS.getOpcode() == ISD::Constant &&
818 cast<ConstantSDNode>(RHS)->isNullValue()) {
820 bool isInt = MVT::isInteger(isSlctCC ? Slct.getOperand(0).getValueType()
821 : Slct.getOperand(0).getOperand(0).getValueType());
822 CC = ISD::getSetCCInverse(CC, isInt);
828 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
830 return DAG.getSelectCC(OtherOp, Result,
831 Slct.getOperand(0), Slct.getOperand(1), CC);
832 SDOperand CCOp = Slct.getOperand(0);
834 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
835 CCOp.getOperand(1), CC);
836 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
841 SDOperand DAGCombiner::visitADD(SDNode *N) {
842 SDOperand N0 = N->getOperand(0);
843 SDOperand N1 = N->getOperand(1);
844 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
845 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
846 MVT::ValueType VT = N0.getValueType();
849 SDOperand FoldedVOp = SimplifyVBinOp(N);
850 if (FoldedVOp.Val) return FoldedVOp;
852 // fold (add c1, c2) -> c1+c2
854 return DAG.getNode(ISD::ADD, VT, N0, N1);
855 // canonicalize constant to RHS
857 return DAG.getNode(ISD::ADD, VT, N1, N0);
858 // fold (add x, 0) -> x
859 if (N1C && N1C->isNullValue())
861 // fold ((c1-A)+c2) -> (c1+c2)-A
862 if (N1C && N0.getOpcode() == ISD::SUB)
863 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
864 return DAG.getNode(ISD::SUB, VT,
865 DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
868 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
871 // fold ((0-A) + B) -> B-A
872 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
873 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
874 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
875 // fold (A + (0-B)) -> A-B
876 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
877 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
878 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
879 // fold (A+(B-A)) -> B
880 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
881 return N1.getOperand(0);
883 if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
884 return SDOperand(N, 0);
886 // fold (a+b) -> (a|b) iff a and b share no bits.
887 if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
888 uint64_t LHSZero, LHSOne;
889 uint64_t RHSZero, RHSOne;
890 uint64_t Mask = MVT::getIntVTBitMask(VT);
891 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
893 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
895 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
896 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
897 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
898 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
899 return DAG.getNode(ISD::OR, VT, N0, N1);
903 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
904 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
905 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
906 if (Result.Val) return Result;
908 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
909 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
910 if (Result.Val) return Result;
913 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
914 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
915 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
916 if (Result.Val) return Result;
918 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
919 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
920 if (Result.Val) return Result;
923 // If either operand is undef, the result is undef
924 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
925 return DAG.getNode(ISD::UNDEF, VT);
930 SDOperand DAGCombiner::visitADDC(SDNode *N) {
931 SDOperand N0 = N->getOperand(0);
932 SDOperand N1 = N->getOperand(1);
933 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
934 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
935 MVT::ValueType VT = N0.getValueType();
937 // If the flag result is dead, turn this into an ADD.
938 if (N->hasNUsesOfValue(0, 1))
939 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
940 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
942 // canonicalize constant to RHS.
944 SDOperand Ops[] = { N1, N0 };
945 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
948 // fold (addc x, 0) -> x + no carry out
949 if (N1C && N1C->isNullValue())
950 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
952 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
953 uint64_t LHSZero, LHSOne;
954 uint64_t RHSZero, RHSOne;
955 uint64_t Mask = MVT::getIntVTBitMask(VT);
956 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
958 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
960 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
961 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
962 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
963 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
964 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
965 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
971 SDOperand DAGCombiner::visitADDE(SDNode *N) {
972 SDOperand N0 = N->getOperand(0);
973 SDOperand N1 = N->getOperand(1);
974 SDOperand CarryIn = N->getOperand(2);
975 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
976 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
977 //MVT::ValueType VT = N0.getValueType();
979 // canonicalize constant to RHS
981 SDOperand Ops[] = { N1, N0, CarryIn };
982 return DAG.getNode(ISD::ADDE, N->getVTList(), Ops, 3);
985 // fold (adde x, y, false) -> (addc x, y)
986 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
987 SDOperand Ops[] = { N1, N0 };
988 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
996 SDOperand DAGCombiner::visitSUB(SDNode *N) {
997 SDOperand N0 = N->getOperand(0);
998 SDOperand N1 = N->getOperand(1);
999 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1000 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1001 MVT::ValueType VT = N0.getValueType();
1004 SDOperand FoldedVOp = SimplifyVBinOp(N);
1005 if (FoldedVOp.Val) return FoldedVOp;
1007 // fold (sub x, x) -> 0
1009 return DAG.getConstant(0, N->getValueType(0));
1010 // fold (sub c1, c2) -> c1-c2
1012 return DAG.getNode(ISD::SUB, VT, N0, N1);
1013 // fold (sub x, c) -> (add x, -c)
1015 return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
1016 // fold (A+B)-A -> B
1017 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1018 return N0.getOperand(1);
1019 // fold (A+B)-B -> A
1020 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1021 return N0.getOperand(0);
1022 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1023 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1024 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1025 if (Result.Val) return Result;
1027 // If either operand is undef, the result is undef
1028 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1029 return DAG.getNode(ISD::UNDEF, VT);
1034 SDOperand DAGCombiner::visitMUL(SDNode *N) {
1035 SDOperand N0 = N->getOperand(0);
1036 SDOperand N1 = N->getOperand(1);
1037 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1038 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1039 MVT::ValueType VT = N0.getValueType();
1042 SDOperand FoldedVOp = SimplifyVBinOp(N);
1043 if (FoldedVOp.Val) return FoldedVOp;
1045 // fold (mul c1, c2) -> c1*c2
1047 return DAG.getNode(ISD::MUL, VT, N0, N1);
1048 // canonicalize constant to RHS
1050 return DAG.getNode(ISD::MUL, VT, N1, N0);
1051 // fold (mul x, 0) -> 0
1052 if (N1C && N1C->isNullValue())
1054 // fold (mul x, -1) -> 0-x
1055 if (N1C && N1C->isAllOnesValue())
1056 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1057 // fold (mul x, (1 << c)) -> x << c
1058 if (N1C && isPowerOf2_64(N1C->getValue()))
1059 return DAG.getNode(ISD::SHL, VT, N0,
1060 DAG.getConstant(Log2_64(N1C->getValue()),
1061 TLI.getShiftAmountTy()));
1062 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1063 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1064 // FIXME: If the input is something that is easily negated (e.g. a
1065 // single-use add), we should put the negate there.
1066 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1067 DAG.getNode(ISD::SHL, VT, N0,
1068 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1069 TLI.getShiftAmountTy())));
1072 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1073 if (N1C && N0.getOpcode() == ISD::SHL &&
1074 isa<ConstantSDNode>(N0.getOperand(1))) {
1075 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1076 AddToWorkList(C3.Val);
1077 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1080 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1083 SDOperand Sh(0,0), Y(0,0);
1084 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1085 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1086 N0.Val->hasOneUse()) {
1088 } else if (N1.getOpcode() == ISD::SHL &&
1089 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1093 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1094 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1097 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1098 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1099 isa<ConstantSDNode>(N0.getOperand(1))) {
1100 return DAG.getNode(ISD::ADD, VT,
1101 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1102 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1106 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1110 // If either operand is undef, the result is undef
1111 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1112 return DAG.getNode(ISD::UNDEF, VT);
1117 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1118 SDOperand N0 = N->getOperand(0);
1119 SDOperand N1 = N->getOperand(1);
1120 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1121 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1122 MVT::ValueType VT = N->getValueType(0);
1125 SDOperand FoldedVOp = SimplifyVBinOp(N);
1126 if (FoldedVOp.Val) return FoldedVOp;
1128 // fold (sdiv c1, c2) -> c1/c2
1129 if (N0C && N1C && !N1C->isNullValue())
1130 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1131 // fold (sdiv X, 1) -> X
1132 if (N1C && N1C->getSignExtended() == 1LL)
1134 // fold (sdiv X, -1) -> 0-X
1135 if (N1C && N1C->isAllOnesValue())
1136 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1137 // If we know the sign bits of both operands are zero, strength reduce to a
1138 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1139 uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1140 if (DAG.MaskedValueIsZero(N1, SignBit) &&
1141 DAG.MaskedValueIsZero(N0, SignBit))
1142 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1143 // fold (sdiv X, pow2) -> simple ops after legalize
1144 if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
1145 (isPowerOf2_64(N1C->getSignExtended()) ||
1146 isPowerOf2_64(-N1C->getSignExtended()))) {
1147 // If dividing by powers of two is cheap, then don't perform the following
1149 if (TLI.isPow2DivCheap())
1151 int64_t pow2 = N1C->getSignExtended();
1152 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1153 unsigned lg2 = Log2_64(abs2);
1154 // Splat the sign bit into the register
1155 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1156 DAG.getConstant(MVT::getSizeInBits(VT)-1,
1157 TLI.getShiftAmountTy()));
1158 AddToWorkList(SGN.Val);
1159 // Add (N0 < 0) ? abs2 - 1 : 0;
1160 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1161 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
1162 TLI.getShiftAmountTy()));
1163 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1164 AddToWorkList(SRL.Val);
1165 AddToWorkList(ADD.Val); // Divide by pow2
1166 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1167 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1168 // If we're dividing by a positive value, we're done. Otherwise, we must
1169 // negate the result.
1172 AddToWorkList(SRA.Val);
1173 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1175 // if integer divide is expensive and we satisfy the requirements, emit an
1176 // alternate sequence.
1177 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1178 !TLI.isIntDivCheap()) {
1179 SDOperand Op = BuildSDIV(N);
1180 if (Op.Val) return Op;
1183 // If either operand is undef, the result is undef
1184 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1185 return DAG.getNode(ISD::UNDEF, VT);
1190 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1191 SDOperand N0 = N->getOperand(0);
1192 SDOperand N1 = N->getOperand(1);
1193 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1194 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1195 MVT::ValueType VT = N->getValueType(0);
1198 SDOperand FoldedVOp = SimplifyVBinOp(N);
1199 if (FoldedVOp.Val) return FoldedVOp;
1201 // fold (udiv c1, c2) -> c1/c2
1202 if (N0C && N1C && !N1C->isNullValue())
1203 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1204 // fold (udiv x, (1 << c)) -> x >>u c
1205 if (N1C && isPowerOf2_64(N1C->getValue()))
1206 return DAG.getNode(ISD::SRL, VT, N0,
1207 DAG.getConstant(Log2_64(N1C->getValue()),
1208 TLI.getShiftAmountTy()));
1209 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1210 if (N1.getOpcode() == ISD::SHL) {
1211 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1212 if (isPowerOf2_64(SHC->getValue())) {
1213 MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
1214 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1215 DAG.getConstant(Log2_64(SHC->getValue()),
1217 AddToWorkList(Add.Val);
1218 return DAG.getNode(ISD::SRL, VT, N0, Add);
1222 // fold (udiv x, c) -> alternate
1223 if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
1224 SDOperand Op = BuildUDIV(N);
1225 if (Op.Val) return Op;
1228 // If either operand is undef, the result is undef
1229 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1230 return DAG.getNode(ISD::UNDEF, VT);
1235 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1236 SDOperand N0 = N->getOperand(0);
1237 SDOperand N1 = N->getOperand(1);
1238 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1239 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1240 MVT::ValueType VT = N->getValueType(0);
1242 // fold (srem c1, c2) -> c1%c2
1243 if (N0C && N1C && !N1C->isNullValue())
1244 return DAG.getNode(ISD::SREM, VT, N0, N1);
1245 // If we know the sign bits of both operands are zero, strength reduce to a
1246 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1247 uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1248 if (DAG.MaskedValueIsZero(N1, SignBit) &&
1249 DAG.MaskedValueIsZero(N0, SignBit))
1250 return DAG.getNode(ISD::UREM, VT, N0, N1);
1252 // Unconditionally lower X%C -> X-X/C*C. This allows the X/C logic to hack on
1253 // the remainder operation.
1254 if (N1C && !N1C->isNullValue()) {
1255 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1256 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
1257 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1258 AddToWorkList(Div.Val);
1259 AddToWorkList(Mul.Val);
1263 // If either operand is undef, the result is undef
1264 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1265 return DAG.getNode(ISD::UNDEF, VT);
1270 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1271 SDOperand N0 = N->getOperand(0);
1272 SDOperand N1 = N->getOperand(1);
1273 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1274 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1275 MVT::ValueType VT = N->getValueType(0);
1277 // fold (urem c1, c2) -> c1%c2
1278 if (N0C && N1C && !N1C->isNullValue())
1279 return DAG.getNode(ISD::UREM, VT, N0, N1);
1280 // fold (urem x, pow2) -> (and x, pow2-1)
1281 if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
1282 return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
1283 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1284 if (N1.getOpcode() == ISD::SHL) {
1285 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1286 if (isPowerOf2_64(SHC->getValue())) {
1287 SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
1288 AddToWorkList(Add.Val);
1289 return DAG.getNode(ISD::AND, VT, N0, Add);
1294 // Unconditionally lower X%C -> X-X/C*C. This allows the X/C logic to hack on
1295 // the remainder operation.
1296 if (N1C && !N1C->isNullValue()) {
1297 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1298 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
1299 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1300 AddToWorkList(Div.Val);
1301 AddToWorkList(Mul.Val);
1305 // If either operand is undef, the result is undef
1306 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1307 return DAG.getNode(ISD::UNDEF, VT);
1312 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1313 SDOperand N0 = N->getOperand(0);
1314 SDOperand N1 = N->getOperand(1);
1315 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1316 MVT::ValueType VT = N->getValueType(0);
1318 // fold (mulhs x, 0) -> 0
1319 if (N1C && N1C->isNullValue())
1321 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1322 if (N1C && N1C->getValue() == 1)
1323 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1324 DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1325 TLI.getShiftAmountTy()));
1326 // If either operand is undef, the result is undef
1327 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1328 return DAG.getNode(ISD::UNDEF, VT);
1333 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1334 SDOperand N0 = N->getOperand(0);
1335 SDOperand N1 = N->getOperand(1);
1336 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1337 MVT::ValueType VT = N->getValueType(0);
1339 // fold (mulhu x, 0) -> 0
1340 if (N1C && N1C->isNullValue())
1342 // fold (mulhu x, 1) -> 0
1343 if (N1C && N1C->getValue() == 1)
1344 return DAG.getConstant(0, N0.getValueType());
1345 // If either operand is undef, the result is undef
1346 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1347 return DAG.getNode(ISD::UNDEF, VT);
1352 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1353 /// two operands of the same opcode, try to simplify it.
1354 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1355 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1356 MVT::ValueType VT = N0.getValueType();
1357 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1359 // For each of OP in AND/OR/XOR:
1360 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1361 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1362 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1363 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1364 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1365 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1366 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1367 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1368 N0.getOperand(0).getValueType(),
1369 N0.getOperand(0), N1.getOperand(0));
1370 AddToWorkList(ORNode.Val);
1371 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1374 // For each of OP in SHL/SRL/SRA/AND...
1375 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1376 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1377 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1378 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1379 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1380 N0.getOperand(1) == N1.getOperand(1)) {
1381 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1382 N0.getOperand(0).getValueType(),
1383 N0.getOperand(0), N1.getOperand(0));
1384 AddToWorkList(ORNode.Val);
1385 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1388 // If either operand is undef, the result is undef
1389 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1390 return DAG.getNode(ISD::UNDEF, VT);
1395 SDOperand DAGCombiner::visitAND(SDNode *N) {
1396 SDOperand N0 = N->getOperand(0);
1397 SDOperand N1 = N->getOperand(1);
1398 SDOperand LL, LR, RL, RR, CC0, CC1;
1399 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1400 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1401 MVT::ValueType VT = N1.getValueType();
1404 SDOperand FoldedVOp = SimplifyVBinOp(N);
1405 if (FoldedVOp.Val) return FoldedVOp;
1407 // fold (and c1, c2) -> c1&c2
1409 return DAG.getNode(ISD::AND, VT, N0, N1);
1410 // canonicalize constant to RHS
1412 return DAG.getNode(ISD::AND, VT, N1, N0);
1413 // fold (and x, -1) -> x
1414 if (N1C && N1C->isAllOnesValue())
1416 // if (and x, c) is known to be zero, return 0
1417 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1418 return DAG.getConstant(0, VT);
1420 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1423 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1424 if (N1C && N0.getOpcode() == ISD::OR)
1425 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1426 if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
1428 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1429 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1430 unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
1431 if (DAG.MaskedValueIsZero(N0.getOperand(0),
1432 ~N1C->getValue() & InMask)) {
1433 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1436 // Replace uses of the AND with uses of the Zero extend node.
1439 // We actually want to replace all uses of the any_extend with the
1440 // zero_extend, to avoid duplicating things. This will later cause this
1441 // AND to be folded.
1442 CombineTo(N0.Val, Zext);
1443 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1446 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1447 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1448 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1449 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1451 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1452 MVT::isInteger(LL.getValueType())) {
1453 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1454 if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
1455 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1456 AddToWorkList(ORNode.Val);
1457 return DAG.getSetCC(VT, ORNode, LR, Op1);
1459 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1460 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1461 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1462 AddToWorkList(ANDNode.Val);
1463 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1465 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1466 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1467 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1468 AddToWorkList(ORNode.Val);
1469 return DAG.getSetCC(VT, ORNode, LR, Op1);
1472 // canonicalize equivalent to ll == rl
1473 if (LL == RR && LR == RL) {
1474 Op1 = ISD::getSetCCSwappedOperands(Op1);
1477 if (LL == RL && LR == RR) {
1478 bool isInteger = MVT::isInteger(LL.getValueType());
1479 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1480 if (Result != ISD::SETCC_INVALID)
1481 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1485 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1486 if (N0.getOpcode() == N1.getOpcode()) {
1487 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1488 if (Tmp.Val) return Tmp;
1491 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1492 // fold (and (sra)) -> (and (srl)) when possible.
1493 if (!MVT::isVector(VT) &&
1494 SimplifyDemandedBits(SDOperand(N, 0)))
1495 return SDOperand(N, 0);
1496 // fold (zext_inreg (extload x)) -> (zextload x)
1497 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1498 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1499 MVT::ValueType EVT = LN0->getLoadedVT();
1500 // If we zero all the possible extended bits, then we can turn this into
1501 // a zextload if we are running before legalize or the operation is legal.
1502 if (DAG.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1503 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1504 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1505 LN0->getBasePtr(), LN0->getSrcValue(),
1506 LN0->getSrcValueOffset(), EVT,
1508 LN0->getAlignment());
1510 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1511 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1514 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1515 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1517 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1518 MVT::ValueType EVT = LN0->getLoadedVT();
1519 // If we zero all the possible extended bits, then we can turn this into
1520 // a zextload if we are running before legalize or the operation is legal.
1521 if (DAG.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1522 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1523 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1524 LN0->getBasePtr(), LN0->getSrcValue(),
1525 LN0->getSrcValueOffset(), EVT,
1527 LN0->getAlignment());
1529 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1530 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1534 // fold (and (load x), 255) -> (zextload x, i8)
1535 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1536 if (N1C && N0.getOpcode() == ISD::LOAD) {
1537 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1538 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1539 LN0->getAddressingMode() == ISD::UNINDEXED &&
1541 MVT::ValueType EVT, LoadedVT;
1542 if (N1C->getValue() == 255)
1544 else if (N1C->getValue() == 65535)
1546 else if (N1C->getValue() == ~0U)
1551 LoadedVT = LN0->getLoadedVT();
1552 if (EVT != MVT::Other && LoadedVT > EVT &&
1553 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1554 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1555 // For big endian targets, we need to add an offset to the pointer to
1556 // load the correct bytes. For little endian systems, we merely need to
1557 // read fewer bytes from the same pointer.
1559 (MVT::getSizeInBits(LoadedVT) - MVT::getSizeInBits(EVT)) / 8;
1560 SDOperand NewPtr = LN0->getBasePtr();
1561 if (!TLI.isLittleEndian())
1562 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1563 DAG.getConstant(PtrOff, PtrType));
1564 AddToWorkList(NewPtr.Val);
1566 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1567 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1568 LN0->isVolatile(), LN0->getAlignment());
1570 CombineTo(N0.Val, Load, Load.getValue(1));
1571 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1579 SDOperand DAGCombiner::visitOR(SDNode *N) {
1580 SDOperand N0 = N->getOperand(0);
1581 SDOperand N1 = N->getOperand(1);
1582 SDOperand LL, LR, RL, RR, CC0, CC1;
1583 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1584 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1585 MVT::ValueType VT = N1.getValueType();
1586 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1589 SDOperand FoldedVOp = SimplifyVBinOp(N);
1590 if (FoldedVOp.Val) return FoldedVOp;
1592 // fold (or c1, c2) -> c1|c2
1594 return DAG.getNode(ISD::OR, VT, N0, N1);
1595 // canonicalize constant to RHS
1597 return DAG.getNode(ISD::OR, VT, N1, N0);
1598 // fold (or x, 0) -> x
1599 if (N1C && N1C->isNullValue())
1601 // fold (or x, -1) -> -1
1602 if (N1C && N1C->isAllOnesValue())
1604 // fold (or x, c) -> c iff (x & ~c) == 0
1606 DAG.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
1609 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1612 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1613 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1614 isa<ConstantSDNode>(N0.getOperand(1))) {
1615 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1616 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1618 DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1620 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1621 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1622 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1623 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1625 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1626 MVT::isInteger(LL.getValueType())) {
1627 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1628 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1629 if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1630 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1631 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1632 AddToWorkList(ORNode.Val);
1633 return DAG.getSetCC(VT, ORNode, LR, Op1);
1635 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1636 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1637 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1638 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1639 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1640 AddToWorkList(ANDNode.Val);
1641 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1644 // canonicalize equivalent to ll == rl
1645 if (LL == RR && LR == RL) {
1646 Op1 = ISD::getSetCCSwappedOperands(Op1);
1649 if (LL == RL && LR == RR) {
1650 bool isInteger = MVT::isInteger(LL.getValueType());
1651 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1652 if (Result != ISD::SETCC_INVALID)
1653 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1657 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1658 if (N0.getOpcode() == N1.getOpcode()) {
1659 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1660 if (Tmp.Val) return Tmp;
1663 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1664 if (N0.getOpcode() == ISD::AND &&
1665 N1.getOpcode() == ISD::AND &&
1666 N0.getOperand(1).getOpcode() == ISD::Constant &&
1667 N1.getOperand(1).getOpcode() == ISD::Constant &&
1668 // Don't increase # computations.
1669 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1670 // We can only do this xform if we know that bits from X that are set in C2
1671 // but not in C1 are already zero. Likewise for Y.
1672 uint64_t LHSMask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1673 uint64_t RHSMask = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
1675 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1676 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1677 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1678 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1683 // See if this is some rotate idiom.
1684 if (SDNode *Rot = MatchRotate(N0, N1))
1685 return SDOperand(Rot, 0);
1691 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1692 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1693 if (Op.getOpcode() == ISD::AND) {
1694 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1695 Mask = Op.getOperand(1);
1696 Op = Op.getOperand(0);
1702 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1710 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1711 // idioms for rotate, and if the target supports rotation instructions, generate
1713 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1714 // Must be a legal type. Expanded an promoted things won't work with rotates.
1715 MVT::ValueType VT = LHS.getValueType();
1716 if (!TLI.isTypeLegal(VT)) return 0;
1718 // The target must have at least one rotate flavor.
1719 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1720 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1721 if (!HasROTL && !HasROTR) return 0;
1723 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1724 SDOperand LHSShift; // The shift.
1725 SDOperand LHSMask; // AND value if any.
1726 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1727 return 0; // Not part of a rotate.
1729 SDOperand RHSShift; // The shift.
1730 SDOperand RHSMask; // AND value if any.
1731 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1732 return 0; // Not part of a rotate.
1734 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1735 return 0; // Not shifting the same value.
1737 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1738 return 0; // Shifts must disagree.
1740 // Canonicalize shl to left side in a shl/srl pair.
1741 if (RHSShift.getOpcode() == ISD::SHL) {
1742 std::swap(LHS, RHS);
1743 std::swap(LHSShift, RHSShift);
1744 std::swap(LHSMask , RHSMask );
1747 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1748 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1749 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1750 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1752 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1753 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1754 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
1755 RHSShiftAmt.getOpcode() == ISD::Constant) {
1756 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
1757 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
1758 if ((LShVal + RShVal) != OpSizeInBits)
1763 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
1765 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
1767 // If there is an AND of either shifted operand, apply it to the result.
1768 if (LHSMask.Val || RHSMask.Val) {
1769 uint64_t Mask = MVT::getIntVTBitMask(VT);
1772 uint64_t RHSBits = (1ULL << LShVal)-1;
1773 Mask &= cast<ConstantSDNode>(LHSMask)->getValue() | RHSBits;
1776 uint64_t LHSBits = ~((1ULL << (OpSizeInBits-RShVal))-1);
1777 Mask &= cast<ConstantSDNode>(RHSMask)->getValue() | LHSBits;
1780 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
1786 // If there is a mask here, and we have a variable shift, we can't be sure
1787 // that we're masking out the right stuff.
1788 if (LHSMask.Val || RHSMask.Val)
1791 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
1792 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
1793 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
1794 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
1795 if (ConstantSDNode *SUBC =
1796 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
1797 if (SUBC->getValue() == OpSizeInBits)
1799 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1801 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
1805 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
1806 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
1807 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
1808 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
1809 if (ConstantSDNode *SUBC =
1810 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
1811 if (SUBC->getValue() == OpSizeInBits)
1813 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1815 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
1819 // Look for sign/zext/any-extended cases:
1820 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
1821 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
1822 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
1823 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
1824 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
1825 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
1826 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
1827 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
1828 if (RExtOp0.getOpcode() == ISD::SUB &&
1829 RExtOp0.getOperand(1) == LExtOp0) {
1830 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
1832 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
1833 // (rotl x, (sub 32, y))
1834 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
1835 if (SUBC->getValue() == OpSizeInBits) {
1837 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1839 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
1842 } else if (LExtOp0.getOpcode() == ISD::SUB &&
1843 RExtOp0 == LExtOp0.getOperand(1)) {
1844 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
1846 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
1847 // (rotr x, (sub 32, y))
1848 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
1849 if (SUBC->getValue() == OpSizeInBits) {
1851 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
1853 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1863 SDOperand DAGCombiner::visitXOR(SDNode *N) {
1864 SDOperand N0 = N->getOperand(0);
1865 SDOperand N1 = N->getOperand(1);
1866 SDOperand LHS, RHS, CC;
1867 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1868 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1869 MVT::ValueType VT = N0.getValueType();
1872 SDOperand FoldedVOp = SimplifyVBinOp(N);
1873 if (FoldedVOp.Val) return FoldedVOp;
1875 // fold (xor c1, c2) -> c1^c2
1877 return DAG.getNode(ISD::XOR, VT, N0, N1);
1878 // canonicalize constant to RHS
1880 return DAG.getNode(ISD::XOR, VT, N1, N0);
1881 // fold (xor x, 0) -> x
1882 if (N1C && N1C->isNullValue())
1885 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
1888 // fold !(x cc y) -> (x !cc y)
1889 if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
1890 bool isInt = MVT::isInteger(LHS.getValueType());
1891 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
1893 if (N0.getOpcode() == ISD::SETCC)
1894 return DAG.getSetCC(VT, LHS, RHS, NotCC);
1895 if (N0.getOpcode() == ISD::SELECT_CC)
1896 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
1897 assert(0 && "Unhandled SetCC Equivalent!");
1900 // fold !(x or y) -> (!x and !y) iff x or y are setcc
1901 if (N1C && N1C->getValue() == 1 && VT == MVT::i1 &&
1902 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1903 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1904 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
1905 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1906 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
1907 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
1908 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1909 return DAG.getNode(NewOpcode, VT, LHS, RHS);
1912 // fold !(x or y) -> (!x and !y) iff x or y are constants
1913 if (N1C && N1C->isAllOnesValue() &&
1914 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1915 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1916 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
1917 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1918 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
1919 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
1920 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1921 return DAG.getNode(NewOpcode, VT, LHS, RHS);
1924 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
1925 if (N1C && N0.getOpcode() == ISD::XOR) {
1926 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
1927 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1929 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
1930 DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
1932 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
1933 DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
1935 // fold (xor x, x) -> 0
1937 if (!MVT::isVector(VT)) {
1938 return DAG.getConstant(0, VT);
1939 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1940 // Produce a vector of zeros.
1941 SDOperand El = DAG.getConstant(0, MVT::getVectorElementType(VT));
1942 std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
1943 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1947 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
1948 if (N0.getOpcode() == N1.getOpcode()) {
1949 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1950 if (Tmp.Val) return Tmp;
1953 // Simplify the expression using non-local knowledge.
1954 if (!MVT::isVector(VT) &&
1955 SimplifyDemandedBits(SDOperand(N, 0)))
1956 return SDOperand(N, 0);
1961 SDOperand DAGCombiner::visitSHL(SDNode *N) {
1962 SDOperand N0 = N->getOperand(0);
1963 SDOperand N1 = N->getOperand(1);
1964 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1965 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1966 MVT::ValueType VT = N0.getValueType();
1967 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1969 // fold (shl c1, c2) -> c1<<c2
1971 return DAG.getNode(ISD::SHL, VT, N0, N1);
1972 // fold (shl 0, x) -> 0
1973 if (N0C && N0C->isNullValue())
1975 // fold (shl x, c >= size(x)) -> undef
1976 if (N1C && N1C->getValue() >= OpSizeInBits)
1977 return DAG.getNode(ISD::UNDEF, VT);
1978 // fold (shl x, 0) -> x
1979 if (N1C && N1C->isNullValue())
1981 // if (shl x, c) is known to be zero, return 0
1982 if (DAG.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1983 return DAG.getConstant(0, VT);
1984 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
1985 return SDOperand(N, 0);
1986 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
1987 if (N1C && N0.getOpcode() == ISD::SHL &&
1988 N0.getOperand(1).getOpcode() == ISD::Constant) {
1989 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1990 uint64_t c2 = N1C->getValue();
1991 if (c1 + c2 > OpSizeInBits)
1992 return DAG.getConstant(0, VT);
1993 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
1994 DAG.getConstant(c1 + c2, N1.getValueType()));
1996 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
1997 // (srl (and x, -1 << c1), c1-c2)
1998 if (N1C && N0.getOpcode() == ISD::SRL &&
1999 N0.getOperand(1).getOpcode() == ISD::Constant) {
2000 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2001 uint64_t c2 = N1C->getValue();
2002 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2003 DAG.getConstant(~0ULL << c1, VT));
2005 return DAG.getNode(ISD::SHL, VT, Mask,
2006 DAG.getConstant(c2-c1, N1.getValueType()));
2008 return DAG.getNode(ISD::SRL, VT, Mask,
2009 DAG.getConstant(c1-c2, N1.getValueType()));
2011 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2012 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2013 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2014 DAG.getConstant(~0ULL << N1C->getValue(), VT));
2018 SDOperand DAGCombiner::visitSRA(SDNode *N) {
2019 SDOperand N0 = N->getOperand(0);
2020 SDOperand N1 = N->getOperand(1);
2021 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2022 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2023 MVT::ValueType VT = N0.getValueType();
2025 // fold (sra c1, c2) -> c1>>c2
2027 return DAG.getNode(ISD::SRA, VT, N0, N1);
2028 // fold (sra 0, x) -> 0
2029 if (N0C && N0C->isNullValue())
2031 // fold (sra -1, x) -> -1
2032 if (N0C && N0C->isAllOnesValue())
2034 // fold (sra x, c >= size(x)) -> undef
2035 if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
2036 return DAG.getNode(ISD::UNDEF, VT);
2037 // fold (sra x, 0) -> x
2038 if (N1C && N1C->isNullValue())
2040 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2042 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2043 unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
2046 default: EVT = MVT::Other; break;
2047 case 1: EVT = MVT::i1; break;
2048 case 8: EVT = MVT::i8; break;
2049 case 16: EVT = MVT::i16; break;
2050 case 32: EVT = MVT::i32; break;
2052 if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
2053 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2054 DAG.getValueType(EVT));
2057 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2058 if (N1C && N0.getOpcode() == ISD::SRA) {
2059 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2060 unsigned Sum = N1C->getValue() + C1->getValue();
2061 if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
2062 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2063 DAG.getConstant(Sum, N1C->getValueType(0)));
2067 // Simplify, based on bits shifted out of the LHS.
2068 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2069 return SDOperand(N, 0);
2072 // If the sign bit is known to be zero, switch this to a SRL.
2073 if (DAG.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
2074 return DAG.getNode(ISD::SRL, VT, N0, N1);
2078 SDOperand DAGCombiner::visitSRL(SDNode *N) {
2079 SDOperand N0 = N->getOperand(0);
2080 SDOperand N1 = N->getOperand(1);
2081 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2082 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2083 MVT::ValueType VT = N0.getValueType();
2084 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2086 // fold (srl c1, c2) -> c1 >>u c2
2088 return DAG.getNode(ISD::SRL, VT, N0, N1);
2089 // fold (srl 0, x) -> 0
2090 if (N0C && N0C->isNullValue())
2092 // fold (srl x, c >= size(x)) -> undef
2093 if (N1C && N1C->getValue() >= OpSizeInBits)
2094 return DAG.getNode(ISD::UNDEF, VT);
2095 // fold (srl x, 0) -> x
2096 if (N1C && N1C->isNullValue())
2098 // if (srl x, c) is known to be zero, return 0
2099 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
2100 return DAG.getConstant(0, VT);
2102 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2103 if (N1C && N0.getOpcode() == ISD::SRL &&
2104 N0.getOperand(1).getOpcode() == ISD::Constant) {
2105 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2106 uint64_t c2 = N1C->getValue();
2107 if (c1 + c2 > OpSizeInBits)
2108 return DAG.getConstant(0, VT);
2109 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2110 DAG.getConstant(c1 + c2, N1.getValueType()));
2113 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2114 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2115 // Shifting in all undef bits?
2116 MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
2117 if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
2118 return DAG.getNode(ISD::UNDEF, VT);
2120 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2121 AddToWorkList(SmallShift.Val);
2122 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2125 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2126 // bit, which is unmodified by sra.
2127 if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
2128 if (N0.getOpcode() == ISD::SRA)
2129 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2132 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2133 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2134 N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
2135 uint64_t KnownZero, KnownOne, Mask = MVT::getIntVTBitMask(VT);
2136 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2138 // If any of the input bits are KnownOne, then the input couldn't be all
2139 // zeros, thus the result of the srl will always be zero.
2140 if (KnownOne) return DAG.getConstant(0, VT);
2142 // If all of the bits input the to ctlz node are known to be zero, then
2143 // the result of the ctlz is "32" and the result of the shift is one.
2144 uint64_t UnknownBits = ~KnownZero & Mask;
2145 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2147 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2148 if ((UnknownBits & (UnknownBits-1)) == 0) {
2149 // Okay, we know that only that the single bit specified by UnknownBits
2150 // could be set on input to the CTLZ node. If this bit is set, the SRL
2151 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2152 // to an SRL,XOR pair, which is likely to simplify more.
2153 unsigned ShAmt = CountTrailingZeros_64(UnknownBits);
2154 SDOperand Op = N0.getOperand(0);
2156 Op = DAG.getNode(ISD::SRL, VT, Op,
2157 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2158 AddToWorkList(Op.Val);
2160 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2164 // fold operands of srl based on knowledge that the low bits are not
2166 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2167 return SDOperand(N, 0);
2172 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2173 SDOperand N0 = N->getOperand(0);
2174 MVT::ValueType VT = N->getValueType(0);
2176 // fold (ctlz c1) -> c2
2177 if (isa<ConstantSDNode>(N0))
2178 return DAG.getNode(ISD::CTLZ, VT, N0);
2182 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2183 SDOperand N0 = N->getOperand(0);
2184 MVT::ValueType VT = N->getValueType(0);
2186 // fold (cttz c1) -> c2
2187 if (isa<ConstantSDNode>(N0))
2188 return DAG.getNode(ISD::CTTZ, VT, N0);
2192 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2193 SDOperand N0 = N->getOperand(0);
2194 MVT::ValueType VT = N->getValueType(0);
2196 // fold (ctpop c1) -> c2
2197 if (isa<ConstantSDNode>(N0))
2198 return DAG.getNode(ISD::CTPOP, VT, N0);
2202 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2203 SDOperand N0 = N->getOperand(0);
2204 SDOperand N1 = N->getOperand(1);
2205 SDOperand N2 = N->getOperand(2);
2206 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2207 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2208 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2209 MVT::ValueType VT = N->getValueType(0);
2211 // fold select C, X, X -> X
2214 // fold select true, X, Y -> X
2215 if (N0C && !N0C->isNullValue())
2217 // fold select false, X, Y -> Y
2218 if (N0C && N0C->isNullValue())
2220 // fold select C, 1, X -> C | X
2221 if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
2222 return DAG.getNode(ISD::OR, VT, N0, N2);
2223 // fold select C, 0, X -> ~C & X
2224 // FIXME: this should check for C type == X type, not i1?
2225 if (MVT::i1 == VT && N1C && N1C->isNullValue()) {
2226 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2227 AddToWorkList(XORNode.Val);
2228 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2230 // fold select C, X, 1 -> ~C | X
2231 if (MVT::i1 == VT && N2C && N2C->getValue() == 1) {
2232 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2233 AddToWorkList(XORNode.Val);
2234 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2236 // fold select C, X, 0 -> C & X
2237 // FIXME: this should check for C type == X type, not i1?
2238 if (MVT::i1 == VT && N2C && N2C->isNullValue())
2239 return DAG.getNode(ISD::AND, VT, N0, N1);
2240 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2241 if (MVT::i1 == VT && N0 == N1)
2242 return DAG.getNode(ISD::OR, VT, N0, N2);
2243 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2244 if (MVT::i1 == VT && N0 == N2)
2245 return DAG.getNode(ISD::AND, VT, N0, N1);
2247 // If we can fold this based on the true/false value, do so.
2248 if (SimplifySelectOps(N, N1, N2))
2249 return SDOperand(N, 0); // Don't revisit N.
2251 // fold selects based on a setcc into other things, such as min/max/abs
2252 if (N0.getOpcode() == ISD::SETCC)
2254 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2255 // having to say they don't support SELECT_CC on every type the DAG knows
2256 // about, since there is no way to mark an opcode illegal at all value types
2257 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2258 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2259 N1, N2, N0.getOperand(2));
2261 return SimplifySelect(N0, N1, N2);
2265 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2266 SDOperand N0 = N->getOperand(0);
2267 SDOperand N1 = N->getOperand(1);
2268 SDOperand N2 = N->getOperand(2);
2269 SDOperand N3 = N->getOperand(3);
2270 SDOperand N4 = N->getOperand(4);
2271 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2273 // fold select_cc lhs, rhs, x, x, cc -> x
2277 // Determine if the condition we're dealing with is constant
2278 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
2279 if (SCC.Val) AddToWorkList(SCC.Val);
2281 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2282 if (SCCC->getValue())
2283 return N2; // cond always true -> true val
2285 return N3; // cond always false -> false val
2288 // Fold to a simpler select_cc
2289 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2290 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2291 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2294 // If we can fold this based on the true/false value, do so.
2295 if (SimplifySelectOps(N, N2, N3))
2296 return SDOperand(N, 0); // Don't revisit N.
2298 // fold select_cc into other things, such as min/max/abs
2299 return SimplifySelectCC(N0, N1, N2, N3, CC);
2302 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2303 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2304 cast<CondCodeSDNode>(N->getOperand(2))->get());
2307 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2308 SDOperand N0 = N->getOperand(0);
2309 MVT::ValueType VT = N->getValueType(0);
2311 // fold (sext c1) -> c1
2312 if (isa<ConstantSDNode>(N0))
2313 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2315 // fold (sext (sext x)) -> (sext x)
2316 // fold (sext (aext x)) -> (sext x)
2317 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2318 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2320 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2321 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2322 if (N0.getOpcode() == ISD::TRUNCATE) {
2323 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2324 if (NarrowLoad.Val) {
2325 if (NarrowLoad.Val != N0.Val)
2326 CombineTo(N0.Val, NarrowLoad);
2327 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2331 // See if the value being truncated is already sign extended. If so, just
2332 // eliminate the trunc/sext pair.
2333 if (N0.getOpcode() == ISD::TRUNCATE) {
2334 SDOperand Op = N0.getOperand(0);
2335 unsigned OpBits = MVT::getSizeInBits(Op.getValueType());
2336 unsigned MidBits = MVT::getSizeInBits(N0.getValueType());
2337 unsigned DestBits = MVT::getSizeInBits(VT);
2338 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2340 if (OpBits == DestBits) {
2341 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2342 // bits, it is already ready.
2343 if (NumSignBits > DestBits-MidBits)
2345 } else if (OpBits < DestBits) {
2346 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2347 // bits, just sext from i32.
2348 if (NumSignBits > OpBits-MidBits)
2349 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2351 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2352 // bits, just truncate to i32.
2353 if (NumSignBits > OpBits-MidBits)
2354 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2357 // fold (sext (truncate x)) -> (sextinreg x).
2358 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2359 N0.getValueType())) {
2360 if (Op.getValueType() < VT)
2361 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2362 else if (Op.getValueType() > VT)
2363 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2364 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2365 DAG.getValueType(N0.getValueType()));
2369 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2370 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2371 (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
2372 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2373 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2374 LN0->getBasePtr(), LN0->getSrcValue(),
2375 LN0->getSrcValueOffset(),
2378 CombineTo(N, ExtLoad);
2379 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2380 ExtLoad.getValue(1));
2381 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2384 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2385 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2386 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2387 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2388 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2389 MVT::ValueType EVT = LN0->getLoadedVT();
2390 if (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2391 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2392 LN0->getBasePtr(), LN0->getSrcValue(),
2393 LN0->getSrcValueOffset(), EVT,
2395 LN0->getAlignment());
2396 CombineTo(N, ExtLoad);
2397 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2398 ExtLoad.getValue(1));
2399 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2403 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2404 if (N0.getOpcode() == ISD::SETCC) {
2406 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2407 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2408 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2409 if (SCC.Val) return SCC;
2415 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2416 SDOperand N0 = N->getOperand(0);
2417 MVT::ValueType VT = N->getValueType(0);
2419 // fold (zext c1) -> c1
2420 if (isa<ConstantSDNode>(N0))
2421 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2422 // fold (zext (zext x)) -> (zext x)
2423 // fold (zext (aext x)) -> (zext x)
2424 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2425 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2427 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2428 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2429 if (N0.getOpcode() == ISD::TRUNCATE) {
2430 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2431 if (NarrowLoad.Val) {
2432 if (NarrowLoad.Val != N0.Val)
2433 CombineTo(N0.Val, NarrowLoad);
2434 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2438 // fold (zext (truncate x)) -> (and x, mask)
2439 if (N0.getOpcode() == ISD::TRUNCATE &&
2440 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2441 SDOperand Op = N0.getOperand(0);
2442 if (Op.getValueType() < VT) {
2443 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2444 } else if (Op.getValueType() > VT) {
2445 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2447 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2450 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2451 if (N0.getOpcode() == ISD::AND &&
2452 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2453 N0.getOperand(1).getOpcode() == ISD::Constant) {
2454 SDOperand X = N0.getOperand(0).getOperand(0);
2455 if (X.getValueType() < VT) {
2456 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2457 } else if (X.getValueType() > VT) {
2458 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2460 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2461 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2464 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2465 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2466 (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2467 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2468 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2469 LN0->getBasePtr(), LN0->getSrcValue(),
2470 LN0->getSrcValueOffset(),
2473 LN0->getAlignment());
2474 CombineTo(N, ExtLoad);
2475 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2476 ExtLoad.getValue(1));
2477 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2480 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2481 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2482 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2483 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2484 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2485 MVT::ValueType EVT = LN0->getLoadedVT();
2486 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2487 LN0->getBasePtr(), LN0->getSrcValue(),
2488 LN0->getSrcValueOffset(), EVT,
2490 LN0->getAlignment());
2491 CombineTo(N, ExtLoad);
2492 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2493 ExtLoad.getValue(1));
2494 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2497 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2498 if (N0.getOpcode() == ISD::SETCC) {
2500 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2501 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2502 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2503 if (SCC.Val) return SCC;
2509 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
2510 SDOperand N0 = N->getOperand(0);
2511 MVT::ValueType VT = N->getValueType(0);
2513 // fold (aext c1) -> c1
2514 if (isa<ConstantSDNode>(N0))
2515 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
2516 // fold (aext (aext x)) -> (aext x)
2517 // fold (aext (zext x)) -> (zext x)
2518 // fold (aext (sext x)) -> (sext x)
2519 if (N0.getOpcode() == ISD::ANY_EXTEND ||
2520 N0.getOpcode() == ISD::ZERO_EXTEND ||
2521 N0.getOpcode() == ISD::SIGN_EXTEND)
2522 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2524 // fold (aext (truncate (load x))) -> (aext (smaller load x))
2525 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
2526 if (N0.getOpcode() == ISD::TRUNCATE) {
2527 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2528 if (NarrowLoad.Val) {
2529 if (NarrowLoad.Val != N0.Val)
2530 CombineTo(N0.Val, NarrowLoad);
2531 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
2535 // fold (aext (truncate x))
2536 if (N0.getOpcode() == ISD::TRUNCATE) {
2537 SDOperand TruncOp = N0.getOperand(0);
2538 if (TruncOp.getValueType() == VT)
2539 return TruncOp; // x iff x size == zext size.
2540 if (TruncOp.getValueType() > VT)
2541 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
2542 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
2545 // fold (aext (and (trunc x), cst)) -> (and x, cst).
2546 if (N0.getOpcode() == ISD::AND &&
2547 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2548 N0.getOperand(1).getOpcode() == ISD::Constant) {
2549 SDOperand X = N0.getOperand(0).getOperand(0);
2550 if (X.getValueType() < VT) {
2551 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2552 } else if (X.getValueType() > VT) {
2553 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2555 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2556 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2559 // fold (aext (load x)) -> (aext (truncate (extload x)))
2560 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2561 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2562 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2563 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2564 LN0->getBasePtr(), LN0->getSrcValue(),
2565 LN0->getSrcValueOffset(),
2568 LN0->getAlignment());
2569 CombineTo(N, ExtLoad);
2570 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2571 ExtLoad.getValue(1));
2572 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2575 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
2576 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
2577 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
2578 if (N0.getOpcode() == ISD::LOAD &&
2579 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
2581 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2582 MVT::ValueType EVT = LN0->getLoadedVT();
2583 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
2584 LN0->getChain(), LN0->getBasePtr(),
2586 LN0->getSrcValueOffset(), EVT,
2588 LN0->getAlignment());
2589 CombineTo(N, ExtLoad);
2590 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2591 ExtLoad.getValue(1));
2592 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2595 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2596 if (N0.getOpcode() == ISD::SETCC) {
2598 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2599 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2600 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2608 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
2609 /// bits and then truncated to a narrower type and where N is a multiple
2610 /// of number of bits of the narrower type, transform it to a narrower load
2611 /// from address + N / num of bits of new type. If the result is to be
2612 /// extended, also fold the extension to form a extending load.
2613 SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
2614 unsigned Opc = N->getOpcode();
2615 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2616 SDOperand N0 = N->getOperand(0);
2617 MVT::ValueType VT = N->getValueType(0);
2618 MVT::ValueType EVT = N->getValueType(0);
2620 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
2622 if (Opc == ISD::SIGN_EXTEND_INREG) {
2623 ExtType = ISD::SEXTLOAD;
2624 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2625 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
2629 unsigned EVTBits = MVT::getSizeInBits(EVT);
2631 bool CombineSRL = false;
2632 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
2633 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2634 ShAmt = N01->getValue();
2635 // Is the shift amount a multiple of size of VT?
2636 if ((ShAmt & (EVTBits-1)) == 0) {
2637 N0 = N0.getOperand(0);
2638 if (MVT::getSizeInBits(N0.getValueType()) <= EVTBits)
2645 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2646 // Do not allow folding to i1 here. i1 is implicitly stored in memory in
2647 // zero extended form: by shrinking the load, we lose track of the fact
2648 // that it is already zero extended.
2649 // FIXME: This should be reevaluated.
2651 assert(MVT::getSizeInBits(N0.getValueType()) > EVTBits &&
2652 "Cannot truncate to larger type!");
2653 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2654 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
2655 // For big endian targets, we need to adjust the offset to the pointer to
2656 // load the correct bytes.
2657 if (!TLI.isLittleEndian())
2658 ShAmt = MVT::getSizeInBits(N0.getValueType()) - ShAmt - EVTBits;
2659 uint64_t PtrOff = ShAmt / 8;
2660 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
2661 DAG.getConstant(PtrOff, PtrType));
2662 AddToWorkList(NewPtr.Val);
2663 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
2664 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
2665 LN0->getSrcValue(), LN0->getSrcValueOffset(),
2666 LN0->isVolatile(), LN0->getAlignment())
2667 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
2668 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
2669 LN0->isVolatile(), LN0->getAlignment());
2672 std::vector<SDNode*> NowDead;
2673 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1), NowDead);
2674 CombineTo(N->getOperand(0).Val, Load);
2676 CombineTo(N0.Val, Load, Load.getValue(1));
2678 if (Opc == ISD::SIGN_EXTEND_INREG)
2679 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
2681 return DAG.getNode(Opc, VT, Load);
2683 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2690 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
2691 SDOperand N0 = N->getOperand(0);
2692 SDOperand N1 = N->getOperand(1);
2693 MVT::ValueType VT = N->getValueType(0);
2694 MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
2695 unsigned EVTBits = MVT::getSizeInBits(EVT);
2697 // fold (sext_in_reg c1) -> c1
2698 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
2699 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
2701 // If the input is already sign extended, just drop the extension.
2702 if (DAG.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
2705 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
2706 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2707 EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
2708 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
2711 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
2712 if (DAG.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
2713 return DAG.getZeroExtendInReg(N0, EVT);
2715 // fold operands of sext_in_reg based on knowledge that the top bits are not
2717 if (SimplifyDemandedBits(SDOperand(N, 0)))
2718 return SDOperand(N, 0);
2720 // fold (sext_in_reg (load x)) -> (smaller sextload x)
2721 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
2722 SDOperand NarrowLoad = ReduceLoadWidth(N);
2726 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
2727 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
2728 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
2729 if (N0.getOpcode() == ISD::SRL) {
2730 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2731 if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
2732 // We can turn this into an SRA iff the input to the SRL is already sign
2734 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
2735 if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
2736 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
2740 // fold (sext_inreg (extload x)) -> (sextload x)
2741 if (ISD::isEXTLoad(N0.Val) &&
2742 ISD::isUNINDEXEDLoad(N0.Val) &&
2743 EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2744 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2745 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2746 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2747 LN0->getBasePtr(), LN0->getSrcValue(),
2748 LN0->getSrcValueOffset(), EVT,
2750 LN0->getAlignment());
2751 CombineTo(N, ExtLoad);
2752 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2753 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2755 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
2756 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
2758 EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2759 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2760 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2761 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2762 LN0->getBasePtr(), LN0->getSrcValue(),
2763 LN0->getSrcValueOffset(), EVT,
2765 LN0->getAlignment());
2766 CombineTo(N, ExtLoad);
2767 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2768 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2773 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
2774 SDOperand N0 = N->getOperand(0);
2775 MVT::ValueType VT = N->getValueType(0);
2778 if (N0.getValueType() == N->getValueType(0))
2780 // fold (truncate c1) -> c1
2781 if (isa<ConstantSDNode>(N0))
2782 return DAG.getNode(ISD::TRUNCATE, VT, N0);
2783 // fold (truncate (truncate x)) -> (truncate x)
2784 if (N0.getOpcode() == ISD::TRUNCATE)
2785 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
2786 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
2787 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
2788 N0.getOpcode() == ISD::ANY_EXTEND) {
2789 if (N0.getOperand(0).getValueType() < VT)
2790 // if the source is smaller than the dest, we still need an extend
2791 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2792 else if (N0.getOperand(0).getValueType() > VT)
2793 // if the source is larger than the dest, than we just need the truncate
2794 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
2796 // if the source and dest are the same type, we can drop both the extend
2798 return N0.getOperand(0);
2801 // fold (truncate (load x)) -> (smaller load x)
2802 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
2803 return ReduceLoadWidth(N);
2806 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
2807 SDOperand N0 = N->getOperand(0);
2808 MVT::ValueType VT = N->getValueType(0);
2810 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
2811 // Only do this before legalize, since afterward the target may be depending
2812 // on the bitconvert.
2813 // First check to see if this is all constant.
2814 if (!AfterLegalize &&
2815 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
2816 MVT::isVector(VT)) {
2817 bool isSimple = true;
2818 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
2819 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
2820 N0.getOperand(i).getOpcode() != ISD::Constant &&
2821 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
2826 MVT::ValueType DestEltVT = MVT::getVectorElementType(N->getValueType(0));
2827 assert(!MVT::isVector(DestEltVT) &&
2828 "Element type of vector ValueType must not be vector!");
2830 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
2834 // If the input is a constant, let getNode() fold it.
2835 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
2836 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
2837 if (Res.Val != N) return Res;
2840 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
2841 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
2843 // fold (conv (load x)) -> (load (conv*)x)
2844 // If the resultant load doesn't need a higher alignment than the original!
2845 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2846 ISD::isUNINDEXEDLoad(N0.Val) &&
2847 TLI.isOperationLegal(ISD::LOAD, VT)) {
2848 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2849 unsigned Align = TLI.getTargetMachine().getTargetData()->
2850 getABITypeAlignment(MVT::getTypeForValueType(VT));
2851 unsigned OrigAlign = LN0->getAlignment();
2852 if (Align <= OrigAlign) {
2853 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
2854 LN0->getSrcValue(), LN0->getSrcValueOffset(),
2855 LN0->isVolatile(), LN0->getAlignment());
2857 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
2866 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
2867 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
2868 /// destination element value type.
2869 SDOperand DAGCombiner::
2870 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
2871 MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
2873 // If this is already the right type, we're done.
2874 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
2876 unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
2877 unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
2879 // If this is a conversion of N elements of one type to N elements of another
2880 // type, convert each element. This handles FP<->INT cases.
2881 if (SrcBitSize == DstBitSize) {
2882 SmallVector<SDOperand, 8> Ops;
2883 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2884 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
2885 AddToWorkList(Ops.back().Val);
2888 MVT::getVectorType(DstEltVT,
2889 MVT::getVectorNumElements(BV->getValueType(0)));
2890 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2893 // Otherwise, we're growing or shrinking the elements. To avoid having to
2894 // handle annoying details of growing/shrinking FP values, we convert them to
2896 if (MVT::isFloatingPoint(SrcEltVT)) {
2897 // Convert the input float vector to a int vector where the elements are the
2899 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
2900 MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2901 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
2905 // Now we know the input is an integer vector. If the output is a FP type,
2906 // convert to integer first, then to FP of the right size.
2907 if (MVT::isFloatingPoint(DstEltVT)) {
2908 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
2909 MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2910 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
2912 // Next, convert to FP elements of the same size.
2913 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
2916 // Okay, we know the src/dst types are both integers of differing types.
2917 // Handling growing first.
2918 assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
2919 if (SrcBitSize < DstBitSize) {
2920 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
2922 SmallVector<SDOperand, 8> Ops;
2923 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
2924 i += NumInputsPerOutput) {
2925 bool isLE = TLI.isLittleEndian();
2926 uint64_t NewBits = 0;
2927 bool EltIsUndef = true;
2928 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
2929 // Shift the previously computed bits over.
2930 NewBits <<= SrcBitSize;
2931 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
2932 if (Op.getOpcode() == ISD::UNDEF) continue;
2935 NewBits |= cast<ConstantSDNode>(Op)->getValue();
2939 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2941 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
2944 MVT::ValueType VT = MVT::getVectorType(DstEltVT,
2946 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2949 // Finally, this must be the case where we are shrinking elements: each input
2950 // turns into multiple outputs.
2951 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
2952 SmallVector<SDOperand, 8> Ops;
2953 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2954 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
2955 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
2956 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2959 uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
2961 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
2962 unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
2963 OpVal >>= DstBitSize;
2964 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
2967 // For big endian targets, swap the order of the pieces of each element.
2968 if (!TLI.isLittleEndian())
2969 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
2971 MVT::ValueType VT = MVT::getVectorType(DstEltVT, Ops.size());
2972 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2977 SDOperand DAGCombiner::visitFADD(SDNode *N) {
2978 SDOperand N0 = N->getOperand(0);
2979 SDOperand N1 = N->getOperand(1);
2980 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2981 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2982 MVT::ValueType VT = N->getValueType(0);
2985 SDOperand FoldedVOp = SimplifyVBinOp(N);
2986 if (FoldedVOp.Val) return FoldedVOp;
2988 // fold (fadd c1, c2) -> c1+c2
2990 return DAG.getNode(ISD::FADD, VT, N0, N1);
2991 // canonicalize constant to RHS
2992 if (N0CFP && !N1CFP)
2993 return DAG.getNode(ISD::FADD, VT, N1, N0);
2994 // fold (A + (-B)) -> A-B
2995 if (isNegatibleForFree(N1) == 2)
2996 return DAG.getNode(ISD::FSUB, VT, N0, GetNegatedExpression(N1, DAG));
2997 // fold ((-A) + B) -> B-A
2998 if (isNegatibleForFree(N0) == 2)
2999 return DAG.getNode(ISD::FSUB, VT, N1, GetNegatedExpression(N0, DAG));
3001 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3002 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3003 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3004 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3005 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3007 // If either operand is undef, the result is undef
3008 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
3009 return DAG.getNode(ISD::UNDEF, VT);
3014 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3015 SDOperand N0 = N->getOperand(0);
3016 SDOperand N1 = N->getOperand(1);
3017 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3018 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3019 MVT::ValueType VT = N->getValueType(0);
3022 SDOperand FoldedVOp = SimplifyVBinOp(N);
3023 if (FoldedVOp.Val) return FoldedVOp;
3025 // fold (fsub c1, c2) -> c1-c2
3027 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3028 // fold (A-(-B)) -> A+B
3029 if (isNegatibleForFree(N1))
3030 return DAG.getNode(ISD::FADD, VT, N0, GetNegatedExpression(N1, DAG));
3032 // If either operand is undef, the result is undef
3033 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
3034 return DAG.getNode(ISD::UNDEF, VT);
3039 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3040 SDOperand N0 = N->getOperand(0);
3041 SDOperand N1 = N->getOperand(1);
3042 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3043 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3044 MVT::ValueType VT = N->getValueType(0);
3047 SDOperand FoldedVOp = SimplifyVBinOp(N);
3048 if (FoldedVOp.Val) return FoldedVOp;
3050 // fold (fmul c1, c2) -> c1*c2
3052 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3053 // canonicalize constant to RHS
3054 if (N0CFP && !N1CFP)
3055 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3056 // fold (fmul X, 2.0) -> (fadd X, X)
3057 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3058 return DAG.getNode(ISD::FADD, VT, N0, N0);
3059 // fold (fmul X, -1.0) -> (fneg X)
3060 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3061 return DAG.getNode(ISD::FNEG, VT, N0);
3064 if (char LHSNeg = isNegatibleForFree(N0)) {
3065 if (char RHSNeg = isNegatibleForFree(N1)) {
3066 // Both can be negated for free, check to see if at least one is cheaper
3068 if (LHSNeg == 2 || RHSNeg == 2)
3069 return DAG.getNode(ISD::FMUL, VT, GetNegatedExpression(N0, DAG),
3070 GetNegatedExpression(N1, DAG));
3074 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3075 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3076 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3077 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3078 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3080 // If either operand is undef, the result is undef
3081 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
3082 return DAG.getNode(ISD::UNDEF, VT);
3087 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3088 SDOperand N0 = N->getOperand(0);
3089 SDOperand N1 = N->getOperand(1);
3090 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3091 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3092 MVT::ValueType VT = N->getValueType(0);
3095 SDOperand FoldedVOp = SimplifyVBinOp(N);
3096 if (FoldedVOp.Val) return FoldedVOp;
3098 // fold (fdiv c1, c2) -> c1/c2
3100 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3104 if (char LHSNeg = isNegatibleForFree(N0)) {
3105 if (char RHSNeg = isNegatibleForFree(N1)) {
3106 // Both can be negated for free, check to see if at least one is cheaper
3108 if (LHSNeg == 2 || RHSNeg == 2)
3109 return DAG.getNode(ISD::FDIV, VT, GetNegatedExpression(N0, DAG),
3110 GetNegatedExpression(N1, DAG));
3114 // If either operand is undef, the result is undef
3115 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
3116 return DAG.getNode(ISD::UNDEF, VT);
3121 SDOperand DAGCombiner::visitFREM(SDNode *N) {
3122 SDOperand N0 = N->getOperand(0);
3123 SDOperand N1 = N->getOperand(1);
3124 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3125 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3126 MVT::ValueType VT = N->getValueType(0);
3128 // fold (frem c1, c2) -> fmod(c1,c2)
3130 return DAG.getNode(ISD::FREM, VT, N0, N1);
3132 // If either operand is undef, the result is undef
3133 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
3134 return DAG.getNode(ISD::UNDEF, VT);
3139 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3140 SDOperand N0 = N->getOperand(0);
3141 SDOperand N1 = N->getOperand(1);
3142 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3143 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3144 MVT::ValueType VT = N->getValueType(0);
3146 if (N0CFP && N1CFP) // Constant fold
3147 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3150 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3151 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3156 u.d = N1CFP->getValue();
3158 return DAG.getNode(ISD::FABS, VT, N0);
3160 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3163 // copysign(fabs(x), y) -> copysign(x, y)
3164 // copysign(fneg(x), y) -> copysign(x, y)
3165 // copysign(copysign(x,z), y) -> copysign(x, y)
3166 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3167 N0.getOpcode() == ISD::FCOPYSIGN)
3168 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3170 // copysign(x, abs(y)) -> abs(x)
3171 if (N1.getOpcode() == ISD::FABS)
3172 return DAG.getNode(ISD::FABS, VT, N0);
3174 // copysign(x, copysign(y,z)) -> copysign(x, z)
3175 if (N1.getOpcode() == ISD::FCOPYSIGN)
3176 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3178 // copysign(x, fp_extend(y)) -> copysign(x, y)
3179 // copysign(x, fp_round(y)) -> copysign(x, y)
3180 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3181 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3188 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3189 SDOperand N0 = N->getOperand(0);
3190 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3191 MVT::ValueType VT = N->getValueType(0);
3193 // fold (sint_to_fp c1) -> c1fp
3195 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3199 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3200 SDOperand N0 = N->getOperand(0);
3201 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3202 MVT::ValueType VT = N->getValueType(0);
3204 // fold (uint_to_fp c1) -> c1fp
3206 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3210 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3211 SDOperand N0 = N->getOperand(0);
3212 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3213 MVT::ValueType VT = N->getValueType(0);
3215 // fold (fp_to_sint c1fp) -> c1
3217 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3221 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3222 SDOperand N0 = N->getOperand(0);
3223 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3224 MVT::ValueType VT = N->getValueType(0);
3226 // fold (fp_to_uint c1fp) -> c1
3228 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3232 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3233 SDOperand N0 = N->getOperand(0);
3234 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3235 MVT::ValueType VT = N->getValueType(0);
3237 // fold (fp_round c1fp) -> c1fp
3239 return DAG.getNode(ISD::FP_ROUND, VT, N0);
3241 // fold (fp_round (fp_extend x)) -> x
3242 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3243 return N0.getOperand(0);
3245 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3246 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
3247 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0));
3248 AddToWorkList(Tmp.Val);
3249 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3255 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3256 SDOperand N0 = N->getOperand(0);
3257 MVT::ValueType VT = N->getValueType(0);
3258 MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3259 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3261 // fold (fp_round_inreg c1fp) -> c1fp
3263 SDOperand Round = DAG.getConstantFP(N0CFP->getValue(), EVT);
3264 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3269 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3270 SDOperand N0 = N->getOperand(0);
3271 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3272 MVT::ValueType VT = N->getValueType(0);
3274 // fold (fp_extend c1fp) -> c1fp
3276 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
3278 // fold (fpext (load x)) -> (fpext (fpround (extload x)))
3279 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3280 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3281 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3282 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3283 LN0->getBasePtr(), LN0->getSrcValue(),
3284 LN0->getSrcValueOffset(),
3287 LN0->getAlignment());
3288 CombineTo(N, ExtLoad);
3289 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad),
3290 ExtLoad.getValue(1));
3291 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3298 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3299 SDOperand N0 = N->getOperand(0);
3300 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3301 MVT::ValueType VT = N->getValueType(0);
3303 // fold (fneg c1) -> -c1
3305 return DAG.getNode(ISD::FNEG, VT, N0);
3306 // fold (fneg (sub x, y)) -> (sub y, x)
3307 if (N0.getOpcode() == ISD::SUB)
3308 return DAG.getNode(ISD::SUB, VT, N0.getOperand(1), N0.getOperand(0));
3309 // fold (fneg (fneg x)) -> x
3310 if (N0.getOpcode() == ISD::FNEG)
3311 return N0.getOperand(0);
3315 SDOperand DAGCombiner::visitFABS(SDNode *N) {
3316 SDOperand N0 = N->getOperand(0);
3317 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3318 MVT::ValueType VT = N->getValueType(0);
3320 // fold (fabs c1) -> fabs(c1)
3322 return DAG.getNode(ISD::FABS, VT, N0);
3323 // fold (fabs (fabs x)) -> (fabs x)
3324 if (N0.getOpcode() == ISD::FABS)
3325 return N->getOperand(0);
3326 // fold (fabs (fneg x)) -> (fabs x)
3327 // fold (fabs (fcopysign x, y)) -> (fabs x)
3328 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
3329 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
3334 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
3335 SDOperand Chain = N->getOperand(0);
3336 SDOperand N1 = N->getOperand(1);
3337 SDOperand N2 = N->getOperand(2);
3338 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3340 // never taken branch, fold to chain
3341 if (N1C && N1C->isNullValue())
3343 // unconditional branch
3344 if (N1C && N1C->getValue() == 1)
3345 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
3346 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
3348 if (N1.getOpcode() == ISD::SETCC &&
3349 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
3350 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
3351 N1.getOperand(0), N1.getOperand(1), N2);
3356 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
3358 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
3359 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
3360 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
3362 // Use SimplifySetCC to simplify SETCC's.
3363 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
3364 if (Simp.Val) AddToWorkList(Simp.Val);
3366 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
3368 // fold br_cc true, dest -> br dest (unconditional branch)
3369 if (SCCC && SCCC->getValue())
3370 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
3372 // fold br_cc false, dest -> unconditional fall through
3373 if (SCCC && SCCC->isNullValue())
3374 return N->getOperand(0);
3376 // fold to a simpler setcc
3377 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
3378 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
3379 Simp.getOperand(2), Simp.getOperand(0),
3380 Simp.getOperand(1), N->getOperand(4));
3385 /// CombineToPreIndexedLoadStore - Try turning a load / store and a
3386 /// pre-indexed load / store when the base pointer is a add or subtract
3387 /// and it has other uses besides the load / store. After the
3388 /// transformation, the new indexed load / store has effectively folded
3389 /// the add / subtract in and all of its other uses are redirected to the
3390 /// new load / store.
3391 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
3398 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3399 if (LD->getAddressingMode() != ISD::UNINDEXED)
3401 VT = LD->getLoadedVT();
3402 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
3403 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
3405 Ptr = LD->getBasePtr();
3406 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3407 if (ST->getAddressingMode() != ISD::UNINDEXED)
3409 VT = ST->getStoredVT();
3410 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
3411 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
3413 Ptr = ST->getBasePtr();
3418 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
3419 // out. There is no reason to make this a preinc/predec.
3420 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
3421 Ptr.Val->hasOneUse())
3424 // Ask the target to do addressing mode selection.
3427 ISD::MemIndexedMode AM = ISD::UNINDEXED;
3428 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
3430 // Don't create a indexed load / store with zero offset.
3431 if (isa<ConstantSDNode>(Offset) &&
3432 cast<ConstantSDNode>(Offset)->getValue() == 0)
3435 // Try turning it into a pre-indexed load / store except when:
3436 // 1) The new base ptr is a frame index.
3437 // 2) If N is a store and the new base ptr is either the same as or is a
3438 // predecessor of the value being stored.
3439 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
3440 // that would create a cycle.
3441 // 4) All uses are load / store ops that use it as old base ptr.
3443 // Check #1. Preinc'ing a frame index would require copying the stack pointer
3444 // (plus the implicit offset) to a register to preinc anyway.
3445 if (isa<FrameIndexSDNode>(BasePtr))
3450 SDOperand Val = cast<StoreSDNode>(N)->getValue();
3451 if (Val == BasePtr || BasePtr.Val->isPredecessor(Val.Val))
3455 // Now check for #3 and #4.
3456 bool RealUse = false;
3457 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
3458 E = Ptr.Val->use_end(); I != E; ++I) {
3462 if (Use->isPredecessor(N))
3465 if (!((Use->getOpcode() == ISD::LOAD &&
3466 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
3467 (Use->getOpcode() == ISD::STORE) &&
3468 cast<StoreSDNode>(Use)->getBasePtr() == Ptr))
3476 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
3478 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
3481 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
3482 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
3484 std::vector<SDNode*> NowDead;
3486 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
3488 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
3491 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
3495 // Nodes can end up on the worklist more than once. Make sure we do
3496 // not process a node that has been replaced.
3497 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3498 removeFromWorkList(NowDead[i]);
3499 // Finally, since the node is now dead, remove it from the graph.
3502 // Replace the uses of Ptr with uses of the updated base value.
3503 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
3505 removeFromWorkList(Ptr.Val);
3506 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3507 removeFromWorkList(NowDead[i]);
3508 DAG.DeleteNode(Ptr.Val);
3513 /// CombineToPostIndexedLoadStore - Try combine a load / store with a
3514 /// add / sub of the base pointer node into a post-indexed load / store.
3515 /// The transformation folded the add / subtract into the new indexed
3516 /// load / store effectively and all of its uses are redirected to the
3517 /// new load / store.
3518 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
3525 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3526 if (LD->getAddressingMode() != ISD::UNINDEXED)
3528 VT = LD->getLoadedVT();
3529 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
3530 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
3532 Ptr = LD->getBasePtr();
3533 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3534 if (ST->getAddressingMode() != ISD::UNINDEXED)
3536 VT = ST->getStoredVT();
3537 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
3538 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
3540 Ptr = ST->getBasePtr();
3545 if (Ptr.Val->hasOneUse())
3548 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
3549 E = Ptr.Val->use_end(); I != E; ++I) {
3552 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
3557 ISD::MemIndexedMode AM = ISD::UNINDEXED;
3558 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
3560 std::swap(BasePtr, Offset);
3563 // Don't create a indexed load / store with zero offset.
3564 if (isa<ConstantSDNode>(Offset) &&
3565 cast<ConstantSDNode>(Offset)->getValue() == 0)
3568 // Try turning it into a post-indexed load / store except when
3569 // 1) All uses are load / store ops that use it as base ptr.
3570 // 2) Op must be independent of N, i.e. Op is neither a predecessor
3571 // nor a successor of N. Otherwise, if Op is folded that would
3575 bool TryNext = false;
3576 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
3577 EE = BasePtr.Val->use_end(); II != EE; ++II) {
3582 // If all the uses are load / store addresses, then don't do the
3584 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
3585 bool RealUse = false;
3586 for (SDNode::use_iterator III = Use->use_begin(),
3587 EEE = Use->use_end(); III != EEE; ++III) {
3588 SDNode *UseUse = *III;
3589 if (!((UseUse->getOpcode() == ISD::LOAD &&
3590 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
3591 (UseUse->getOpcode() == ISD::STORE) &&
3592 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use))
3606 if (!Op->isPredecessor(N) && !N->isPredecessor(Op)) {
3607 SDOperand Result = isLoad
3608 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
3609 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
3612 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
3613 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
3615 std::vector<SDNode*> NowDead;
3617 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
3619 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
3622 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
3626 // Nodes can end up on the worklist more than once. Make sure we do
3627 // not process a node that has been replaced.
3628 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3629 removeFromWorkList(NowDead[i]);
3630 // Finally, since the node is now dead, remove it from the graph.
3633 // Replace the uses of Use with uses of the updated base value.
3634 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
3635 Result.getValue(isLoad ? 1 : 0),
3637 removeFromWorkList(Op);
3638 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3639 removeFromWorkList(NowDead[i]);
3650 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
3651 LoadSDNode *LD = cast<LoadSDNode>(N);
3652 SDOperand Chain = LD->getChain();
3653 SDOperand Ptr = LD->getBasePtr();
3655 // If load is not volatile and there are no uses of the loaded value (and
3656 // the updated indexed value in case of indexed loads), change uses of the
3657 // chain value into uses of the chain input (i.e. delete the dead load).
3658 if (!LD->isVolatile()) {
3659 if (N->getValueType(1) == MVT::Other) {
3661 if (N->hasNUsesOfValue(0, 0))
3662 return CombineTo(N, DAG.getNode(ISD::UNDEF, N->getValueType(0)), Chain);
3665 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
3666 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
3667 SDOperand Undef0 = DAG.getNode(ISD::UNDEF, N->getValueType(0));
3668 SDOperand Undef1 = DAG.getNode(ISD::UNDEF, N->getValueType(1));
3669 SDOperand To[] = { Undef0, Undef1, Chain };
3670 return CombineTo(N, To, 3);
3675 // If this load is directly stored, replace the load value with the stored
3677 // TODO: Handle store large -> read small portion.
3678 // TODO: Handle TRUNCSTORE/LOADEXT
3679 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
3680 if (ISD::isNON_TRUNCStore(Chain.Val)) {
3681 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
3682 if (PrevST->getBasePtr() == Ptr &&
3683 PrevST->getValue().getValueType() == N->getValueType(0))
3684 return CombineTo(N, Chain.getOperand(1), Chain);
3689 // Walk up chain skipping non-aliasing memory nodes.
3690 SDOperand BetterChain = FindBetterChain(N, Chain);
3692 // If there is a better chain.
3693 if (Chain != BetterChain) {
3696 // Replace the chain to void dependency.
3697 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
3698 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
3699 LD->getSrcValue(), LD->getSrcValueOffset(),
3700 LD->isVolatile(), LD->getAlignment());
3702 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
3703 LD->getValueType(0),
3704 BetterChain, Ptr, LD->getSrcValue(),
3705 LD->getSrcValueOffset(),
3708 LD->getAlignment());
3711 // Create token factor to keep old chain connected.
3712 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
3713 Chain, ReplLoad.getValue(1));
3715 // Replace uses with load result and token factor. Don't add users
3717 return CombineTo(N, ReplLoad.getValue(0), Token, false);
3721 // Try transforming N to an indexed load.
3722 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
3723 return SDOperand(N, 0);
3728 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
3729 StoreSDNode *ST = cast<StoreSDNode>(N);
3730 SDOperand Chain = ST->getChain();
3731 SDOperand Value = ST->getValue();
3732 SDOperand Ptr = ST->getBasePtr();
3734 // If this is a store of a bit convert, store the input value if the
3735 // resultant store does not need a higher alignment than the original.
3736 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
3737 ST->getAddressingMode() == ISD::UNINDEXED) {
3738 unsigned Align = ST->getAlignment();
3739 MVT::ValueType SVT = Value.getOperand(0).getValueType();
3740 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
3741 getABITypeAlignment(MVT::getTypeForValueType(SVT));
3742 if (Align <= OrigAlign && TLI.isOperationLegal(ISD::STORE, SVT))
3743 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
3744 ST->getSrcValueOffset());
3747 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
3748 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
3749 if (Value.getOpcode() != ISD::TargetConstantFP) {
3751 switch (CFP->getValueType(0)) {
3752 default: assert(0 && "Unknown FP type");
3754 if (!AfterLegalize || TLI.isTypeLegal(MVT::i32)) {
3755 Tmp = DAG.getConstant(FloatToBits(CFP->getValue()), MVT::i32);
3756 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
3757 ST->getSrcValueOffset());
3761 if (!AfterLegalize || TLI.isTypeLegal(MVT::i64)) {
3762 Tmp = DAG.getConstant(DoubleToBits(CFP->getValue()), MVT::i64);
3763 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
3764 ST->getSrcValueOffset());
3765 } else if (TLI.isTypeLegal(MVT::i32)) {
3766 // Many FP stores are not make apparent until after legalize, e.g. for
3767 // argument passing. Since this is so common, custom legalize the
3768 // 64-bit integer store into two 32-bit stores.
3769 uint64_t Val = DoubleToBits(CFP->getValue());
3770 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
3771 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
3772 if (!TLI.isLittleEndian()) std::swap(Lo, Hi);
3774 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
3775 ST->getSrcValueOffset());
3776 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
3777 DAG.getConstant(4, Ptr.getValueType()));
3778 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
3779 ST->getSrcValueOffset()+4);
3780 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
3788 // Walk up chain skipping non-aliasing memory nodes.
3789 SDOperand BetterChain = FindBetterChain(N, Chain);
3791 // If there is a better chain.
3792 if (Chain != BetterChain) {
3793 // Replace the chain to avoid dependency.
3794 SDOperand ReplStore;
3795 if (ST->isTruncatingStore()) {
3796 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
3797 ST->getSrcValue(),ST->getSrcValueOffset(), ST->getStoredVT());
3799 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
3800 ST->getSrcValue(), ST->getSrcValueOffset());
3803 // Create token to keep both nodes around.
3805 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
3807 // Don't add users to work list.
3808 return CombineTo(N, Token, false);
3812 // Try transforming N to an indexed store.
3813 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
3814 return SDOperand(N, 0);
3819 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
3820 SDOperand InVec = N->getOperand(0);
3821 SDOperand InVal = N->getOperand(1);
3822 SDOperand EltNo = N->getOperand(2);
3824 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
3825 // vector with the inserted element.
3826 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
3827 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
3828 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
3829 if (Elt < Ops.size())
3831 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
3832 &Ops[0], Ops.size());
3838 SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
3839 unsigned NumInScalars = N->getNumOperands();
3840 MVT::ValueType VT = N->getValueType(0);
3841 unsigned NumElts = MVT::getVectorNumElements(VT);
3842 MVT::ValueType EltType = MVT::getVectorElementType(VT);
3844 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
3845 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
3846 // at most two distinct vectors, turn this into a shuffle node.
3847 SDOperand VecIn1, VecIn2;
3848 for (unsigned i = 0; i != NumInScalars; ++i) {
3849 // Ignore undef inputs.
3850 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
3852 // If this input is something other than a EXTRACT_VECTOR_ELT with a
3853 // constant index, bail out.
3854 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
3855 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
3856 VecIn1 = VecIn2 = SDOperand(0, 0);
3860 // If the input vector type disagrees with the result of the build_vector,
3861 // we can't make a shuffle.
3862 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
3863 if (ExtractedFromVec.getValueType() != VT) {
3864 VecIn1 = VecIn2 = SDOperand(0, 0);
3868 // Otherwise, remember this. We allow up to two distinct input vectors.
3869 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
3872 if (VecIn1.Val == 0) {
3873 VecIn1 = ExtractedFromVec;
3874 } else if (VecIn2.Val == 0) {
3875 VecIn2 = ExtractedFromVec;
3878 VecIn1 = VecIn2 = SDOperand(0, 0);
3883 // If everything is good, we can make a shuffle operation.
3885 SmallVector<SDOperand, 8> BuildVecIndices;
3886 for (unsigned i = 0; i != NumInScalars; ++i) {
3887 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
3888 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
3892 SDOperand Extract = N->getOperand(i);
3894 // If extracting from the first vector, just use the index directly.
3895 if (Extract.getOperand(0) == VecIn1) {
3896 BuildVecIndices.push_back(Extract.getOperand(1));
3900 // Otherwise, use InIdx + VecSize
3901 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
3902 BuildVecIndices.push_back(DAG.getConstant(Idx+NumInScalars,
3903 TLI.getPointerTy()));
3906 // Add count and size info.
3907 MVT::ValueType BuildVecVT =
3908 MVT::getVectorType(TLI.getPointerTy(), NumElts);
3910 // Return the new VECTOR_SHUFFLE node.
3916 // Use an undef build_vector as input for the second operand.
3917 std::vector<SDOperand> UnOps(NumInScalars,
3918 DAG.getNode(ISD::UNDEF,
3920 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
3921 &UnOps[0], UnOps.size());
3922 AddToWorkList(Ops[1].Val);
3924 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
3925 &BuildVecIndices[0], BuildVecIndices.size());
3926 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
3932 SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
3933 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
3934 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
3935 // inputs come from at most two distinct vectors, turn this into a shuffle
3938 // If we only have one input vector, we don't need to do any concatenation.
3939 if (N->getNumOperands() == 1) {
3940 return N->getOperand(0);
3946 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
3947 SDOperand ShufMask = N->getOperand(2);
3948 unsigned NumElts = ShufMask.getNumOperands();
3950 // If the shuffle mask is an identity operation on the LHS, return the LHS.
3951 bool isIdentity = true;
3952 for (unsigned i = 0; i != NumElts; ++i) {
3953 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3954 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
3959 if (isIdentity) return N->getOperand(0);
3961 // If the shuffle mask is an identity operation on the RHS, return the RHS.
3963 for (unsigned i = 0; i != NumElts; ++i) {
3964 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3965 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
3970 if (isIdentity) return N->getOperand(1);
3972 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
3974 bool isUnary = true;
3975 bool isSplat = true;
3977 unsigned BaseIdx = 0;
3978 for (unsigned i = 0; i != NumElts; ++i)
3979 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
3980 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
3981 int V = (Idx < NumElts) ? 0 : 1;
3995 SDOperand N0 = N->getOperand(0);
3996 SDOperand N1 = N->getOperand(1);
3997 // Normalize unary shuffle so the RHS is undef.
3998 if (isUnary && VecNum == 1)
4001 // If it is a splat, check if the argument vector is a build_vector with
4002 // all scalar elements the same.
4006 // If this is a bit convert that changes the element type of the vector but
4007 // not the number of vector elements, look through it. Be careful not to
4008 // look though conversions that change things like v4f32 to v2f64.
4009 if (V->getOpcode() == ISD::BIT_CONVERT) {
4010 SDOperand ConvInput = V->getOperand(0);
4011 if (MVT::getVectorNumElements(ConvInput.getValueType()) == NumElts)
4015 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4016 unsigned NumElems = V->getNumOperands();
4017 if (NumElems > BaseIdx) {
4019 bool AllSame = true;
4020 for (unsigned i = 0; i != NumElems; ++i) {
4021 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4022 Base = V->getOperand(i);
4026 // Splat of <u, u, u, u>, return <u, u, u, u>
4029 for (unsigned i = 0; i != NumElems; ++i) {
4030 if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
4031 V->getOperand(i) != Base) {
4036 // Splat of <x, x, x, x>, return <x, x, x, x>
4043 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4045 if (isUnary || N0 == N1) {
4046 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4048 SmallVector<SDOperand, 8> MappedOps;
4049 for (unsigned i = 0; i != NumElts; ++i) {
4050 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4051 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4052 MappedOps.push_back(ShufMask.getOperand(i));
4055 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4056 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4059 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4060 &MappedOps[0], MappedOps.size());
4061 AddToWorkList(ShufMask.Val);
4062 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
4064 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
4071 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
4072 /// an AND to a vector_shuffle with the destination vector and a zero vector.
4073 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
4074 /// vector_shuffle V, Zero, <0, 4, 2, 4>
4075 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
4076 SDOperand LHS = N->getOperand(0);
4077 SDOperand RHS = N->getOperand(1);
4078 if (N->getOpcode() == ISD::AND) {
4079 if (RHS.getOpcode() == ISD::BIT_CONVERT)
4080 RHS = RHS.getOperand(0);
4081 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
4082 std::vector<SDOperand> IdxOps;
4083 unsigned NumOps = RHS.getNumOperands();
4084 unsigned NumElts = NumOps;
4085 MVT::ValueType EVT = MVT::getVectorElementType(RHS.getValueType());
4086 for (unsigned i = 0; i != NumElts; ++i) {
4087 SDOperand Elt = RHS.getOperand(i);
4088 if (!isa<ConstantSDNode>(Elt))
4090 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
4091 IdxOps.push_back(DAG.getConstant(i, EVT));
4092 else if (cast<ConstantSDNode>(Elt)->isNullValue())
4093 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
4098 // Let's see if the target supports this vector_shuffle.
4099 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
4102 // Return the new VECTOR_SHUFFLE node.
4103 MVT::ValueType VT = MVT::getVectorType(EVT, NumElts);
4104 std::vector<SDOperand> Ops;
4105 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
4107 AddToWorkList(LHS.Val);
4108 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
4109 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4110 &ZeroOps[0], ZeroOps.size()));
4111 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4112 &IdxOps[0], IdxOps.size()));
4113 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
4114 &Ops[0], Ops.size());
4115 if (VT != LHS.getValueType()) {
4116 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
4124 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
4125 SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
4126 // After legalize, the target may be depending on adds and other
4127 // binary ops to provide legal ways to construct constants or other
4128 // things. Simplifying them may result in a loss of legality.
4129 if (AfterLegalize) return SDOperand();
4131 MVT::ValueType VT = N->getValueType(0);
4132 if (!MVT::isVector(VT)) return SDOperand();
4134 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4135 SDOperand LHS = N->getOperand(0);
4136 SDOperand RHS = N->getOperand(1);
4137 SDOperand Shuffle = XformToShuffleWithZero(N);
4138 if (Shuffle.Val) return Shuffle;
4140 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
4142 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
4143 RHS.getOpcode() == ISD::BUILD_VECTOR) {
4144 SmallVector<SDOperand, 8> Ops;
4145 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
4146 SDOperand LHSOp = LHS.getOperand(i);
4147 SDOperand RHSOp = RHS.getOperand(i);
4148 // If these two elements can't be folded, bail out.
4149 if ((LHSOp.getOpcode() != ISD::UNDEF &&
4150 LHSOp.getOpcode() != ISD::Constant &&
4151 LHSOp.getOpcode() != ISD::ConstantFP) ||
4152 (RHSOp.getOpcode() != ISD::UNDEF &&
4153 RHSOp.getOpcode() != ISD::Constant &&
4154 RHSOp.getOpcode() != ISD::ConstantFP))
4156 // Can't fold divide by zero.
4157 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
4158 N->getOpcode() == ISD::FDIV) {
4159 if ((RHSOp.getOpcode() == ISD::Constant &&
4160 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
4161 (RHSOp.getOpcode() == ISD::ConstantFP &&
4162 !cast<ConstantFPSDNode>(RHSOp.Val)->getValue()))
4165 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
4166 AddToWorkList(Ops.back().Val);
4167 assert((Ops.back().getOpcode() == ISD::UNDEF ||
4168 Ops.back().getOpcode() == ISD::Constant ||
4169 Ops.back().getOpcode() == ISD::ConstantFP) &&
4170 "Scalar binop didn't fold!");
4173 if (Ops.size() == LHS.getNumOperands()) {
4174 MVT::ValueType VT = LHS.getValueType();
4175 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
4182 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
4183 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
4185 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
4186 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4187 // If we got a simplified select_cc node back from SimplifySelectCC, then
4188 // break it down into a new SETCC node, and a new SELECT node, and then return
4189 // the SELECT node, since we were called with a SELECT node.
4191 // Check to see if we got a select_cc back (to turn into setcc/select).
4192 // Otherwise, just return whatever node we got back, like fabs.
4193 if (SCC.getOpcode() == ISD::SELECT_CC) {
4194 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
4195 SCC.getOperand(0), SCC.getOperand(1),
4197 AddToWorkList(SETCC.Val);
4198 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
4199 SCC.getOperand(3), SETCC);
4206 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
4207 /// are the two values being selected between, see if we can simplify the
4208 /// select. Callers of this should assume that TheSelect is deleted if this
4209 /// returns true. As such, they should return the appropriate thing (e.g. the
4210 /// node) back to the top-level of the DAG combiner loop to avoid it being
4213 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
4216 // If this is a select from two identical things, try to pull the operation
4217 // through the select.
4218 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
4219 // If this is a load and the token chain is identical, replace the select
4220 // of two loads with a load through a select of the address to load from.
4221 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
4222 // constants have been dropped into the constant pool.
4223 if (LHS.getOpcode() == ISD::LOAD &&
4224 // Token chains must be identical.
4225 LHS.getOperand(0) == RHS.getOperand(0)) {
4226 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
4227 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
4229 // If this is an EXTLOAD, the VT's must match.
4230 if (LLD->getLoadedVT() == RLD->getLoadedVT()) {
4231 // FIXME: this conflates two src values, discarding one. This is not
4232 // the right thing to do, but nothing uses srcvalues now. When they do,
4233 // turn SrcValue into a list of locations.
4235 if (TheSelect->getOpcode() == ISD::SELECT) {
4236 // Check that the condition doesn't reach either load. If so, folding
4237 // this will induce a cycle into the DAG.
4238 if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4239 !RLD->isPredecessor(TheSelect->getOperand(0).Val)) {
4240 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
4241 TheSelect->getOperand(0), LLD->getBasePtr(),
4245 // Check that the condition doesn't reach either load. If so, folding
4246 // this will induce a cycle into the DAG.
4247 if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4248 !RLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4249 !LLD->isPredecessor(TheSelect->getOperand(1).Val) &&
4250 !RLD->isPredecessor(TheSelect->getOperand(1).Val)) {
4251 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
4252 TheSelect->getOperand(0),
4253 TheSelect->getOperand(1),
4254 LLD->getBasePtr(), RLD->getBasePtr(),
4255 TheSelect->getOperand(4));
4261 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
4262 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
4263 Addr,LLD->getSrcValue(),
4264 LLD->getSrcValueOffset(),
4266 LLD->getAlignment());
4268 Load = DAG.getExtLoad(LLD->getExtensionType(),
4269 TheSelect->getValueType(0),
4270 LLD->getChain(), Addr, LLD->getSrcValue(),
4271 LLD->getSrcValueOffset(),
4274 LLD->getAlignment());
4276 // Users of the select now use the result of the load.
4277 CombineTo(TheSelect, Load);
4279 // Users of the old loads now use the new load's chain. We know the
4280 // old-load value is dead now.
4281 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
4282 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
4292 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
4293 SDOperand N2, SDOperand N3,
4294 ISD::CondCode CC, bool NotExtCompare) {
4296 MVT::ValueType VT = N2.getValueType();
4297 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
4298 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
4299 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
4301 // Determine if the condition we're dealing with is constant
4302 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
4303 if (SCC.Val) AddToWorkList(SCC.Val);
4304 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
4306 // fold select_cc true, x, y -> x
4307 if (SCCC && SCCC->getValue())
4309 // fold select_cc false, x, y -> y
4310 if (SCCC && SCCC->getValue() == 0)
4313 // Check to see if we can simplify the select into an fabs node
4314 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
4315 // Allow either -0.0 or 0.0
4316 if (CFP->getValue() == 0.0) {
4317 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
4318 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
4319 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
4320 N2 == N3.getOperand(0))
4321 return DAG.getNode(ISD::FABS, VT, N0);
4323 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
4324 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
4325 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
4326 N2.getOperand(0) == N3)
4327 return DAG.getNode(ISD::FABS, VT, N3);
4331 // Check to see if we can perform the "gzip trick", transforming
4332 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
4333 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
4334 MVT::isInteger(N0.getValueType()) &&
4335 MVT::isInteger(N2.getValueType()) &&
4336 (N1C->isNullValue() || // (a < 0) ? b : 0
4337 (N1C->getValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
4338 MVT::ValueType XType = N0.getValueType();
4339 MVT::ValueType AType = N2.getValueType();
4340 if (XType >= AType) {
4341 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
4342 // single-bit constant.
4343 if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
4344 unsigned ShCtV = Log2_64(N2C->getValue());
4345 ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
4346 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
4347 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
4348 AddToWorkList(Shift.Val);
4349 if (XType > AType) {
4350 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
4351 AddToWorkList(Shift.Val);
4353 return DAG.getNode(ISD::AND, AType, Shift, N2);
4355 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
4356 DAG.getConstant(MVT::getSizeInBits(XType)-1,
4357 TLI.getShiftAmountTy()));
4358 AddToWorkList(Shift.Val);
4359 if (XType > AType) {
4360 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
4361 AddToWorkList(Shift.Val);
4363 return DAG.getNode(ISD::AND, AType, Shift, N2);
4367 // fold select C, 16, 0 -> shl C, 4
4368 if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
4369 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
4371 // If the caller doesn't want us to simplify this into a zext of a compare,
4373 if (NotExtCompare && N2C->getValue() == 1)
4376 // Get a SetCC of the condition
4377 // FIXME: Should probably make sure that setcc is legal if we ever have a
4378 // target where it isn't.
4379 SDOperand Temp, SCC;
4380 // cast from setcc result type to select result type
4381 if (AfterLegalize) {
4382 SCC = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
4383 if (N2.getValueType() < SCC.getValueType())
4384 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
4386 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
4388 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
4389 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
4391 AddToWorkList(SCC.Val);
4392 AddToWorkList(Temp.Val);
4394 if (N2C->getValue() == 1)
4396 // shl setcc result by log2 n2c
4397 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
4398 DAG.getConstant(Log2_64(N2C->getValue()),
4399 TLI.getShiftAmountTy()));
4402 // Check to see if this is the equivalent of setcc
4403 // FIXME: Turn all of these into setcc if setcc if setcc is legal
4404 // otherwise, go ahead with the folds.
4405 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
4406 MVT::ValueType XType = N0.getValueType();
4407 if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
4408 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
4409 if (Res.getValueType() != VT)
4410 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
4414 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
4415 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
4416 TLI.isOperationLegal(ISD::CTLZ, XType)) {
4417 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
4418 return DAG.getNode(ISD::SRL, XType, Ctlz,
4419 DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
4420 TLI.getShiftAmountTy()));
4422 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
4423 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
4424 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
4426 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
4427 DAG.getConstant(~0ULL, XType));
4428 return DAG.getNode(ISD::SRL, XType,
4429 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
4430 DAG.getConstant(MVT::getSizeInBits(XType)-1,
4431 TLI.getShiftAmountTy()));
4433 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
4434 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
4435 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
4436 DAG.getConstant(MVT::getSizeInBits(XType)-1,
4437 TLI.getShiftAmountTy()));
4438 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
4442 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
4443 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4444 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
4445 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
4446 N2.getOperand(0) == N1 && MVT::isInteger(N0.getValueType())) {
4447 MVT::ValueType XType = N0.getValueType();
4448 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
4449 DAG.getConstant(MVT::getSizeInBits(XType)-1,
4450 TLI.getShiftAmountTy()));
4451 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
4452 AddToWorkList(Shift.Val);
4453 AddToWorkList(Add.Val);
4454 return DAG.getNode(ISD::XOR, XType, Add, Shift);
4456 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
4457 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4458 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
4459 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
4460 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
4461 MVT::ValueType XType = N0.getValueType();
4462 if (SubC->isNullValue() && MVT::isInteger(XType)) {
4463 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
4464 DAG.getConstant(MVT::getSizeInBits(XType)-1,
4465 TLI.getShiftAmountTy()));
4466 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
4467 AddToWorkList(Shift.Val);
4468 AddToWorkList(Add.Val);
4469 return DAG.getNode(ISD::XOR, XType, Add, Shift);
4477 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
4478 SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
4479 SDOperand N1, ISD::CondCode Cond,
4480 bool foldBooleans) {
4481 TargetLowering::DAGCombinerInfo
4482 DagCombineInfo(DAG, !AfterLegalize, false, this);
4483 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
4486 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
4487 /// return a DAG expression to select that will generate the same value by
4488 /// multiplying by a magic number. See:
4489 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4490 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
4491 std::vector<SDNode*> Built;
4492 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
4494 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4500 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
4501 /// return a DAG expression to select that will generate the same value by
4502 /// multiplying by a magic number. See:
4503 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4504 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
4505 std::vector<SDNode*> Built;
4506 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
4508 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4514 /// FindBaseOffset - Return true if base is known not to alias with anything
4515 /// but itself. Provides base object and offset as results.
4516 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
4517 // Assume it is a primitive operation.
4518 Base = Ptr; Offset = 0;
4520 // If it's an adding a simple constant then integrate the offset.
4521 if (Base.getOpcode() == ISD::ADD) {
4522 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
4523 Base = Base.getOperand(0);
4524 Offset += C->getValue();
4528 // If it's any of the following then it can't alias with anything but itself.
4529 return isa<FrameIndexSDNode>(Base) ||
4530 isa<ConstantPoolSDNode>(Base) ||
4531 isa<GlobalAddressSDNode>(Base);
4534 /// isAlias - Return true if there is any possibility that the two addresses
4536 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
4537 const Value *SrcValue1, int SrcValueOffset1,
4538 SDOperand Ptr2, int64_t Size2,
4539 const Value *SrcValue2, int SrcValueOffset2)
4541 // If they are the same then they must be aliases.
4542 if (Ptr1 == Ptr2) return true;
4544 // Gather base node and offset information.
4545 SDOperand Base1, Base2;
4546 int64_t Offset1, Offset2;
4547 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
4548 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
4550 // If they have a same base address then...
4551 if (Base1 == Base2) {
4552 // Check to see if the addresses overlap.
4553 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
4556 // If we know both bases then they can't alias.
4557 if (KnownBase1 && KnownBase2) return false;
4559 if (CombinerGlobalAA) {
4560 // Use alias analysis information.
4561 int Overlap1 = Size1 + SrcValueOffset1 + Offset1;
4562 int Overlap2 = Size2 + SrcValueOffset2 + Offset2;
4563 AliasAnalysis::AliasResult AAResult =
4564 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
4565 if (AAResult == AliasAnalysis::NoAlias)
4569 // Otherwise we have to assume they alias.
4573 /// FindAliasInfo - Extracts the relevant alias information from the memory
4574 /// node. Returns true if the operand was a load.
4575 bool DAGCombiner::FindAliasInfo(SDNode *N,
4576 SDOperand &Ptr, int64_t &Size,
4577 const Value *&SrcValue, int &SrcValueOffset) {
4578 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4579 Ptr = LD->getBasePtr();
4580 Size = MVT::getSizeInBits(LD->getLoadedVT()) >> 3;
4581 SrcValue = LD->getSrcValue();
4582 SrcValueOffset = LD->getSrcValueOffset();
4584 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4585 Ptr = ST->getBasePtr();
4586 Size = MVT::getSizeInBits(ST->getStoredVT()) >> 3;
4587 SrcValue = ST->getSrcValue();
4588 SrcValueOffset = ST->getSrcValueOffset();
4590 assert(0 && "FindAliasInfo expected a memory operand");
4596 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
4597 /// looking for aliasing nodes and adding them to the Aliases vector.
4598 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
4599 SmallVector<SDOperand, 8> &Aliases) {
4600 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
4601 std::set<SDNode *> Visited; // Visited node set.
4603 // Get alias information for node.
4606 const Value *SrcValue;
4608 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
4611 Chains.push_back(OriginalChain);
4613 // Look at each chain and determine if it is an alias. If so, add it to the
4614 // aliases list. If not, then continue up the chain looking for the next
4616 while (!Chains.empty()) {
4617 SDOperand Chain = Chains.back();
4620 // Don't bother if we've been before.
4621 if (Visited.find(Chain.Val) != Visited.end()) continue;
4622 Visited.insert(Chain.Val);
4624 switch (Chain.getOpcode()) {
4625 case ISD::EntryToken:
4626 // Entry token is ideal chain operand, but handled in FindBetterChain.
4631 // Get alias information for Chain.
4634 const Value *OpSrcValue;
4635 int OpSrcValueOffset;
4636 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
4637 OpSrcValue, OpSrcValueOffset);
4639 // If chain is alias then stop here.
4640 if (!(IsLoad && IsOpLoad) &&
4641 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
4642 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
4643 Aliases.push_back(Chain);
4645 // Look further up the chain.
4646 Chains.push_back(Chain.getOperand(0));
4647 // Clean up old chain.
4648 AddToWorkList(Chain.Val);
4653 case ISD::TokenFactor:
4654 // We have to check each of the operands of the token factor, so we queue
4655 // then up. Adding the operands to the queue (stack) in reverse order
4656 // maintains the original order and increases the likelihood that getNode
4657 // will find a matching token factor (CSE.)
4658 for (unsigned n = Chain.getNumOperands(); n;)
4659 Chains.push_back(Chain.getOperand(--n));
4660 // Eliminate the token factor if we can.
4661 AddToWorkList(Chain.Val);
4665 // For all other instructions we will just have to take what we can get.
4666 Aliases.push_back(Chain);
4672 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
4673 /// for a better chain (aliasing node.)
4674 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
4675 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
4677 // Accumulate all the aliases to this node.
4678 GatherAllAliases(N, OldChain, Aliases);
4680 if (Aliases.size() == 0) {
4681 // If no operands then chain to entry token.
4682 return DAG.getEntryNode();
4683 } else if (Aliases.size() == 1) {
4684 // If a single operand then chain to it. We don't need to revisit it.
4688 // Construct a custom tailored token factor.
4689 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4690 &Aliases[0], Aliases.size());
4692 // Make sure the old chain gets cleaned up.
4693 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
4698 // SelectionDAG::Combine - This is the entry point for the file.
4700 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
4701 if (!RunningAfterLegalize && ViewDAGCombine1)
4703 if (RunningAfterLegalize && ViewDAGCombine2)
4705 /// run - This is the main entry point to this class.
4707 DAGCombiner(*this, AA).Run(RunningAfterLegalize);