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/ADT/Statistic.h"
33 #include "llvm/Analysis/AliasAnalysis.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/CommandLine.h"
47 static Statistic<> NodesCombined ("dagcombiner",
48 "Number of dag nodes combined");
50 static Statistic<> PreIndexedNodes ("pre_indexed_ops",
51 "Number of pre-indexed nodes created");
52 static Statistic<> PostIndexedNodes ("post_indexed_ops",
53 "Number of post-indexed nodes created");
56 CombinerAA("combiner-alias-analysis", cl::Hidden,
57 cl::desc("Turn on alias analysis during testing"));
60 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
61 cl::desc("Include global information in alias analysis"));
63 //------------------------------ DAGCombiner ---------------------------------//
65 class VISIBILITY_HIDDEN DAGCombiner {
70 // Worklist of all of the nodes that need to be simplified.
71 std::vector<SDNode*> WorkList;
73 // AA - Used for DAG load/store alias analysis.
76 /// AddUsersToWorkList - When an instruction is simplified, add all users of
77 /// the instruction to the work lists because they might get more simplified
80 void AddUsersToWorkList(SDNode *N) {
81 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
86 /// removeFromWorkList - remove all instances of N from the worklist.
88 void removeFromWorkList(SDNode *N) {
89 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
94 /// AddToWorkList - Add to the work list making sure it's instance is at the
95 /// the back (next to be processed.)
96 void AddToWorkList(SDNode *N) {
97 removeFromWorkList(N);
98 WorkList.push_back(N);
101 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
103 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
105 DEBUG(std::cerr << "\nReplacing.1 "; N->dump();
106 std::cerr << "\nWith: "; To[0].Val->dump(&DAG);
107 std::cerr << " and " << NumTo-1 << " other values\n");
108 std::vector<SDNode*> NowDead;
109 DAG.ReplaceAllUsesWith(N, To, &NowDead);
112 // Push the new nodes and any users onto the worklist
113 for (unsigned i = 0, e = NumTo; i != e; ++i) {
114 AddToWorkList(To[i].Val);
115 AddUsersToWorkList(To[i].Val);
119 // Nodes can be reintroduced into the worklist. Make sure we do not
120 // process a node that has been replaced.
121 removeFromWorkList(N);
122 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
123 removeFromWorkList(NowDead[i]);
125 // Finally, since the node is now dead, remove it from the graph.
127 return SDOperand(N, 0);
130 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
131 return CombineTo(N, &Res, 1, AddTo);
134 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
136 SDOperand To[] = { Res0, Res1 };
137 return CombineTo(N, To, 2, AddTo);
141 /// SimplifyDemandedBits - Check the specified integer node value to see if
142 /// it can be simplified or if things it uses can be simplified by bit
143 /// propagation. If so, return true.
144 bool SimplifyDemandedBits(SDOperand Op) {
145 TargetLowering::TargetLoweringOpt TLO(DAG);
146 uint64_t KnownZero, KnownOne;
147 uint64_t Demanded = MVT::getIntVTBitMask(Op.getValueType());
148 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
152 AddToWorkList(Op.Val);
154 // Replace the old value with the new one.
156 DEBUG(std::cerr << "\nReplacing.2 "; TLO.Old.Val->dump();
157 std::cerr << "\nWith: "; TLO.New.Val->dump(&DAG);
160 std::vector<SDNode*> NowDead;
161 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, NowDead);
163 // Push the new node and any (possibly new) users onto the worklist.
164 AddToWorkList(TLO.New.Val);
165 AddUsersToWorkList(TLO.New.Val);
167 // Nodes can end up on the worklist more than once. Make sure we do
168 // not process a node that has been replaced.
169 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
170 removeFromWorkList(NowDead[i]);
172 // Finally, if the node is now dead, remove it from the graph. The node
173 // may not be dead if the replacement process recursively simplified to
174 // something else needing this node.
175 if (TLO.Old.Val->use_empty()) {
176 removeFromWorkList(TLO.Old.Val);
177 DAG.DeleteNode(TLO.Old.Val);
182 /// CombineToPreIndexedLoadStore - Try turning a load / store and a
183 /// pre-indexed load / store when the base pointer is a add or subtract
184 /// and it has other uses besides the load / store. After the
185 /// transformation, the new indexed load / store has effectively folded
186 /// the add / subtract in and all of its other uses are redirected to the
187 /// new load / store.
188 bool CombineToPreIndexedLoadStore(SDNode *N) {
194 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
195 Ptr = LD->getBasePtr();
196 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
197 Ptr = ST->getBasePtr();
202 if ((Ptr.getOpcode() == ISD::ADD || Ptr.getOpcode() == ISD::SUB) &&
203 Ptr.Val->use_size() > 1) {
206 ISD::MemOpAddrMode AM = ISD::UNINDEXED;
207 if (TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) {
208 // Try turning it into a pre-indexed load / store except when
209 // 1) Another use of base ptr is a predecessor of N. If ptr is folded
210 // that would create a cycle.
211 // 2) All uses are load / store ops that use it as base ptr and offset
212 // is just an addressing mode immediate.
213 // 3) If the would-be new base may not to be dead at N.
215 bool OffIsAMImm = Offset.getOpcode() == ISD::Constant && TLI.
216 isLegalAddressImmediate(cast<ConstantSDNode>(Offset)->getValue());
219 for (SDNode::use_iterator I = BasePtr.Val->use_begin(),
220 E = BasePtr.Val->use_end(); I != E; ++I) {
224 if (Use->getOpcode() == ISD::CopyToReg)
226 if (OffIsAMImm && (Use->getOpcode() == ISD::ADD ||
227 Use->getOpcode() == ISD::SUB)) {
228 for (SDNode::use_iterator II = Use->use_begin(),
229 EE = Use->use_end(); II != EE; ++II) {
230 SDNode *UseUse = *II;
231 if (UseUse->getOpcode() == ISD::LOAD &&
232 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use)
234 else if (UseUse->getOpcode() == ISD::STORE &&
235 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)
241 // Now check for #1 and #2.
242 unsigned NumRealUses = 0;
244 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
245 E = Ptr.Val->use_end(); I != E; ++I) {
249 if (Use->isPredecessor(N))
254 } else if (Use->getOpcode() == ISD::LOAD) {
255 if (cast<LoadSDNode>(Use)->getBasePtr().Val != Ptr.Val)
257 } else if (Use->getOpcode() == ISD::STORE) {
258 if (cast<StoreSDNode>(Use)->getBasePtr().Val != Ptr.Val)
264 if (NumRealUses == 0)
267 SDOperand Result = isLoad
268 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
269 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
272 DEBUG(std::cerr << "\nReplacing.4 "; N->dump();
273 std::cerr << "\nWith: "; Result.Val->dump(&DAG);
275 std::vector<SDNode*> NowDead;
277 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
279 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
282 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
286 // Nodes can end up on the worklist more than once. Make sure we do
287 // not process a node that has been replaced.
288 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
289 removeFromWorkList(NowDead[i]);
290 // Finally, since the node is now dead, remove it from the graph.
293 // Replace the uses of Ptr with uses of the updated base value.
294 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
296 removeFromWorkList(Ptr.Val);
297 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
298 removeFromWorkList(NowDead[i]);
299 DAG.DeleteNode(Ptr.Val);
307 /// CombineToPostIndexedLoadStore - Try combine a load / store with a
308 /// add / sub of the base pointer node into a post-indexed load / store.
309 /// The transformation folded the add / subtract into the new indexed
310 /// load / store effectively and all of its uses are redirected to the
311 /// new load / store.
312 bool CombineToPostIndexedLoadStore(SDNode *N) {
319 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
320 Ptr = LD->getBasePtr();
321 VT = LD->getLoadedVT();
322 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
323 Ptr = ST->getBasePtr();
324 VT = ST->getStoredVT();
329 if (Ptr.Val->use_size() > 1) {
330 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
331 E = Ptr.Val->use_end(); I != E; ++I) {
334 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
339 ISD::MemOpAddrMode AM = ISD::UNINDEXED;
340 if (TLI.getPostIndexedAddressParts(Op, VT, BasePtr, Offset, AM,DAG) &&
341 BasePtr.Val == Ptr.Val) {
342 // Try turning it into a post-indexed load / store except when
343 // 1) Op must be independent of N, i.e. Op is neither a predecessor
344 // nor a successor of N. Otherwise, if Op is folded that would
346 // 2) All uses are load / store ops that use it as base ptr and offset
347 // is just an addressing mode immediate.
348 // 3) If the would-be new base may not to be dead at N.
350 bool OffIsAMImm = Offset.getOpcode() == ISD::Constant && TLI.
351 isLegalAddressImmediate(cast<ConstantSDNode>(Offset)->getValue());
354 bool TryNext = false;
355 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
356 EE = BasePtr.Val->use_end(); II != EE; ++II) {
360 if (Use->getOpcode() == ISD::CopyToReg) {
365 if (OffIsAMImm && (Use->getOpcode() == ISD::ADD ||
366 Use->getOpcode() == ISD::SUB)) {
367 for (SDNode::use_iterator III = Use->use_begin(),
368 EEE = Use->use_end(); III != EEE; ++III) {
369 SDNode *UseUse = *III;
370 if (UseUse->getOpcode() == ISD::LOAD &&
371 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) {
374 } else if (UseUse->getOpcode() == ISD::STORE &&
375 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use) {
388 unsigned NumRealUses = 0;
389 for (SDNode::use_iterator II = Op->use_begin(), EE = Op->use_end();
392 if (Use->getOpcode() == ISD::LOAD) {
393 if (cast<LoadSDNode>(Use)->getBasePtr().Val != Op)
395 } else if (Use->getOpcode() == ISD::STORE) {
396 if (cast<StoreSDNode>(Use)->getBasePtr().Val != Op)
401 if (NumRealUses == 0)
406 if (!Op->isPredecessor(N) && !N->isPredecessor(Op)) {
407 SDOperand Result = isLoad
408 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
409 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
412 DEBUG(std::cerr << "\nReplacing.5 "; N->dump();
413 std::cerr << "\nWith: "; Result.Val->dump(&DAG);
415 std::vector<SDNode*> NowDead;
417 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
419 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
422 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
426 // Nodes can end up on the worklist more than once. Make sure we do
427 // not process a node that has been replaced.
428 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
429 removeFromWorkList(NowDead[i]);
430 // Finally, since the node is now dead, remove it from the graph.
433 // Replace the uses of Use with uses of the updated base value.
434 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
435 Result.getValue(isLoad ? 1 : 0),
437 removeFromWorkList(Op);
438 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
439 removeFromWorkList(NowDead[i]);
450 /// visit - call the node-specific routine that knows how to fold each
451 /// particular type of node.
452 SDOperand visit(SDNode *N);
454 // Visitation implementation - Implement dag node combining for different
455 // node types. The semantics are as follows:
457 // SDOperand.Val == 0 - No change was made
458 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
459 // otherwise - N should be replaced by the returned Operand.
461 SDOperand visitTokenFactor(SDNode *N);
462 SDOperand visitADD(SDNode *N);
463 SDOperand visitSUB(SDNode *N);
464 SDOperand visitMUL(SDNode *N);
465 SDOperand visitSDIV(SDNode *N);
466 SDOperand visitUDIV(SDNode *N);
467 SDOperand visitSREM(SDNode *N);
468 SDOperand visitUREM(SDNode *N);
469 SDOperand visitMULHU(SDNode *N);
470 SDOperand visitMULHS(SDNode *N);
471 SDOperand visitAND(SDNode *N);
472 SDOperand visitOR(SDNode *N);
473 SDOperand visitXOR(SDNode *N);
474 SDOperand visitVBinOp(SDNode *N, ISD::NodeType IntOp, ISD::NodeType FPOp);
475 SDOperand visitSHL(SDNode *N);
476 SDOperand visitSRA(SDNode *N);
477 SDOperand visitSRL(SDNode *N);
478 SDOperand visitCTLZ(SDNode *N);
479 SDOperand visitCTTZ(SDNode *N);
480 SDOperand visitCTPOP(SDNode *N);
481 SDOperand visitSELECT(SDNode *N);
482 SDOperand visitSELECT_CC(SDNode *N);
483 SDOperand visitSETCC(SDNode *N);
484 SDOperand visitSIGN_EXTEND(SDNode *N);
485 SDOperand visitZERO_EXTEND(SDNode *N);
486 SDOperand visitANY_EXTEND(SDNode *N);
487 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
488 SDOperand visitTRUNCATE(SDNode *N);
489 SDOperand visitBIT_CONVERT(SDNode *N);
490 SDOperand visitVBIT_CONVERT(SDNode *N);
491 SDOperand visitFADD(SDNode *N);
492 SDOperand visitFSUB(SDNode *N);
493 SDOperand visitFMUL(SDNode *N);
494 SDOperand visitFDIV(SDNode *N);
495 SDOperand visitFREM(SDNode *N);
496 SDOperand visitFCOPYSIGN(SDNode *N);
497 SDOperand visitSINT_TO_FP(SDNode *N);
498 SDOperand visitUINT_TO_FP(SDNode *N);
499 SDOperand visitFP_TO_SINT(SDNode *N);
500 SDOperand visitFP_TO_UINT(SDNode *N);
501 SDOperand visitFP_ROUND(SDNode *N);
502 SDOperand visitFP_ROUND_INREG(SDNode *N);
503 SDOperand visitFP_EXTEND(SDNode *N);
504 SDOperand visitFNEG(SDNode *N);
505 SDOperand visitFABS(SDNode *N);
506 SDOperand visitBRCOND(SDNode *N);
507 SDOperand visitBR_CC(SDNode *N);
508 SDOperand visitLOAD(SDNode *N);
509 SDOperand visitSTORE(SDNode *N);
510 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
511 SDOperand visitVINSERT_VECTOR_ELT(SDNode *N);
512 SDOperand visitVBUILD_VECTOR(SDNode *N);
513 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
514 SDOperand visitVVECTOR_SHUFFLE(SDNode *N);
516 SDOperand XformToShuffleWithZero(SDNode *N);
517 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
519 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
520 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
521 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
522 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
523 SDOperand N3, ISD::CondCode CC);
524 SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
525 ISD::CondCode Cond, bool foldBooleans = true);
526 SDOperand ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(SDNode *, MVT::ValueType);
527 SDOperand BuildSDIV(SDNode *N);
528 SDOperand BuildUDIV(SDNode *N);
529 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
531 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
532 /// looking for aliasing nodes and adding them to the Aliases vector.
533 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
534 SmallVector<SDOperand, 8> &Aliases);
536 /// isAlias - Return true if there is any possibility that the two addresses
538 bool isAlias(SDOperand Ptr1, int64_t Size1,
539 const Value *SrcValue1, int SrcValueOffset1,
540 SDOperand Ptr2, int64_t Size2,
541 const Value *SrcValue2, int SrcValueOffset2);
543 /// FindAliasInfo - Extracts the relevant alias information from the memory
544 /// node. Returns true if the operand was a load.
545 bool FindAliasInfo(SDNode *N,
546 SDOperand &Ptr, int64_t &Size,
547 const Value *&SrcValue, int &SrcValueOffset);
549 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
550 /// looking for a better chain (aliasing node.)
551 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
554 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
556 TLI(D.getTargetLoweringInfo()),
557 AfterLegalize(false),
560 /// Run - runs the dag combiner on all nodes in the work list
561 void Run(bool RunningAfterLegalize);
565 //===----------------------------------------------------------------------===//
566 // TargetLowering::DAGCombinerInfo implementation
567 //===----------------------------------------------------------------------===//
569 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
570 ((DAGCombiner*)DC)->AddToWorkList(N);
573 SDOperand TargetLowering::DAGCombinerInfo::
574 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
575 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
578 SDOperand TargetLowering::DAGCombinerInfo::
579 CombineTo(SDNode *N, SDOperand Res) {
580 return ((DAGCombiner*)DC)->CombineTo(N, Res);
584 SDOperand TargetLowering::DAGCombinerInfo::
585 CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
586 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
592 //===----------------------------------------------------------------------===//
595 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
596 // that selects between the values 1 and 0, making it equivalent to a setcc.
597 // Also, set the incoming LHS, RHS, and CC references to the appropriate
598 // nodes based on the type of node we are checking. This simplifies life a
599 // bit for the callers.
600 static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
602 if (N.getOpcode() == ISD::SETCC) {
603 LHS = N.getOperand(0);
604 RHS = N.getOperand(1);
605 CC = N.getOperand(2);
608 if (N.getOpcode() == ISD::SELECT_CC &&
609 N.getOperand(2).getOpcode() == ISD::Constant &&
610 N.getOperand(3).getOpcode() == ISD::Constant &&
611 cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
612 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
613 LHS = N.getOperand(0);
614 RHS = N.getOperand(1);
615 CC = N.getOperand(4);
621 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
622 // one use. If this is true, it allows the users to invert the operation for
623 // free when it is profitable to do so.
624 static bool isOneUseSetCC(SDOperand N) {
625 SDOperand N0, N1, N2;
626 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
631 SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
632 MVT::ValueType VT = N0.getValueType();
633 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
634 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
635 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
636 if (isa<ConstantSDNode>(N1)) {
637 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
638 AddToWorkList(OpNode.Val);
639 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
640 } else if (N0.hasOneUse()) {
641 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
642 AddToWorkList(OpNode.Val);
643 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
646 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
647 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
648 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
649 if (isa<ConstantSDNode>(N0)) {
650 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
651 AddToWorkList(OpNode.Val);
652 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
653 } else if (N1.hasOneUse()) {
654 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
655 AddToWorkList(OpNode.Val);
656 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
662 void DAGCombiner::Run(bool RunningAfterLegalize) {
663 // set the instance variable, so that the various visit routines may use it.
664 AfterLegalize = RunningAfterLegalize;
666 // Add all the dag nodes to the worklist.
667 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
668 E = DAG.allnodes_end(); I != E; ++I)
669 WorkList.push_back(I);
671 // Create a dummy node (which is not added to allnodes), that adds a reference
672 // to the root node, preventing it from being deleted, and tracking any
673 // changes of the root.
674 HandleSDNode Dummy(DAG.getRoot());
676 // The root of the dag may dangle to deleted nodes until the dag combiner is
677 // done. Set it to null to avoid confusion.
678 DAG.setRoot(SDOperand());
680 /// DagCombineInfo - Expose the DAG combiner to the target combiner impls.
681 TargetLowering::DAGCombinerInfo
682 DagCombineInfo(DAG, !RunningAfterLegalize, this);
684 // while the worklist isn't empty, inspect the node on the end of it and
685 // try and combine it.
686 while (!WorkList.empty()) {
687 SDNode *N = WorkList.back();
690 // If N has no uses, it is dead. Make sure to revisit all N's operands once
691 // N is deleted from the DAG, since they too may now be dead or may have a
692 // reduced number of uses, allowing other xforms.
693 if (N->use_empty() && N != &Dummy) {
694 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
695 AddToWorkList(N->getOperand(i).Val);
701 SDOperand RV = visit(N);
703 // If nothing happened, try a target-specific DAG combine.
705 assert(N->getOpcode() != ISD::DELETED_NODE &&
706 "Node was deleted but visit returned NULL!");
707 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
708 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode()))
709 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
714 // If we get back the same node we passed in, rather than a new node or
715 // zero, we know that the node must have defined multiple values and
716 // CombineTo was used. Since CombineTo takes care of the worklist
717 // mechanics for us, we have no work to do in this case.
719 assert(N->getOpcode() != ISD::DELETED_NODE &&
720 RV.Val->getOpcode() != ISD::DELETED_NODE &&
721 "Node was deleted but visit returned new node!");
723 DEBUG(std::cerr << "\nReplacing.3 "; N->dump();
724 std::cerr << "\nWith: "; RV.Val->dump(&DAG);
726 std::vector<SDNode*> NowDead;
727 if (N->getNumValues() == RV.Val->getNumValues())
728 DAG.ReplaceAllUsesWith(N, RV.Val, &NowDead);
730 assert(N->getValueType(0) == RV.getValueType() && "Type mismatch");
732 DAG.ReplaceAllUsesWith(N, &OpV, &NowDead);
735 // Push the new node and any users onto the worklist
736 AddToWorkList(RV.Val);
737 AddUsersToWorkList(RV.Val);
739 // Nodes can be reintroduced into the worklist. Make sure we do not
740 // process a node that has been replaced.
741 removeFromWorkList(N);
742 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
743 removeFromWorkList(NowDead[i]);
745 // Finally, since the node is now dead, remove it from the graph.
751 // If the root changed (e.g. it was a dead load, update the root).
752 DAG.setRoot(Dummy.getValue());
755 SDOperand DAGCombiner::visit(SDNode *N) {
756 switch(N->getOpcode()) {
758 case ISD::TokenFactor: return visitTokenFactor(N);
759 case ISD::ADD: return visitADD(N);
760 case ISD::SUB: return visitSUB(N);
761 case ISD::MUL: return visitMUL(N);
762 case ISD::SDIV: return visitSDIV(N);
763 case ISD::UDIV: return visitUDIV(N);
764 case ISD::SREM: return visitSREM(N);
765 case ISD::UREM: return visitUREM(N);
766 case ISD::MULHU: return visitMULHU(N);
767 case ISD::MULHS: return visitMULHS(N);
768 case ISD::AND: return visitAND(N);
769 case ISD::OR: return visitOR(N);
770 case ISD::XOR: return visitXOR(N);
771 case ISD::SHL: return visitSHL(N);
772 case ISD::SRA: return visitSRA(N);
773 case ISD::SRL: return visitSRL(N);
774 case ISD::CTLZ: return visitCTLZ(N);
775 case ISD::CTTZ: return visitCTTZ(N);
776 case ISD::CTPOP: return visitCTPOP(N);
777 case ISD::SELECT: return visitSELECT(N);
778 case ISD::SELECT_CC: return visitSELECT_CC(N);
779 case ISD::SETCC: return visitSETCC(N);
780 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
781 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
782 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
783 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
784 case ISD::TRUNCATE: return visitTRUNCATE(N);
785 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
786 case ISD::VBIT_CONVERT: return visitVBIT_CONVERT(N);
787 case ISD::FADD: return visitFADD(N);
788 case ISD::FSUB: return visitFSUB(N);
789 case ISD::FMUL: return visitFMUL(N);
790 case ISD::FDIV: return visitFDIV(N);
791 case ISD::FREM: return visitFREM(N);
792 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
793 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
794 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
795 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
796 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
797 case ISD::FP_ROUND: return visitFP_ROUND(N);
798 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
799 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
800 case ISD::FNEG: return visitFNEG(N);
801 case ISD::FABS: return visitFABS(N);
802 case ISD::BRCOND: return visitBRCOND(N);
803 case ISD::BR_CC: return visitBR_CC(N);
804 case ISD::LOAD: return visitLOAD(N);
805 case ISD::STORE: return visitSTORE(N);
806 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
807 case ISD::VINSERT_VECTOR_ELT: return visitVINSERT_VECTOR_ELT(N);
808 case ISD::VBUILD_VECTOR: return visitVBUILD_VECTOR(N);
809 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
810 case ISD::VVECTOR_SHUFFLE: return visitVVECTOR_SHUFFLE(N);
811 case ISD::VADD: return visitVBinOp(N, ISD::ADD , ISD::FADD);
812 case ISD::VSUB: return visitVBinOp(N, ISD::SUB , ISD::FSUB);
813 case ISD::VMUL: return visitVBinOp(N, ISD::MUL , ISD::FMUL);
814 case ISD::VSDIV: return visitVBinOp(N, ISD::SDIV, ISD::FDIV);
815 case ISD::VUDIV: return visitVBinOp(N, ISD::UDIV, ISD::UDIV);
816 case ISD::VAND: return visitVBinOp(N, ISD::AND , ISD::AND);
817 case ISD::VOR: return visitVBinOp(N, ISD::OR , ISD::OR);
818 case ISD::VXOR: return visitVBinOp(N, ISD::XOR , ISD::XOR);
823 /// getInputChainForNode - Given a node, return its input chain if it has one,
824 /// otherwise return a null sd operand.
825 static SDOperand getInputChainForNode(SDNode *N) {
826 if (unsigned NumOps = N->getNumOperands()) {
827 if (N->getOperand(0).getValueType() == MVT::Other)
828 return N->getOperand(0);
829 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
830 return N->getOperand(NumOps-1);
831 for (unsigned i = 1; i < NumOps-1; ++i)
832 if (N->getOperand(i).getValueType() == MVT::Other)
833 return N->getOperand(i);
835 return SDOperand(0, 0);
838 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
839 // If N has two operands, where one has an input chain equal to the other,
840 // the 'other' chain is redundant.
841 if (N->getNumOperands() == 2) {
842 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
843 return N->getOperand(0);
844 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
845 return N->getOperand(1);
849 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
850 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
851 bool Changed = false; // If we should replace this token factor.
853 // Start out with this token factor.
856 // Iterate through token factors. The TFs grows when new token factors are
858 for (unsigned i = 0; i < TFs.size(); ++i) {
861 // Check each of the operands.
862 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
863 SDOperand Op = TF->getOperand(i);
865 switch (Op.getOpcode()) {
866 case ISD::EntryToken:
867 // Entry tokens don't need to be added to the list. They are
872 case ISD::TokenFactor:
873 if ((CombinerAA || Op.hasOneUse()) &&
874 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
875 // Queue up for processing.
876 TFs.push_back(Op.Val);
877 // Clean up in case the token factor is removed.
878 AddToWorkList(Op.Val);
885 // Only add if not there prior.
886 if (std::find(Ops.begin(), Ops.end(), Op) == Ops.end())
895 // If we've change things around then replace token factor.
897 if (Ops.size() == 0) {
898 // The entry token is the only possible outcome.
899 Result = DAG.getEntryNode();
901 // New and improved token factor.
902 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
905 // Don't add users to work list.
906 return CombineTo(N, Result, false);
912 SDOperand DAGCombiner::visitADD(SDNode *N) {
913 SDOperand N0 = N->getOperand(0);
914 SDOperand N1 = N->getOperand(1);
915 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
916 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
917 MVT::ValueType VT = N0.getValueType();
919 // fold (add c1, c2) -> c1+c2
921 return DAG.getNode(ISD::ADD, VT, N0, N1);
922 // canonicalize constant to RHS
924 return DAG.getNode(ISD::ADD, VT, N1, N0);
925 // fold (add x, 0) -> x
926 if (N1C && N1C->isNullValue())
928 // fold ((c1-A)+c2) -> (c1+c2)-A
929 if (N1C && N0.getOpcode() == ISD::SUB)
930 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
931 return DAG.getNode(ISD::SUB, VT,
932 DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
935 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
938 // fold ((0-A) + B) -> B-A
939 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
940 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
941 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
942 // fold (A + (0-B)) -> A-B
943 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
944 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
945 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
946 // fold (A+(B-A)) -> B
947 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
948 return N1.getOperand(0);
950 if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
951 return SDOperand(N, 0);
953 // fold (a+b) -> (a|b) iff a and b share no bits.
954 if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
955 uint64_t LHSZero, LHSOne;
956 uint64_t RHSZero, RHSOne;
957 uint64_t Mask = MVT::getIntVTBitMask(VT);
958 TLI.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
960 TLI.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
962 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
963 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
964 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
965 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
966 return DAG.getNode(ISD::OR, VT, N0, N1);
973 SDOperand DAGCombiner::visitSUB(SDNode *N) {
974 SDOperand N0 = N->getOperand(0);
975 SDOperand N1 = N->getOperand(1);
976 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
977 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
978 MVT::ValueType VT = N0.getValueType();
980 // fold (sub x, x) -> 0
982 return DAG.getConstant(0, N->getValueType(0));
983 // fold (sub c1, c2) -> c1-c2
985 return DAG.getNode(ISD::SUB, VT, N0, N1);
986 // fold (sub x, c) -> (add x, -c)
988 return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
990 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
991 return N0.getOperand(1);
993 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
994 return N0.getOperand(0);
998 SDOperand DAGCombiner::visitMUL(SDNode *N) {
999 SDOperand N0 = N->getOperand(0);
1000 SDOperand N1 = N->getOperand(1);
1001 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1002 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1003 MVT::ValueType VT = N0.getValueType();
1005 // fold (mul c1, c2) -> c1*c2
1007 return DAG.getNode(ISD::MUL, VT, N0, N1);
1008 // canonicalize constant to RHS
1010 return DAG.getNode(ISD::MUL, VT, N1, N0);
1011 // fold (mul x, 0) -> 0
1012 if (N1C && N1C->isNullValue())
1014 // fold (mul x, -1) -> 0-x
1015 if (N1C && N1C->isAllOnesValue())
1016 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1017 // fold (mul x, (1 << c)) -> x << c
1018 if (N1C && isPowerOf2_64(N1C->getValue()))
1019 return DAG.getNode(ISD::SHL, VT, N0,
1020 DAG.getConstant(Log2_64(N1C->getValue()),
1021 TLI.getShiftAmountTy()));
1022 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1023 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1024 // FIXME: If the input is something that is easily negated (e.g. a
1025 // single-use add), we should put the negate there.
1026 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1027 DAG.getNode(ISD::SHL, VT, N0,
1028 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1029 TLI.getShiftAmountTy())));
1032 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1033 if (N1C && N0.getOpcode() == ISD::SHL &&
1034 isa<ConstantSDNode>(N0.getOperand(1))) {
1035 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1036 AddToWorkList(C3.Val);
1037 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1040 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1043 SDOperand Sh(0,0), Y(0,0);
1044 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1045 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1046 N0.Val->hasOneUse()) {
1048 } else if (N1.getOpcode() == ISD::SHL &&
1049 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1053 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1054 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1057 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1058 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1059 isa<ConstantSDNode>(N0.getOperand(1))) {
1060 return DAG.getNode(ISD::ADD, VT,
1061 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1062 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1066 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1072 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1073 SDOperand N0 = N->getOperand(0);
1074 SDOperand N1 = N->getOperand(1);
1075 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1076 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1077 MVT::ValueType VT = N->getValueType(0);
1079 // fold (sdiv c1, c2) -> c1/c2
1080 if (N0C && N1C && !N1C->isNullValue())
1081 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1082 // fold (sdiv X, 1) -> X
1083 if (N1C && N1C->getSignExtended() == 1LL)
1085 // fold (sdiv X, -1) -> 0-X
1086 if (N1C && N1C->isAllOnesValue())
1087 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1088 // If we know the sign bits of both operands are zero, strength reduce to a
1089 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1090 uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1091 if (TLI.MaskedValueIsZero(N1, SignBit) &&
1092 TLI.MaskedValueIsZero(N0, SignBit))
1093 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1094 // fold (sdiv X, pow2) -> simple ops after legalize
1095 if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
1096 (isPowerOf2_64(N1C->getSignExtended()) ||
1097 isPowerOf2_64(-N1C->getSignExtended()))) {
1098 // If dividing by powers of two is cheap, then don't perform the following
1100 if (TLI.isPow2DivCheap())
1102 int64_t pow2 = N1C->getSignExtended();
1103 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1104 unsigned lg2 = Log2_64(abs2);
1105 // Splat the sign bit into the register
1106 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1107 DAG.getConstant(MVT::getSizeInBits(VT)-1,
1108 TLI.getShiftAmountTy()));
1109 AddToWorkList(SGN.Val);
1110 // Add (N0 < 0) ? abs2 - 1 : 0;
1111 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1112 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
1113 TLI.getShiftAmountTy()));
1114 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1115 AddToWorkList(SRL.Val);
1116 AddToWorkList(ADD.Val); // Divide by pow2
1117 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1118 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1119 // If we're dividing by a positive value, we're done. Otherwise, we must
1120 // negate the result.
1123 AddToWorkList(SRA.Val);
1124 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1126 // if integer divide is expensive and we satisfy the requirements, emit an
1127 // alternate sequence.
1128 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1129 !TLI.isIntDivCheap()) {
1130 SDOperand Op = BuildSDIV(N);
1131 if (Op.Val) return Op;
1136 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1137 SDOperand N0 = N->getOperand(0);
1138 SDOperand N1 = N->getOperand(1);
1139 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1140 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1141 MVT::ValueType VT = N->getValueType(0);
1143 // fold (udiv c1, c2) -> c1/c2
1144 if (N0C && N1C && !N1C->isNullValue())
1145 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1146 // fold (udiv x, (1 << c)) -> x >>u c
1147 if (N1C && isPowerOf2_64(N1C->getValue()))
1148 return DAG.getNode(ISD::SRL, VT, N0,
1149 DAG.getConstant(Log2_64(N1C->getValue()),
1150 TLI.getShiftAmountTy()));
1151 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1152 if (N1.getOpcode() == ISD::SHL) {
1153 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1154 if (isPowerOf2_64(SHC->getValue())) {
1155 MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
1156 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1157 DAG.getConstant(Log2_64(SHC->getValue()),
1159 AddToWorkList(Add.Val);
1160 return DAG.getNode(ISD::SRL, VT, N0, Add);
1164 // fold (udiv x, c) -> alternate
1165 if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
1166 SDOperand Op = BuildUDIV(N);
1167 if (Op.Val) return Op;
1172 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1173 SDOperand N0 = N->getOperand(0);
1174 SDOperand N1 = N->getOperand(1);
1175 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1176 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1177 MVT::ValueType VT = N->getValueType(0);
1179 // fold (srem c1, c2) -> c1%c2
1180 if (N0C && N1C && !N1C->isNullValue())
1181 return DAG.getNode(ISD::SREM, VT, N0, N1);
1182 // If we know the sign bits of both operands are zero, strength reduce to a
1183 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1184 uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1185 if (TLI.MaskedValueIsZero(N1, SignBit) &&
1186 TLI.MaskedValueIsZero(N0, SignBit))
1187 return DAG.getNode(ISD::UREM, VT, N0, N1);
1189 // Unconditionally lower X%C -> X-X/C*C. This allows the X/C logic to hack on
1190 // the remainder operation.
1191 if (N1C && !N1C->isNullValue()) {
1192 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1193 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
1194 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1195 AddToWorkList(Div.Val);
1196 AddToWorkList(Mul.Val);
1203 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1204 SDOperand N0 = N->getOperand(0);
1205 SDOperand N1 = N->getOperand(1);
1206 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1207 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1208 MVT::ValueType VT = N->getValueType(0);
1210 // fold (urem c1, c2) -> c1%c2
1211 if (N0C && N1C && !N1C->isNullValue())
1212 return DAG.getNode(ISD::UREM, VT, N0, N1);
1213 // fold (urem x, pow2) -> (and x, pow2-1)
1214 if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
1215 return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
1216 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1217 if (N1.getOpcode() == ISD::SHL) {
1218 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1219 if (isPowerOf2_64(SHC->getValue())) {
1220 SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
1221 AddToWorkList(Add.Val);
1222 return DAG.getNode(ISD::AND, VT, N0, Add);
1227 // Unconditionally lower X%C -> X-X/C*C. This allows the X/C logic to hack on
1228 // the remainder operation.
1229 if (N1C && !N1C->isNullValue()) {
1230 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1231 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
1232 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1233 AddToWorkList(Div.Val);
1234 AddToWorkList(Mul.Val);
1241 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1242 SDOperand N0 = N->getOperand(0);
1243 SDOperand N1 = N->getOperand(1);
1244 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1246 // fold (mulhs x, 0) -> 0
1247 if (N1C && N1C->isNullValue())
1249 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1250 if (N1C && N1C->getValue() == 1)
1251 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1252 DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1253 TLI.getShiftAmountTy()));
1257 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1258 SDOperand N0 = N->getOperand(0);
1259 SDOperand N1 = N->getOperand(1);
1260 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1262 // fold (mulhu x, 0) -> 0
1263 if (N1C && N1C->isNullValue())
1265 // fold (mulhu x, 1) -> 0
1266 if (N1C && N1C->getValue() == 1)
1267 return DAG.getConstant(0, N0.getValueType());
1271 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1272 /// two operands of the same opcode, try to simplify it.
1273 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1274 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1275 MVT::ValueType VT = N0.getValueType();
1276 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1278 // For each of OP in AND/OR/XOR:
1279 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1280 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1281 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1282 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1283 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1284 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1285 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1286 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1287 N0.getOperand(0).getValueType(),
1288 N0.getOperand(0), N1.getOperand(0));
1289 AddToWorkList(ORNode.Val);
1290 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1293 // For each of OP in SHL/SRL/SRA/AND...
1294 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1295 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1296 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1297 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1298 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1299 N0.getOperand(1) == N1.getOperand(1)) {
1300 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1301 N0.getOperand(0).getValueType(),
1302 N0.getOperand(0), N1.getOperand(0));
1303 AddToWorkList(ORNode.Val);
1304 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1310 SDOperand DAGCombiner::visitAND(SDNode *N) {
1311 SDOperand N0 = N->getOperand(0);
1312 SDOperand N1 = N->getOperand(1);
1313 SDOperand LL, LR, RL, RR, CC0, CC1;
1314 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1315 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1316 MVT::ValueType VT = N1.getValueType();
1318 // fold (and c1, c2) -> c1&c2
1320 return DAG.getNode(ISD::AND, VT, N0, N1);
1321 // canonicalize constant to RHS
1323 return DAG.getNode(ISD::AND, VT, N1, N0);
1324 // fold (and x, -1) -> x
1325 if (N1C && N1C->isAllOnesValue())
1327 // if (and x, c) is known to be zero, return 0
1328 if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1329 return DAG.getConstant(0, VT);
1331 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1334 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1335 if (N1C && N0.getOpcode() == ISD::OR)
1336 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1337 if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
1339 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1340 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1341 unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
1342 if (TLI.MaskedValueIsZero(N0.getOperand(0),
1343 ~N1C->getValue() & InMask)) {
1344 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1347 // Replace uses of the AND with uses of the Zero extend node.
1350 // We actually want to replace all uses of the any_extend with the
1351 // zero_extend, to avoid duplicating things. This will later cause this
1352 // AND to be folded.
1353 CombineTo(N0.Val, Zext);
1354 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1357 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1358 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1359 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1360 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1362 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1363 MVT::isInteger(LL.getValueType())) {
1364 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1365 if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
1366 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1367 AddToWorkList(ORNode.Val);
1368 return DAG.getSetCC(VT, ORNode, LR, Op1);
1370 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1371 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1372 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1373 AddToWorkList(ANDNode.Val);
1374 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1376 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1377 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1378 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1379 AddToWorkList(ORNode.Val);
1380 return DAG.getSetCC(VT, ORNode, LR, Op1);
1383 // canonicalize equivalent to ll == rl
1384 if (LL == RR && LR == RL) {
1385 Op1 = ISD::getSetCCSwappedOperands(Op1);
1388 if (LL == RL && LR == RR) {
1389 bool isInteger = MVT::isInteger(LL.getValueType());
1390 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1391 if (Result != ISD::SETCC_INVALID)
1392 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1396 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1397 if (N0.getOpcode() == N1.getOpcode()) {
1398 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1399 if (Tmp.Val) return Tmp;
1402 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1403 // fold (and (sra)) -> (and (srl)) when possible.
1404 if (!MVT::isVector(VT) &&
1405 SimplifyDemandedBits(SDOperand(N, 0)))
1406 return SDOperand(N, 0);
1407 // fold (zext_inreg (extload x)) -> (zextload x)
1408 if (ISD::isEXTLoad(N0.Val)) {
1409 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1410 MVT::ValueType EVT = LN0->getLoadedVT();
1411 // If we zero all the possible extended bits, then we can turn this into
1412 // a zextload if we are running before legalize or the operation is legal.
1413 if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1414 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1415 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1416 LN0->getBasePtr(), LN0->getSrcValue(),
1417 LN0->getSrcValueOffset(), EVT);
1419 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1420 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1423 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1424 if (ISD::isSEXTLoad(N0.Val) && N0.hasOneUse()) {
1425 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1426 MVT::ValueType EVT = LN0->getLoadedVT();
1427 // If we zero all the possible extended bits, then we can turn this into
1428 // a zextload if we are running before legalize or the operation is legal.
1429 if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1430 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1431 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1432 LN0->getBasePtr(), LN0->getSrcValue(),
1433 LN0->getSrcValueOffset(), EVT);
1435 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1436 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1440 // fold (and (load x), 255) -> (zextload x, i8)
1441 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1442 if (N1C && N0.getOpcode() == ISD::LOAD) {
1443 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1444 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1446 MVT::ValueType EVT, LoadedVT;
1447 if (N1C->getValue() == 255)
1449 else if (N1C->getValue() == 65535)
1451 else if (N1C->getValue() == ~0U)
1456 LoadedVT = LN0->getLoadedVT();
1457 if (EVT != MVT::Other && LoadedVT > EVT &&
1458 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1459 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1460 // For big endian targets, we need to add an offset to the pointer to
1461 // load the correct bytes. For little endian systems, we merely need to
1462 // read fewer bytes from the same pointer.
1464 (MVT::getSizeInBits(LoadedVT) - MVT::getSizeInBits(EVT)) / 8;
1465 SDOperand NewPtr = LN0->getBasePtr();
1466 if (!TLI.isLittleEndian())
1467 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1468 DAG.getConstant(PtrOff, PtrType));
1469 AddToWorkList(NewPtr.Val);
1471 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1472 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT);
1474 CombineTo(N0.Val, Load, Load.getValue(1));
1475 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1483 SDOperand DAGCombiner::visitOR(SDNode *N) {
1484 SDOperand N0 = N->getOperand(0);
1485 SDOperand N1 = N->getOperand(1);
1486 SDOperand LL, LR, RL, RR, CC0, CC1;
1487 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1488 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1489 MVT::ValueType VT = N1.getValueType();
1490 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1492 // fold (or c1, c2) -> c1|c2
1494 return DAG.getNode(ISD::OR, VT, N0, N1);
1495 // canonicalize constant to RHS
1497 return DAG.getNode(ISD::OR, VT, N1, N0);
1498 // fold (or x, 0) -> x
1499 if (N1C && N1C->isNullValue())
1501 // fold (or x, -1) -> -1
1502 if (N1C && N1C->isAllOnesValue())
1504 // fold (or x, c) -> c iff (x & ~c) == 0
1506 TLI.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
1509 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1512 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1513 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1514 isa<ConstantSDNode>(N0.getOperand(1))) {
1515 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1516 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1518 DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1520 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1521 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1522 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1523 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1525 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1526 MVT::isInteger(LL.getValueType())) {
1527 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1528 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1529 if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1530 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1531 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1532 AddToWorkList(ORNode.Val);
1533 return DAG.getSetCC(VT, ORNode, LR, Op1);
1535 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1536 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1537 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1538 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1539 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1540 AddToWorkList(ANDNode.Val);
1541 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1544 // canonicalize equivalent to ll == rl
1545 if (LL == RR && LR == RL) {
1546 Op1 = ISD::getSetCCSwappedOperands(Op1);
1549 if (LL == RL && LR == RR) {
1550 bool isInteger = MVT::isInteger(LL.getValueType());
1551 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1552 if (Result != ISD::SETCC_INVALID)
1553 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1557 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1558 if (N0.getOpcode() == N1.getOpcode()) {
1559 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1560 if (Tmp.Val) return Tmp;
1563 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1564 if (N0.getOpcode() == ISD::AND &&
1565 N1.getOpcode() == ISD::AND &&
1566 N0.getOperand(1).getOpcode() == ISD::Constant &&
1567 N1.getOperand(1).getOpcode() == ISD::Constant &&
1568 // Don't increase # computations.
1569 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1570 // We can only do this xform if we know that bits from X that are set in C2
1571 // but not in C1 are already zero. Likewise for Y.
1572 uint64_t LHSMask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1573 uint64_t RHSMask = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
1575 if (TLI.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1576 TLI.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1577 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1578 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1583 // See if this is some rotate idiom.
1584 if (SDNode *Rot = MatchRotate(N0, N1))
1585 return SDOperand(Rot, 0);
1591 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1592 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1593 if (Op.getOpcode() == ISD::AND) {
1594 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1595 Mask = Op.getOperand(1);
1596 Op = Op.getOperand(0);
1602 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1610 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1611 // idioms for rotate, and if the target supports rotation instructions, generate
1613 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1614 // Must be a legal type. Expanded an promoted things won't work with rotates.
1615 MVT::ValueType VT = LHS.getValueType();
1616 if (!TLI.isTypeLegal(VT)) return 0;
1618 // The target must have at least one rotate flavor.
1619 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1620 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1621 if (!HasROTL && !HasROTR) return 0;
1623 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1624 SDOperand LHSShift; // The shift.
1625 SDOperand LHSMask; // AND value if any.
1626 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1627 return 0; // Not part of a rotate.
1629 SDOperand RHSShift; // The shift.
1630 SDOperand RHSMask; // AND value if any.
1631 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1632 return 0; // Not part of a rotate.
1634 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1635 return 0; // Not shifting the same value.
1637 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1638 return 0; // Shifts must disagree.
1640 // Canonicalize shl to left side in a shl/srl pair.
1641 if (RHSShift.getOpcode() == ISD::SHL) {
1642 std::swap(LHS, RHS);
1643 std::swap(LHSShift, RHSShift);
1644 std::swap(LHSMask , RHSMask );
1647 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1649 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1650 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1651 if (LHSShift.getOperand(1).getOpcode() == ISD::Constant &&
1652 RHSShift.getOperand(1).getOpcode() == ISD::Constant) {
1653 uint64_t LShVal = cast<ConstantSDNode>(LHSShift.getOperand(1))->getValue();
1654 uint64_t RShVal = cast<ConstantSDNode>(RHSShift.getOperand(1))->getValue();
1655 if ((LShVal + RShVal) != OpSizeInBits)
1660 Rot = DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1661 LHSShift.getOperand(1));
1663 Rot = DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1664 RHSShift.getOperand(1));
1666 // If there is an AND of either shifted operand, apply it to the result.
1667 if (LHSMask.Val || RHSMask.Val) {
1668 uint64_t Mask = MVT::getIntVTBitMask(VT);
1671 uint64_t RHSBits = (1ULL << LShVal)-1;
1672 Mask &= cast<ConstantSDNode>(LHSMask)->getValue() | RHSBits;
1675 uint64_t LHSBits = ~((1ULL << (OpSizeInBits-RShVal))-1);
1676 Mask &= cast<ConstantSDNode>(RHSMask)->getValue() | LHSBits;
1679 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
1685 // If there is a mask here, and we have a variable shift, we can't be sure
1686 // that we're masking out the right stuff.
1687 if (LHSMask.Val || RHSMask.Val)
1690 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
1691 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
1692 if (RHSShift.getOperand(1).getOpcode() == ISD::SUB &&
1693 LHSShift.getOperand(1) == RHSShift.getOperand(1).getOperand(1)) {
1694 if (ConstantSDNode *SUBC =
1695 dyn_cast<ConstantSDNode>(RHSShift.getOperand(1).getOperand(0))) {
1696 if (SUBC->getValue() == OpSizeInBits)
1698 return DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1699 LHSShift.getOperand(1)).Val;
1701 return DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1702 LHSShift.getOperand(1)).Val;
1706 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
1707 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
1708 if (LHSShift.getOperand(1).getOpcode() == ISD::SUB &&
1709 RHSShift.getOperand(1) == LHSShift.getOperand(1).getOperand(1)) {
1710 if (ConstantSDNode *SUBC =
1711 dyn_cast<ConstantSDNode>(LHSShift.getOperand(1).getOperand(0))) {
1712 if (SUBC->getValue() == OpSizeInBits)
1714 return DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1715 LHSShift.getOperand(1)).Val;
1717 return DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1718 RHSShift.getOperand(1)).Val;
1726 SDOperand DAGCombiner::visitXOR(SDNode *N) {
1727 SDOperand N0 = N->getOperand(0);
1728 SDOperand N1 = N->getOperand(1);
1729 SDOperand LHS, RHS, CC;
1730 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1731 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1732 MVT::ValueType VT = N0.getValueType();
1734 // fold (xor c1, c2) -> c1^c2
1736 return DAG.getNode(ISD::XOR, VT, N0, N1);
1737 // canonicalize constant to RHS
1739 return DAG.getNode(ISD::XOR, VT, N1, N0);
1740 // fold (xor x, 0) -> x
1741 if (N1C && N1C->isNullValue())
1744 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
1747 // fold !(x cc y) -> (x !cc y)
1748 if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
1749 bool isInt = MVT::isInteger(LHS.getValueType());
1750 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
1752 if (N0.getOpcode() == ISD::SETCC)
1753 return DAG.getSetCC(VT, LHS, RHS, NotCC);
1754 if (N0.getOpcode() == ISD::SELECT_CC)
1755 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
1756 assert(0 && "Unhandled SetCC Equivalent!");
1759 // fold !(x or y) -> (!x and !y) iff x or y are setcc
1760 if (N1C && N1C->getValue() == 1 &&
1761 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1762 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1763 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
1764 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1765 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
1766 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
1767 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1768 return DAG.getNode(NewOpcode, VT, LHS, RHS);
1771 // fold !(x or y) -> (!x and !y) iff x or y are constants
1772 if (N1C && N1C->isAllOnesValue() &&
1773 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1774 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1775 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
1776 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1777 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
1778 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
1779 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1780 return DAG.getNode(NewOpcode, VT, LHS, RHS);
1783 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
1784 if (N1C && N0.getOpcode() == ISD::XOR) {
1785 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
1786 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1788 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
1789 DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
1791 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
1792 DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
1794 // fold (xor x, x) -> 0
1796 if (!MVT::isVector(VT)) {
1797 return DAG.getConstant(0, VT);
1798 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1799 // Produce a vector of zeros.
1800 SDOperand El = DAG.getConstant(0, MVT::getVectorBaseType(VT));
1801 std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
1802 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1806 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
1807 if (N0.getOpcode() == N1.getOpcode()) {
1808 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1809 if (Tmp.Val) return Tmp;
1812 // Simplify the expression using non-local knowledge.
1813 if (!MVT::isVector(VT) &&
1814 SimplifyDemandedBits(SDOperand(N, 0)))
1815 return SDOperand(N, 0);
1820 SDOperand DAGCombiner::visitSHL(SDNode *N) {
1821 SDOperand N0 = N->getOperand(0);
1822 SDOperand N1 = N->getOperand(1);
1823 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1824 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1825 MVT::ValueType VT = N0.getValueType();
1826 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1828 // fold (shl c1, c2) -> c1<<c2
1830 return DAG.getNode(ISD::SHL, VT, N0, N1);
1831 // fold (shl 0, x) -> 0
1832 if (N0C && N0C->isNullValue())
1834 // fold (shl x, c >= size(x)) -> undef
1835 if (N1C && N1C->getValue() >= OpSizeInBits)
1836 return DAG.getNode(ISD::UNDEF, VT);
1837 // fold (shl x, 0) -> x
1838 if (N1C && N1C->isNullValue())
1840 // if (shl x, c) is known to be zero, return 0
1841 if (TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1842 return DAG.getConstant(0, VT);
1843 if (SimplifyDemandedBits(SDOperand(N, 0)))
1844 return SDOperand(N, 0);
1845 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
1846 if (N1C && N0.getOpcode() == ISD::SHL &&
1847 N0.getOperand(1).getOpcode() == ISD::Constant) {
1848 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1849 uint64_t c2 = N1C->getValue();
1850 if (c1 + c2 > OpSizeInBits)
1851 return DAG.getConstant(0, VT);
1852 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
1853 DAG.getConstant(c1 + c2, N1.getValueType()));
1855 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
1856 // (srl (and x, -1 << c1), c1-c2)
1857 if (N1C && N0.getOpcode() == ISD::SRL &&
1858 N0.getOperand(1).getOpcode() == ISD::Constant) {
1859 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1860 uint64_t c2 = N1C->getValue();
1861 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1862 DAG.getConstant(~0ULL << c1, VT));
1864 return DAG.getNode(ISD::SHL, VT, Mask,
1865 DAG.getConstant(c2-c1, N1.getValueType()));
1867 return DAG.getNode(ISD::SRL, VT, Mask,
1868 DAG.getConstant(c1-c2, N1.getValueType()));
1870 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
1871 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
1872 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1873 DAG.getConstant(~0ULL << N1C->getValue(), VT));
1874 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1<<c2)
1875 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1876 isa<ConstantSDNode>(N0.getOperand(1))) {
1877 return DAG.getNode(ISD::ADD, VT,
1878 DAG.getNode(ISD::SHL, VT, N0.getOperand(0), N1),
1879 DAG.getNode(ISD::SHL, VT, N0.getOperand(1), N1));
1884 SDOperand DAGCombiner::visitSRA(SDNode *N) {
1885 SDOperand N0 = N->getOperand(0);
1886 SDOperand N1 = N->getOperand(1);
1887 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1888 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1889 MVT::ValueType VT = N0.getValueType();
1891 // fold (sra c1, c2) -> c1>>c2
1893 return DAG.getNode(ISD::SRA, VT, N0, N1);
1894 // fold (sra 0, x) -> 0
1895 if (N0C && N0C->isNullValue())
1897 // fold (sra -1, x) -> -1
1898 if (N0C && N0C->isAllOnesValue())
1900 // fold (sra x, c >= size(x)) -> undef
1901 if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
1902 return DAG.getNode(ISD::UNDEF, VT);
1903 // fold (sra x, 0) -> x
1904 if (N1C && N1C->isNullValue())
1906 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
1908 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
1909 unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
1912 default: EVT = MVT::Other; break;
1913 case 1: EVT = MVT::i1; break;
1914 case 8: EVT = MVT::i8; break;
1915 case 16: EVT = MVT::i16; break;
1916 case 32: EVT = MVT::i32; break;
1918 if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
1919 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
1920 DAG.getValueType(EVT));
1923 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
1924 if (N1C && N0.getOpcode() == ISD::SRA) {
1925 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1926 unsigned Sum = N1C->getValue() + C1->getValue();
1927 if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
1928 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
1929 DAG.getConstant(Sum, N1C->getValueType(0)));
1933 // Simplify, based on bits shifted out of the LHS.
1934 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
1935 return SDOperand(N, 0);
1938 // If the sign bit is known to be zero, switch this to a SRL.
1939 if (TLI.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
1940 return DAG.getNode(ISD::SRL, VT, N0, N1);
1944 SDOperand DAGCombiner::visitSRL(SDNode *N) {
1945 SDOperand N0 = N->getOperand(0);
1946 SDOperand N1 = N->getOperand(1);
1947 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1948 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1949 MVT::ValueType VT = N0.getValueType();
1950 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1952 // fold (srl c1, c2) -> c1 >>u c2
1954 return DAG.getNode(ISD::SRL, VT, N0, N1);
1955 // fold (srl 0, x) -> 0
1956 if (N0C && N0C->isNullValue())
1958 // fold (srl x, c >= size(x)) -> undef
1959 if (N1C && N1C->getValue() >= OpSizeInBits)
1960 return DAG.getNode(ISD::UNDEF, VT);
1961 // fold (srl x, 0) -> x
1962 if (N1C && N1C->isNullValue())
1964 // if (srl x, c) is known to be zero, return 0
1965 if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
1966 return DAG.getConstant(0, VT);
1967 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
1968 if (N1C && N0.getOpcode() == ISD::SRL &&
1969 N0.getOperand(1).getOpcode() == ISD::Constant) {
1970 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1971 uint64_t c2 = N1C->getValue();
1972 if (c1 + c2 > OpSizeInBits)
1973 return DAG.getConstant(0, VT);
1974 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
1975 DAG.getConstant(c1 + c2, N1.getValueType()));
1978 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
1979 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1980 // Shifting in all undef bits?
1981 MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
1982 if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
1983 return DAG.getNode(ISD::UNDEF, VT);
1985 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
1986 AddToWorkList(SmallShift.Val);
1987 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
1990 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
1991 // bit, which is unmodified by sra.
1992 if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
1993 if (N0.getOpcode() == ISD::SRA)
1994 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
1997 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
1998 if (N1C && N0.getOpcode() == ISD::CTLZ &&
1999 N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
2000 uint64_t KnownZero, KnownOne, Mask = MVT::getIntVTBitMask(VT);
2001 TLI.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2003 // If any of the input bits are KnownOne, then the input couldn't be all
2004 // zeros, thus the result of the srl will always be zero.
2005 if (KnownOne) return DAG.getConstant(0, VT);
2007 // If all of the bits input the to ctlz node are known to be zero, then
2008 // the result of the ctlz is "32" and the result of the shift is one.
2009 uint64_t UnknownBits = ~KnownZero & Mask;
2010 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2012 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2013 if ((UnknownBits & (UnknownBits-1)) == 0) {
2014 // Okay, we know that only that the single bit specified by UnknownBits
2015 // could be set on input to the CTLZ node. If this bit is set, the SRL
2016 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2017 // to an SRL,XOR pair, which is likely to simplify more.
2018 unsigned ShAmt = CountTrailingZeros_64(UnknownBits);
2019 SDOperand Op = N0.getOperand(0);
2021 Op = DAG.getNode(ISD::SRL, VT, Op,
2022 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2023 AddToWorkList(Op.Val);
2025 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2032 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2033 SDOperand N0 = N->getOperand(0);
2034 MVT::ValueType VT = N->getValueType(0);
2036 // fold (ctlz c1) -> c2
2037 if (isa<ConstantSDNode>(N0))
2038 return DAG.getNode(ISD::CTLZ, VT, N0);
2042 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2043 SDOperand N0 = N->getOperand(0);
2044 MVT::ValueType VT = N->getValueType(0);
2046 // fold (cttz c1) -> c2
2047 if (isa<ConstantSDNode>(N0))
2048 return DAG.getNode(ISD::CTTZ, VT, N0);
2052 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2053 SDOperand N0 = N->getOperand(0);
2054 MVT::ValueType VT = N->getValueType(0);
2056 // fold (ctpop c1) -> c2
2057 if (isa<ConstantSDNode>(N0))
2058 return DAG.getNode(ISD::CTPOP, VT, N0);
2062 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2063 SDOperand N0 = N->getOperand(0);
2064 SDOperand N1 = N->getOperand(1);
2065 SDOperand N2 = N->getOperand(2);
2066 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2067 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2068 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2069 MVT::ValueType VT = N->getValueType(0);
2071 // fold select C, X, X -> X
2074 // fold select true, X, Y -> X
2075 if (N0C && !N0C->isNullValue())
2077 // fold select false, X, Y -> Y
2078 if (N0C && N0C->isNullValue())
2080 // fold select C, 1, X -> C | X
2081 if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
2082 return DAG.getNode(ISD::OR, VT, N0, N2);
2083 // fold select C, 0, X -> ~C & X
2084 // FIXME: this should check for C type == X type, not i1?
2085 if (MVT::i1 == VT && N1C && N1C->isNullValue()) {
2086 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2087 AddToWorkList(XORNode.Val);
2088 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2090 // fold select C, X, 1 -> ~C | X
2091 if (MVT::i1 == VT && N2C && N2C->getValue() == 1) {
2092 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2093 AddToWorkList(XORNode.Val);
2094 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2096 // fold select C, X, 0 -> C & X
2097 // FIXME: this should check for C type == X type, not i1?
2098 if (MVT::i1 == VT && N2C && N2C->isNullValue())
2099 return DAG.getNode(ISD::AND, VT, N0, N1);
2100 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2101 if (MVT::i1 == VT && N0 == N1)
2102 return DAG.getNode(ISD::OR, VT, N0, N2);
2103 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2104 if (MVT::i1 == VT && N0 == N2)
2105 return DAG.getNode(ISD::AND, VT, N0, N1);
2107 // If we can fold this based on the true/false value, do so.
2108 if (SimplifySelectOps(N, N1, N2))
2109 return SDOperand(N, 0); // Don't revisit N.
2111 // fold selects based on a setcc into other things, such as min/max/abs
2112 if (N0.getOpcode() == ISD::SETCC)
2114 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2115 // having to say they don't support SELECT_CC on every type the DAG knows
2116 // about, since there is no way to mark an opcode illegal at all value types
2117 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2118 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2119 N1, N2, N0.getOperand(2));
2121 return SimplifySelect(N0, N1, N2);
2125 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2126 SDOperand N0 = N->getOperand(0);
2127 SDOperand N1 = N->getOperand(1);
2128 SDOperand N2 = N->getOperand(2);
2129 SDOperand N3 = N->getOperand(3);
2130 SDOperand N4 = N->getOperand(4);
2131 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2133 // fold select_cc lhs, rhs, x, x, cc -> x
2137 // Determine if the condition we're dealing with is constant
2138 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
2139 if (SCC.Val) AddToWorkList(SCC.Val);
2141 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2142 if (SCCC->getValue())
2143 return N2; // cond always true -> true val
2145 return N3; // cond always false -> false val
2148 // Fold to a simpler select_cc
2149 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2150 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2151 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2154 // If we can fold this based on the true/false value, do so.
2155 if (SimplifySelectOps(N, N2, N3))
2156 return SDOperand(N, 0); // Don't revisit N.
2158 // fold select_cc into other things, such as min/max/abs
2159 return SimplifySelectCC(N0, N1, N2, N3, CC);
2162 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2163 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2164 cast<CondCodeSDNode>(N->getOperand(2))->get());
2167 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2168 SDOperand N0 = N->getOperand(0);
2169 MVT::ValueType VT = N->getValueType(0);
2171 // fold (sext c1) -> c1
2172 if (isa<ConstantSDNode>(N0))
2173 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2175 // fold (sext (sext x)) -> (sext x)
2176 // fold (sext (aext x)) -> (sext x)
2177 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2178 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2180 // fold (sext (truncate x)) -> (sextinreg x).
2181 if (N0.getOpcode() == ISD::TRUNCATE &&
2182 (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2183 N0.getValueType()))) {
2184 SDOperand Op = N0.getOperand(0);
2185 if (Op.getValueType() < VT) {
2186 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2187 } else if (Op.getValueType() > VT) {
2188 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2190 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2191 DAG.getValueType(N0.getValueType()));
2194 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2195 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2196 (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
2197 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2198 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2199 LN0->getBasePtr(), LN0->getSrcValue(),
2200 LN0->getSrcValueOffset(),
2202 CombineTo(N, ExtLoad);
2203 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2204 ExtLoad.getValue(1));
2205 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2208 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2209 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2210 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) && N0.hasOneUse()) {
2211 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2212 MVT::ValueType EVT = LN0->getLoadedVT();
2213 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2214 LN0->getBasePtr(), LN0->getSrcValue(),
2215 LN0->getSrcValueOffset(), EVT);
2216 CombineTo(N, ExtLoad);
2217 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2218 ExtLoad.getValue(1));
2219 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2225 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2226 SDOperand N0 = N->getOperand(0);
2227 MVT::ValueType VT = N->getValueType(0);
2229 // fold (zext c1) -> c1
2230 if (isa<ConstantSDNode>(N0))
2231 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2232 // fold (zext (zext x)) -> (zext x)
2233 // fold (zext (aext x)) -> (zext x)
2234 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2235 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2237 // fold (zext (truncate x)) -> (and x, mask)
2238 if (N0.getOpcode() == ISD::TRUNCATE &&
2239 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2240 SDOperand Op = N0.getOperand(0);
2241 if (Op.getValueType() < VT) {
2242 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2243 } else if (Op.getValueType() > VT) {
2244 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2246 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2249 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2250 if (N0.getOpcode() == ISD::AND &&
2251 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2252 N0.getOperand(1).getOpcode() == ISD::Constant) {
2253 SDOperand X = N0.getOperand(0).getOperand(0);
2254 if (X.getValueType() < VT) {
2255 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2256 } else if (X.getValueType() > VT) {
2257 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2259 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2260 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2263 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2264 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2265 (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2266 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2267 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2268 LN0->getBasePtr(), LN0->getSrcValue(),
2269 LN0->getSrcValueOffset(),
2271 CombineTo(N, ExtLoad);
2272 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2273 ExtLoad.getValue(1));
2274 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2277 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2278 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2279 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) && N0.hasOneUse()) {
2280 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2281 MVT::ValueType EVT = LN0->getLoadedVT();
2282 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2283 LN0->getBasePtr(), LN0->getSrcValue(),
2284 LN0->getSrcValueOffset(), EVT);
2285 CombineTo(N, ExtLoad);
2286 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2287 ExtLoad.getValue(1));
2288 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2293 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
2294 SDOperand N0 = N->getOperand(0);
2295 MVT::ValueType VT = N->getValueType(0);
2297 // fold (aext c1) -> c1
2298 if (isa<ConstantSDNode>(N0))
2299 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
2300 // fold (aext (aext x)) -> (aext x)
2301 // fold (aext (zext x)) -> (zext x)
2302 // fold (aext (sext x)) -> (sext x)
2303 if (N0.getOpcode() == ISD::ANY_EXTEND ||
2304 N0.getOpcode() == ISD::ZERO_EXTEND ||
2305 N0.getOpcode() == ISD::SIGN_EXTEND)
2306 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2308 // fold (aext (truncate x))
2309 if (N0.getOpcode() == ISD::TRUNCATE) {
2310 SDOperand TruncOp = N0.getOperand(0);
2311 if (TruncOp.getValueType() == VT)
2312 return TruncOp; // x iff x size == zext size.
2313 if (TruncOp.getValueType() > VT)
2314 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
2315 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
2318 // fold (aext (and (trunc x), cst)) -> (and x, cst).
2319 if (N0.getOpcode() == ISD::AND &&
2320 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2321 N0.getOperand(1).getOpcode() == ISD::Constant) {
2322 SDOperand X = N0.getOperand(0).getOperand(0);
2323 if (X.getValueType() < VT) {
2324 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2325 } else if (X.getValueType() > VT) {
2326 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2328 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2329 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2332 // fold (aext (load x)) -> (aext (truncate (extload x)))
2333 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2334 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2335 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2336 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2337 LN0->getBasePtr(), LN0->getSrcValue(),
2338 LN0->getSrcValueOffset(),
2340 CombineTo(N, ExtLoad);
2341 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2342 ExtLoad.getValue(1));
2343 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2346 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
2347 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
2348 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
2349 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.Val) &&
2351 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2352 MVT::ValueType EVT = LN0->getLoadedVT();
2353 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
2354 LN0->getChain(), LN0->getBasePtr(),
2356 LN0->getSrcValueOffset(), EVT);
2357 CombineTo(N, ExtLoad);
2358 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2359 ExtLoad.getValue(1));
2360 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2366 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
2367 SDOperand N0 = N->getOperand(0);
2368 SDOperand N1 = N->getOperand(1);
2369 MVT::ValueType VT = N->getValueType(0);
2370 MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
2371 unsigned EVTBits = MVT::getSizeInBits(EVT);
2373 // fold (sext_in_reg c1) -> c1
2374 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
2375 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
2377 // If the input is already sign extended, just drop the extension.
2378 if (TLI.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
2381 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
2382 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2383 EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
2384 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
2387 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is zero
2388 if (TLI.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
2389 return DAG.getZeroExtendInReg(N0, EVT);
2391 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
2392 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
2393 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
2394 if (N0.getOpcode() == ISD::SRL) {
2395 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2396 if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
2397 // We can turn this into an SRA iff the input to the SRL is already sign
2399 unsigned InSignBits = TLI.ComputeNumSignBits(N0.getOperand(0));
2400 if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
2401 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
2405 // fold (sext_inreg (extload x)) -> (sextload x)
2406 if (ISD::isEXTLoad(N0.Val) &&
2407 EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2408 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2409 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2410 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2411 LN0->getBasePtr(), LN0->getSrcValue(),
2412 LN0->getSrcValueOffset(), EVT);
2413 CombineTo(N, ExtLoad);
2414 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2415 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2417 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
2418 if (ISD::isZEXTLoad(N0.Val) && N0.hasOneUse() &&
2419 EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2420 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2421 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2422 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2423 LN0->getBasePtr(), LN0->getSrcValue(),
2424 LN0->getSrcValueOffset(), EVT);
2425 CombineTo(N, ExtLoad);
2426 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2427 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2432 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
2433 SDOperand N0 = N->getOperand(0);
2434 MVT::ValueType VT = N->getValueType(0);
2437 if (N0.getValueType() == N->getValueType(0))
2439 // fold (truncate c1) -> c1
2440 if (isa<ConstantSDNode>(N0))
2441 return DAG.getNode(ISD::TRUNCATE, VT, N0);
2442 // fold (truncate (truncate x)) -> (truncate x)
2443 if (N0.getOpcode() == ISD::TRUNCATE)
2444 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
2445 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
2446 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
2447 N0.getOpcode() == ISD::ANY_EXTEND) {
2448 if (N0.getValueType() < VT)
2449 // if the source is smaller than the dest, we still need an extend
2450 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2451 else if (N0.getValueType() > VT)
2452 // if the source is larger than the dest, than we just need the truncate
2453 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
2455 // if the source and dest are the same type, we can drop both the extend
2457 return N0.getOperand(0);
2459 // fold (truncate (load x)) -> (smaller load x)
2460 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse()) {
2461 assert(MVT::getSizeInBits(N0.getValueType()) > MVT::getSizeInBits(VT) &&
2462 "Cannot truncate to larger type!");
2463 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2464 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
2465 // For big endian targets, we need to add an offset to the pointer to load
2466 // the correct bytes. For little endian systems, we merely need to read
2467 // fewer bytes from the same pointer.
2469 (MVT::getSizeInBits(N0.getValueType()) - MVT::getSizeInBits(VT)) / 8;
2470 SDOperand NewPtr = TLI.isLittleEndian() ? LN0->getBasePtr() :
2471 DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
2472 DAG.getConstant(PtrOff, PtrType));
2473 AddToWorkList(NewPtr.Val);
2474 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), NewPtr,
2475 LN0->getSrcValue(), LN0->getSrcValueOffset());
2477 CombineTo(N0.Val, Load, Load.getValue(1));
2478 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2483 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
2484 SDOperand N0 = N->getOperand(0);
2485 MVT::ValueType VT = N->getValueType(0);
2487 // If the input is a constant, let getNode() fold it.
2488 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
2489 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
2490 if (Res.Val != N) return Res;
2493 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
2494 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
2496 // fold (conv (load x)) -> (load (conv*)x)
2497 // FIXME: These xforms need to know that the resultant load doesn't need a
2498 // higher alignment than the original!
2499 if (0 && ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse()) {
2500 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2501 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
2502 LN0->getSrcValue(), LN0->getSrcValueOffset());
2504 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
2512 SDOperand DAGCombiner::visitVBIT_CONVERT(SDNode *N) {
2513 SDOperand N0 = N->getOperand(0);
2514 MVT::ValueType VT = N->getValueType(0);
2516 // If the input is a VBUILD_VECTOR with all constant elements, fold this now.
2517 // First check to see if this is all constant.
2518 if (N0.getOpcode() == ISD::VBUILD_VECTOR && N0.Val->hasOneUse() &&
2519 VT == MVT::Vector) {
2520 bool isSimple = true;
2521 for (unsigned i = 0, e = N0.getNumOperands()-2; i != e; ++i)
2522 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
2523 N0.getOperand(i).getOpcode() != ISD::Constant &&
2524 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
2529 MVT::ValueType DestEltVT = cast<VTSDNode>(N->getOperand(2))->getVT();
2530 if (isSimple && !MVT::isVector(DestEltVT)) {
2531 return ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(N0.Val, DestEltVT);
2538 /// ConstantFoldVBIT_CONVERTofVBUILD_VECTOR - We know that BV is a vbuild_vector
2539 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
2540 /// destination element value type.
2541 SDOperand DAGCombiner::
2542 ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
2543 MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
2545 // If this is already the right type, we're done.
2546 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
2548 unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
2549 unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
2551 // If this is a conversion of N elements of one type to N elements of another
2552 // type, convert each element. This handles FP<->INT cases.
2553 if (SrcBitSize == DstBitSize) {
2554 SmallVector<SDOperand, 8> Ops;
2555 for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) {
2556 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
2557 AddToWorkList(Ops.back().Val);
2559 Ops.push_back(*(BV->op_end()-2)); // Add num elements.
2560 Ops.push_back(DAG.getValueType(DstEltVT));
2561 return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2564 // Otherwise, we're growing or shrinking the elements. To avoid having to
2565 // handle annoying details of growing/shrinking FP values, we convert them to
2567 if (MVT::isFloatingPoint(SrcEltVT)) {
2568 // Convert the input float vector to a int vector where the elements are the
2570 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
2571 MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2572 BV = ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(BV, IntVT).Val;
2576 // Now we know the input is an integer vector. If the output is a FP type,
2577 // convert to integer first, then to FP of the right size.
2578 if (MVT::isFloatingPoint(DstEltVT)) {
2579 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
2580 MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2581 SDNode *Tmp = ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(BV, TmpVT).Val;
2583 // Next, convert to FP elements of the same size.
2584 return ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(Tmp, DstEltVT);
2587 // Okay, we know the src/dst types are both integers of differing types.
2588 // Handling growing first.
2589 assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
2590 if (SrcBitSize < DstBitSize) {
2591 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
2593 SmallVector<SDOperand, 8> Ops;
2594 for (unsigned i = 0, e = BV->getNumOperands()-2; i != e;
2595 i += NumInputsPerOutput) {
2596 bool isLE = TLI.isLittleEndian();
2597 uint64_t NewBits = 0;
2598 bool EltIsUndef = true;
2599 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
2600 // Shift the previously computed bits over.
2601 NewBits <<= SrcBitSize;
2602 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
2603 if (Op.getOpcode() == ISD::UNDEF) continue;
2606 NewBits |= cast<ConstantSDNode>(Op)->getValue();
2610 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2612 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
2615 Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements.
2616 Ops.push_back(DAG.getValueType(DstEltVT)); // Add element size.
2617 return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2620 // Finally, this must be the case where we are shrinking elements: each input
2621 // turns into multiple outputs.
2622 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
2623 SmallVector<SDOperand, 8> Ops;
2624 for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) {
2625 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
2626 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
2627 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2630 uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
2632 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
2633 unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
2634 OpVal >>= DstBitSize;
2635 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
2638 // For big endian targets, swap the order of the pieces of each element.
2639 if (!TLI.isLittleEndian())
2640 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
2642 Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements.
2643 Ops.push_back(DAG.getValueType(DstEltVT)); // Add element size.
2644 return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2649 SDOperand DAGCombiner::visitFADD(SDNode *N) {
2650 SDOperand N0 = N->getOperand(0);
2651 SDOperand N1 = N->getOperand(1);
2652 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2653 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2654 MVT::ValueType VT = N->getValueType(0);
2656 // fold (fadd c1, c2) -> c1+c2
2658 return DAG.getNode(ISD::FADD, VT, N0, N1);
2659 // canonicalize constant to RHS
2660 if (N0CFP && !N1CFP)
2661 return DAG.getNode(ISD::FADD, VT, N1, N0);
2662 // fold (A + (-B)) -> A-B
2663 if (N1.getOpcode() == ISD::FNEG)
2664 return DAG.getNode(ISD::FSUB, VT, N0, N1.getOperand(0));
2665 // fold ((-A) + B) -> B-A
2666 if (N0.getOpcode() == ISD::FNEG)
2667 return DAG.getNode(ISD::FSUB, VT, N1, N0.getOperand(0));
2671 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
2672 SDOperand N0 = N->getOperand(0);
2673 SDOperand N1 = N->getOperand(1);
2674 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2675 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2676 MVT::ValueType VT = N->getValueType(0);
2678 // fold (fsub c1, c2) -> c1-c2
2680 return DAG.getNode(ISD::FSUB, VT, N0, N1);
2681 // fold (A-(-B)) -> A+B
2682 if (N1.getOpcode() == ISD::FNEG)
2683 return DAG.getNode(ISD::FADD, VT, N0, N1.getOperand(0));
2687 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
2688 SDOperand N0 = N->getOperand(0);
2689 SDOperand N1 = N->getOperand(1);
2690 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2691 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2692 MVT::ValueType VT = N->getValueType(0);
2694 // fold (fmul c1, c2) -> c1*c2
2696 return DAG.getNode(ISD::FMUL, VT, N0, N1);
2697 // canonicalize constant to RHS
2698 if (N0CFP && !N1CFP)
2699 return DAG.getNode(ISD::FMUL, VT, N1, N0);
2700 // fold (fmul X, 2.0) -> (fadd X, X)
2701 if (N1CFP && N1CFP->isExactlyValue(+2.0))
2702 return DAG.getNode(ISD::FADD, VT, N0, N0);
2706 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
2707 SDOperand N0 = N->getOperand(0);
2708 SDOperand N1 = N->getOperand(1);
2709 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2710 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2711 MVT::ValueType VT = N->getValueType(0);
2713 // fold (fdiv c1, c2) -> c1/c2
2715 return DAG.getNode(ISD::FDIV, VT, N0, N1);
2719 SDOperand DAGCombiner::visitFREM(SDNode *N) {
2720 SDOperand N0 = N->getOperand(0);
2721 SDOperand N1 = N->getOperand(1);
2722 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2723 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2724 MVT::ValueType VT = N->getValueType(0);
2726 // fold (frem c1, c2) -> fmod(c1,c2)
2728 return DAG.getNode(ISD::FREM, VT, N0, N1);
2732 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
2733 SDOperand N0 = N->getOperand(0);
2734 SDOperand N1 = N->getOperand(1);
2735 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2736 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2737 MVT::ValueType VT = N->getValueType(0);
2739 if (N0CFP && N1CFP) // Constant fold
2740 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
2743 // copysign(x, c1) -> fabs(x) iff ispos(c1)
2744 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
2749 u.d = N1CFP->getValue();
2751 return DAG.getNode(ISD::FABS, VT, N0);
2753 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
2756 // copysign(fabs(x), y) -> copysign(x, y)
2757 // copysign(fneg(x), y) -> copysign(x, y)
2758 // copysign(copysign(x,z), y) -> copysign(x, y)
2759 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
2760 N0.getOpcode() == ISD::FCOPYSIGN)
2761 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
2763 // copysign(x, abs(y)) -> abs(x)
2764 if (N1.getOpcode() == ISD::FABS)
2765 return DAG.getNode(ISD::FABS, VT, N0);
2767 // copysign(x, copysign(y,z)) -> copysign(x, z)
2768 if (N1.getOpcode() == ISD::FCOPYSIGN)
2769 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
2771 // copysign(x, fp_extend(y)) -> copysign(x, y)
2772 // copysign(x, fp_round(y)) -> copysign(x, y)
2773 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
2774 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
2781 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
2782 SDOperand N0 = N->getOperand(0);
2783 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2784 MVT::ValueType VT = N->getValueType(0);
2786 // fold (sint_to_fp c1) -> c1fp
2788 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
2792 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
2793 SDOperand N0 = N->getOperand(0);
2794 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2795 MVT::ValueType VT = N->getValueType(0);
2797 // fold (uint_to_fp c1) -> c1fp
2799 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
2803 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
2804 SDOperand N0 = N->getOperand(0);
2805 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2806 MVT::ValueType VT = N->getValueType(0);
2808 // fold (fp_to_sint c1fp) -> c1
2810 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
2814 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
2815 SDOperand N0 = N->getOperand(0);
2816 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2817 MVT::ValueType VT = N->getValueType(0);
2819 // fold (fp_to_uint c1fp) -> c1
2821 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
2825 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
2826 SDOperand N0 = N->getOperand(0);
2827 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2828 MVT::ValueType VT = N->getValueType(0);
2830 // fold (fp_round c1fp) -> c1fp
2832 return DAG.getNode(ISD::FP_ROUND, VT, N0);
2834 // fold (fp_round (fp_extend x)) -> x
2835 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
2836 return N0.getOperand(0);
2838 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
2839 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
2840 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0));
2841 AddToWorkList(Tmp.Val);
2842 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
2848 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
2849 SDOperand N0 = N->getOperand(0);
2850 MVT::ValueType VT = N->getValueType(0);
2851 MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2852 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2854 // fold (fp_round_inreg c1fp) -> c1fp
2856 SDOperand Round = DAG.getConstantFP(N0CFP->getValue(), EVT);
2857 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
2862 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
2863 SDOperand N0 = N->getOperand(0);
2864 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2865 MVT::ValueType VT = N->getValueType(0);
2867 // fold (fp_extend c1fp) -> c1fp
2869 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
2871 // fold (fpext (load x)) -> (fpext (fpround (extload x)))
2872 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2873 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2874 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2875 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2876 LN0->getBasePtr(), LN0->getSrcValue(),
2877 LN0->getSrcValueOffset(),
2879 CombineTo(N, ExtLoad);
2880 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad),
2881 ExtLoad.getValue(1));
2882 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2889 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
2890 SDOperand N0 = N->getOperand(0);
2891 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2892 MVT::ValueType VT = N->getValueType(0);
2894 // fold (fneg c1) -> -c1
2896 return DAG.getNode(ISD::FNEG, VT, N0);
2897 // fold (fneg (sub x, y)) -> (sub y, x)
2898 if (N0.getOpcode() == ISD::SUB)
2899 return DAG.getNode(ISD::SUB, VT, N0.getOperand(1), N0.getOperand(0));
2900 // fold (fneg (fneg x)) -> x
2901 if (N0.getOpcode() == ISD::FNEG)
2902 return N0.getOperand(0);
2906 SDOperand DAGCombiner::visitFABS(SDNode *N) {
2907 SDOperand N0 = N->getOperand(0);
2908 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2909 MVT::ValueType VT = N->getValueType(0);
2911 // fold (fabs c1) -> fabs(c1)
2913 return DAG.getNode(ISD::FABS, VT, N0);
2914 // fold (fabs (fabs x)) -> (fabs x)
2915 if (N0.getOpcode() == ISD::FABS)
2916 return N->getOperand(0);
2917 // fold (fabs (fneg x)) -> (fabs x)
2918 // fold (fabs (fcopysign x, y)) -> (fabs x)
2919 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
2920 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
2925 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
2926 SDOperand Chain = N->getOperand(0);
2927 SDOperand N1 = N->getOperand(1);
2928 SDOperand N2 = N->getOperand(2);
2929 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2931 // never taken branch, fold to chain
2932 if (N1C && N1C->isNullValue())
2934 // unconditional branch
2935 if (N1C && N1C->getValue() == 1)
2936 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
2937 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
2939 if (N1.getOpcode() == ISD::SETCC &&
2940 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
2941 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
2942 N1.getOperand(0), N1.getOperand(1), N2);
2947 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
2949 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
2950 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
2951 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
2953 // Use SimplifySetCC to simplify SETCC's.
2954 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
2955 if (Simp.Val) AddToWorkList(Simp.Val);
2957 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
2959 // fold br_cc true, dest -> br dest (unconditional branch)
2960 if (SCCC && SCCC->getValue())
2961 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
2963 // fold br_cc false, dest -> unconditional fall through
2964 if (SCCC && SCCC->isNullValue())
2965 return N->getOperand(0);
2967 // fold to a simpler setcc
2968 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
2969 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
2970 Simp.getOperand(2), Simp.getOperand(0),
2971 Simp.getOperand(1), N->getOperand(4));
2975 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
2976 LoadSDNode *LD = cast<LoadSDNode>(N);
2977 SDOperand Chain = LD->getChain();
2978 SDOperand Ptr = LD->getBasePtr();
2980 // If there are no uses of the loaded value, change uses of the chain value
2981 // into uses of the chain input (i.e. delete the dead load).
2982 if (N->hasNUsesOfValue(0, 0))
2983 return CombineTo(N, DAG.getNode(ISD::UNDEF, N->getValueType(0)), Chain);
2985 // If this load is directly stored, replace the load value with the stored
2987 // TODO: Handle store large -> read small portion.
2988 // TODO: Handle TRUNCSTORE/LOADEXT
2989 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
2990 if (ISD::isNON_TRUNCStore(Chain.Val)) {
2991 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
2992 if (PrevST->getBasePtr() == Ptr &&
2993 PrevST->getValue().getValueType() == N->getValueType(0))
2994 return CombineTo(N, Chain.getOperand(1), Chain);
2999 // Walk up chain skipping non-aliasing memory nodes.
3000 SDOperand BetterChain = FindBetterChain(N, Chain);
3002 // If there is a better chain.
3003 if (Chain != BetterChain) {
3006 // Replace the chain to void dependency.
3007 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
3008 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
3009 LD->getSrcValue(), LD->getSrcValueOffset());
3011 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
3012 LD->getValueType(0),
3013 BetterChain, Ptr, LD->getSrcValue(),
3014 LD->getSrcValueOffset(),
3018 // Create token factor to keep old chain connected.
3019 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
3020 Chain, ReplLoad.getValue(1));
3022 // Replace uses with load result and token factor. Don't add users
3024 return CombineTo(N, ReplLoad.getValue(0), Token, false);
3028 // Try transforming N to an indexed load.
3029 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
3030 return SDOperand(N, 0);
3035 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
3036 StoreSDNode *ST = cast<StoreSDNode>(N);
3037 SDOperand Chain = ST->getChain();
3038 SDOperand Value = ST->getValue();
3039 SDOperand Ptr = ST->getBasePtr();
3041 // If this is a store of a bit convert, store the input value.
3042 // FIXME: This needs to know that the resultant store does not need a
3043 // higher alignment than the original.
3044 if (0 && Value.getOpcode() == ISD::BIT_CONVERT) {
3045 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
3046 ST->getSrcValueOffset());
3050 // Walk up chain skipping non-aliasing memory nodes.
3051 SDOperand BetterChain = FindBetterChain(N, Chain);
3053 // If there is a better chain.
3054 if (Chain != BetterChain) {
3055 // Replace the chain to avoid dependency.
3056 SDOperand ReplStore;
3057 if (ST->isTruncatingStore()) {
3058 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
3059 ST->getSrcValue(),ST->getSrcValueOffset(), ST->getStoredVT());
3061 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
3062 ST->getSrcValue(), ST->getSrcValueOffset());
3065 // Create token to keep both nodes around.
3067 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
3069 // Don't add users to work list.
3070 return CombineTo(N, Token, false);
3074 // Try transforming N to an indexed store.
3075 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
3076 return SDOperand(N, 0);
3081 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
3082 SDOperand InVec = N->getOperand(0);
3083 SDOperand InVal = N->getOperand(1);
3084 SDOperand EltNo = N->getOperand(2);
3086 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
3087 // vector with the inserted element.
3088 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
3089 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
3090 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
3091 if (Elt < Ops.size())
3093 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
3094 &Ops[0], Ops.size());
3100 SDOperand DAGCombiner::visitVINSERT_VECTOR_ELT(SDNode *N) {
3101 SDOperand InVec = N->getOperand(0);
3102 SDOperand InVal = N->getOperand(1);
3103 SDOperand EltNo = N->getOperand(2);
3104 SDOperand NumElts = N->getOperand(3);
3105 SDOperand EltType = N->getOperand(4);
3107 // If the invec is a VBUILD_VECTOR and if EltNo is a constant, build a new
3108 // vector with the inserted element.
3109 if (InVec.getOpcode() == ISD::VBUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
3110 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
3111 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
3112 if (Elt < Ops.size()-2)
3114 return DAG.getNode(ISD::VBUILD_VECTOR, InVec.getValueType(),
3115 &Ops[0], Ops.size());
3121 SDOperand DAGCombiner::visitVBUILD_VECTOR(SDNode *N) {
3122 unsigned NumInScalars = N->getNumOperands()-2;
3123 SDOperand NumElts = N->getOperand(NumInScalars);
3124 SDOperand EltType = N->getOperand(NumInScalars+1);
3126 // Check to see if this is a VBUILD_VECTOR of a bunch of VEXTRACT_VECTOR_ELT
3127 // operations. If so, and if the EXTRACT_ELT vector inputs come from at most
3128 // two distinct vectors, turn this into a shuffle node.
3129 SDOperand VecIn1, VecIn2;
3130 for (unsigned i = 0; i != NumInScalars; ++i) {
3131 // Ignore undef inputs.
3132 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
3134 // If this input is something other than a VEXTRACT_VECTOR_ELT with a
3135 // constant index, bail out.
3136 if (N->getOperand(i).getOpcode() != ISD::VEXTRACT_VECTOR_ELT ||
3137 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
3138 VecIn1 = VecIn2 = SDOperand(0, 0);
3142 // If the input vector type disagrees with the result of the vbuild_vector,
3143 // we can't make a shuffle.
3144 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
3145 if (*(ExtractedFromVec.Val->op_end()-2) != NumElts ||
3146 *(ExtractedFromVec.Val->op_end()-1) != EltType) {
3147 VecIn1 = VecIn2 = SDOperand(0, 0);
3151 // Otherwise, remember this. We allow up to two distinct input vectors.
3152 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
3155 if (VecIn1.Val == 0) {
3156 VecIn1 = ExtractedFromVec;
3157 } else if (VecIn2.Val == 0) {
3158 VecIn2 = ExtractedFromVec;
3161 VecIn1 = VecIn2 = SDOperand(0, 0);
3166 // If everything is good, we can make a shuffle operation.
3168 SmallVector<SDOperand, 8> BuildVecIndices;
3169 for (unsigned i = 0; i != NumInScalars; ++i) {
3170 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
3171 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3175 SDOperand Extract = N->getOperand(i);
3177 // If extracting from the first vector, just use the index directly.
3178 if (Extract.getOperand(0) == VecIn1) {
3179 BuildVecIndices.push_back(Extract.getOperand(1));
3183 // Otherwise, use InIdx + VecSize
3184 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
3185 BuildVecIndices.push_back(DAG.getConstant(Idx+NumInScalars, MVT::i32));
3188 // Add count and size info.
3189 BuildVecIndices.push_back(NumElts);
3190 BuildVecIndices.push_back(DAG.getValueType(MVT::i32));
3192 // Return the new VVECTOR_SHUFFLE node.
3198 // Use an undef vbuild_vector as input for the second operand.
3199 std::vector<SDOperand> UnOps(NumInScalars,
3200 DAG.getNode(ISD::UNDEF,
3201 cast<VTSDNode>(EltType)->getVT()));
3202 UnOps.push_back(NumElts);
3203 UnOps.push_back(EltType);
3204 Ops[1] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3205 &UnOps[0], UnOps.size());
3206 AddToWorkList(Ops[1].Val);
3208 Ops[2] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3209 &BuildVecIndices[0], BuildVecIndices.size());
3212 return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, Ops, 5);
3218 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
3219 SDOperand ShufMask = N->getOperand(2);
3220 unsigned NumElts = ShufMask.getNumOperands();
3222 // If the shuffle mask is an identity operation on the LHS, return the LHS.
3223 bool isIdentity = true;
3224 for (unsigned i = 0; i != NumElts; ++i) {
3225 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3226 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
3231 if (isIdentity) return N->getOperand(0);
3233 // If the shuffle mask is an identity operation on the RHS, return the RHS.
3235 for (unsigned i = 0; i != NumElts; ++i) {
3236 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3237 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
3242 if (isIdentity) return N->getOperand(1);
3244 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
3246 bool isUnary = true;
3247 bool isSplat = true;
3249 unsigned BaseIdx = 0;
3250 for (unsigned i = 0; i != NumElts; ++i)
3251 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
3252 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
3253 int V = (Idx < NumElts) ? 0 : 1;
3267 SDOperand N0 = N->getOperand(0);
3268 SDOperand N1 = N->getOperand(1);
3269 // Normalize unary shuffle so the RHS is undef.
3270 if (isUnary && VecNum == 1)
3273 // If it is a splat, check if the argument vector is a build_vector with
3274 // all scalar elements the same.
3277 if (V->getOpcode() == ISD::BIT_CONVERT)
3278 V = V->getOperand(0).Val;
3279 if (V->getOpcode() == ISD::BUILD_VECTOR) {
3280 unsigned NumElems = V->getNumOperands()-2;
3281 if (NumElems > BaseIdx) {
3283 bool AllSame = true;
3284 for (unsigned i = 0; i != NumElems; ++i) {
3285 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
3286 Base = V->getOperand(i);
3290 // Splat of <u, u, u, u>, return <u, u, u, u>
3293 for (unsigned i = 0; i != NumElems; ++i) {
3294 if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
3295 V->getOperand(i) != Base) {
3300 // Splat of <x, x, x, x>, return <x, x, x, x>
3307 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
3309 if (isUnary || N0 == N1) {
3310 if (N0.getOpcode() == ISD::UNDEF)
3311 return DAG.getNode(ISD::UNDEF, N->getValueType(0));
3312 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
3314 SmallVector<SDOperand, 8> MappedOps;
3315 for (unsigned i = 0, e = ShufMask.getNumOperands(); i != e; ++i) {
3316 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
3317 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
3318 MappedOps.push_back(ShufMask.getOperand(i));
3321 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
3322 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
3325 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
3326 &MappedOps[0], MappedOps.size());
3327 AddToWorkList(ShufMask.Val);
3328 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
3330 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
3337 SDOperand DAGCombiner::visitVVECTOR_SHUFFLE(SDNode *N) {
3338 SDOperand ShufMask = N->getOperand(2);
3339 unsigned NumElts = ShufMask.getNumOperands()-2;
3341 // If the shuffle mask is an identity operation on the LHS, return the LHS.
3342 bool isIdentity = true;
3343 for (unsigned i = 0; i != NumElts; ++i) {
3344 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3345 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
3350 if (isIdentity) return N->getOperand(0);
3352 // If the shuffle mask is an identity operation on the RHS, return the RHS.
3354 for (unsigned i = 0; i != NumElts; ++i) {
3355 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3356 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
3361 if (isIdentity) return N->getOperand(1);
3363 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
3365 bool isUnary = true;
3366 bool isSplat = true;
3368 unsigned BaseIdx = 0;
3369 for (unsigned i = 0; i != NumElts; ++i)
3370 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
3371 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
3372 int V = (Idx < NumElts) ? 0 : 1;
3386 SDOperand N0 = N->getOperand(0);
3387 SDOperand N1 = N->getOperand(1);
3388 // Normalize unary shuffle so the RHS is undef.
3389 if (isUnary && VecNum == 1)
3392 // If it is a splat, check if the argument vector is a build_vector with
3393 // all scalar elements the same.
3397 // If this is a vbit convert that changes the element type of the vector but
3398 // not the number of vector elements, look through it. Be careful not to
3399 // look though conversions that change things like v4f32 to v2f64.
3400 if (V->getOpcode() == ISD::VBIT_CONVERT) {
3401 SDOperand ConvInput = V->getOperand(0);
3402 if (ConvInput.getValueType() == MVT::Vector &&
3404 ConvInput.getConstantOperandVal(ConvInput.getNumOperands()-2))
3408 if (V->getOpcode() == ISD::VBUILD_VECTOR) {
3409 unsigned NumElems = V->getNumOperands()-2;
3410 if (NumElems > BaseIdx) {
3412 bool AllSame = true;
3413 for (unsigned i = 0; i != NumElems; ++i) {
3414 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
3415 Base = V->getOperand(i);
3419 // Splat of <u, u, u, u>, return <u, u, u, u>
3422 for (unsigned i = 0; i != NumElems; ++i) {
3423 if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
3424 V->getOperand(i) != Base) {
3429 // Splat of <x, x, x, x>, return <x, x, x, x>
3436 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
3438 if (isUnary || N0 == N1) {
3439 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
3441 SmallVector<SDOperand, 8> MappedOps;
3442 for (unsigned i = 0; i != NumElts; ++i) {
3443 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
3444 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
3445 MappedOps.push_back(ShufMask.getOperand(i));
3448 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
3449 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
3452 // Add the type/#elts values.
3453 MappedOps.push_back(ShufMask.getOperand(NumElts));
3454 MappedOps.push_back(ShufMask.getOperand(NumElts+1));
3456 ShufMask = DAG.getNode(ISD::VBUILD_VECTOR, ShufMask.getValueType(),
3457 &MappedOps[0], MappedOps.size());
3458 AddToWorkList(ShufMask.Val);
3460 // Build the undef vector.
3461 SDOperand UDVal = DAG.getNode(ISD::UNDEF, MappedOps[0].getValueType());
3462 for (unsigned i = 0; i != NumElts; ++i)
3463 MappedOps[i] = UDVal;
3464 MappedOps[NumElts ] = *(N0.Val->op_end()-2);
3465 MappedOps[NumElts+1] = *(N0.Val->op_end()-1);
3466 UDVal = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3467 &MappedOps[0], MappedOps.size());
3469 return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
3470 N0, UDVal, ShufMask,
3471 MappedOps[NumElts], MappedOps[NumElts+1]);
3477 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
3478 /// a VAND to a vector_shuffle with the destination vector and a zero vector.
3479 /// e.g. VAND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
3480 /// vector_shuffle V, Zero, <0, 4, 2, 4>
3481 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
3482 SDOperand LHS = N->getOperand(0);
3483 SDOperand RHS = N->getOperand(1);
3484 if (N->getOpcode() == ISD::VAND) {
3485 SDOperand DstVecSize = *(LHS.Val->op_end()-2);
3486 SDOperand DstVecEVT = *(LHS.Val->op_end()-1);
3487 if (RHS.getOpcode() == ISD::VBIT_CONVERT)
3488 RHS = RHS.getOperand(0);
3489 if (RHS.getOpcode() == ISD::VBUILD_VECTOR) {
3490 std::vector<SDOperand> IdxOps;
3491 unsigned NumOps = RHS.getNumOperands();
3492 unsigned NumElts = NumOps-2;
3493 MVT::ValueType EVT = cast<VTSDNode>(RHS.getOperand(NumOps-1))->getVT();
3494 for (unsigned i = 0; i != NumElts; ++i) {
3495 SDOperand Elt = RHS.getOperand(i);
3496 if (!isa<ConstantSDNode>(Elt))
3498 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
3499 IdxOps.push_back(DAG.getConstant(i, EVT));
3500 else if (cast<ConstantSDNode>(Elt)->isNullValue())
3501 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
3506 // Let's see if the target supports this vector_shuffle.
3507 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
3510 // Return the new VVECTOR_SHUFFLE node.
3511 SDOperand NumEltsNode = DAG.getConstant(NumElts, MVT::i32);
3512 SDOperand EVTNode = DAG.getValueType(EVT);
3513 std::vector<SDOperand> Ops;
3514 LHS = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, LHS, NumEltsNode,
3517 AddToWorkList(LHS.Val);
3518 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
3519 ZeroOps.push_back(NumEltsNode);
3520 ZeroOps.push_back(EVTNode);
3521 Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3522 &ZeroOps[0], ZeroOps.size()));
3523 IdxOps.push_back(NumEltsNode);
3524 IdxOps.push_back(EVTNode);
3525 Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3526 &IdxOps[0], IdxOps.size()));
3527 Ops.push_back(NumEltsNode);
3528 Ops.push_back(EVTNode);
3529 SDOperand Result = DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
3530 &Ops[0], Ops.size());
3531 if (NumEltsNode != DstVecSize || EVTNode != DstVecEVT) {
3532 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
3533 DstVecSize, DstVecEVT);
3541 /// visitVBinOp - Visit a binary vector operation, like VADD. IntOp indicates
3542 /// the scalar operation of the vop if it is operating on an integer vector
3543 /// (e.g. ADD) and FPOp indicates the FP version (e.g. FADD).
3544 SDOperand DAGCombiner::visitVBinOp(SDNode *N, ISD::NodeType IntOp,
3545 ISD::NodeType FPOp) {
3546 MVT::ValueType EltType = cast<VTSDNode>(*(N->op_end()-1))->getVT();
3547 ISD::NodeType ScalarOp = MVT::isInteger(EltType) ? IntOp : FPOp;
3548 SDOperand LHS = N->getOperand(0);
3549 SDOperand RHS = N->getOperand(1);
3550 SDOperand Shuffle = XformToShuffleWithZero(N);
3551 if (Shuffle.Val) return Shuffle;
3553 // If the LHS and RHS are VBUILD_VECTOR nodes, see if we can constant fold
3555 if (LHS.getOpcode() == ISD::VBUILD_VECTOR &&
3556 RHS.getOpcode() == ISD::VBUILD_VECTOR) {
3557 SmallVector<SDOperand, 8> Ops;
3558 for (unsigned i = 0, e = LHS.getNumOperands()-2; i != e; ++i) {
3559 SDOperand LHSOp = LHS.getOperand(i);
3560 SDOperand RHSOp = RHS.getOperand(i);
3561 // If these two elements can't be folded, bail out.
3562 if ((LHSOp.getOpcode() != ISD::UNDEF &&
3563 LHSOp.getOpcode() != ISD::Constant &&
3564 LHSOp.getOpcode() != ISD::ConstantFP) ||
3565 (RHSOp.getOpcode() != ISD::UNDEF &&
3566 RHSOp.getOpcode() != ISD::Constant &&
3567 RHSOp.getOpcode() != ISD::ConstantFP))
3569 // Can't fold divide by zero.
3570 if (N->getOpcode() == ISD::VSDIV || N->getOpcode() == ISD::VUDIV) {
3571 if ((RHSOp.getOpcode() == ISD::Constant &&
3572 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
3573 (RHSOp.getOpcode() == ISD::ConstantFP &&
3574 !cast<ConstantFPSDNode>(RHSOp.Val)->getValue()))
3577 Ops.push_back(DAG.getNode(ScalarOp, EltType, LHSOp, RHSOp));
3578 AddToWorkList(Ops.back().Val);
3579 assert((Ops.back().getOpcode() == ISD::UNDEF ||
3580 Ops.back().getOpcode() == ISD::Constant ||
3581 Ops.back().getOpcode() == ISD::ConstantFP) &&
3582 "Scalar binop didn't fold!");
3585 if (Ops.size() == LHS.getNumOperands()-2) {
3586 Ops.push_back(*(LHS.Val->op_end()-2));
3587 Ops.push_back(*(LHS.Val->op_end()-1));
3588 return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
3595 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
3596 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
3598 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
3599 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3600 // If we got a simplified select_cc node back from SimplifySelectCC, then
3601 // break it down into a new SETCC node, and a new SELECT node, and then return
3602 // the SELECT node, since we were called with a SELECT node.
3604 // Check to see if we got a select_cc back (to turn into setcc/select).
3605 // Otherwise, just return whatever node we got back, like fabs.
3606 if (SCC.getOpcode() == ISD::SELECT_CC) {
3607 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
3608 SCC.getOperand(0), SCC.getOperand(1),
3610 AddToWorkList(SETCC.Val);
3611 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
3612 SCC.getOperand(3), SETCC);
3619 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
3620 /// are the two values being selected between, see if we can simplify the
3621 /// select. Callers of this should assume that TheSelect is deleted if this
3622 /// returns true. As such, they should return the appropriate thing (e.g. the
3623 /// node) back to the top-level of the DAG combiner loop to avoid it being
3626 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
3629 // If this is a select from two identical things, try to pull the operation
3630 // through the select.
3631 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
3632 // If this is a load and the token chain is identical, replace the select
3633 // of two loads with a load through a select of the address to load from.
3634 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
3635 // constants have been dropped into the constant pool.
3636 if (LHS.getOpcode() == ISD::LOAD &&
3637 // Token chains must be identical.
3638 LHS.getOperand(0) == RHS.getOperand(0)) {
3639 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
3640 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
3642 // If this is an EXTLOAD, the VT's must match.
3643 if (LLD->getLoadedVT() == RLD->getLoadedVT()) {
3644 // FIXME: this conflates two src values, discarding one. This is not
3645 // the right thing to do, but nothing uses srcvalues now. When they do,
3646 // turn SrcValue into a list of locations.
3648 if (TheSelect->getOpcode() == ISD::SELECT)
3649 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
3650 TheSelect->getOperand(0), LLD->getBasePtr(),
3653 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
3654 TheSelect->getOperand(0),
3655 TheSelect->getOperand(1),
3656 LLD->getBasePtr(), RLD->getBasePtr(),
3657 TheSelect->getOperand(4));
3660 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
3661 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
3662 Addr,LLD->getSrcValue(), LLD->getSrcValueOffset());
3664 Load = DAG.getExtLoad(LLD->getExtensionType(),
3665 TheSelect->getValueType(0),
3666 LLD->getChain(), Addr, LLD->getSrcValue(),
3667 LLD->getSrcValueOffset(),
3668 LLD->getLoadedVT());
3670 // Users of the select now use the result of the load.
3671 CombineTo(TheSelect, Load);
3673 // Users of the old loads now use the new load's chain. We know the
3674 // old-load value is dead now.
3675 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
3676 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
3685 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
3686 SDOperand N2, SDOperand N3,
3689 MVT::ValueType VT = N2.getValueType();
3690 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
3691 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
3692 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
3694 // Determine if the condition we're dealing with is constant
3695 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
3696 if (SCC.Val) AddToWorkList(SCC.Val);
3697 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
3699 // fold select_cc true, x, y -> x
3700 if (SCCC && SCCC->getValue())
3702 // fold select_cc false, x, y -> y
3703 if (SCCC && SCCC->getValue() == 0)
3706 // Check to see if we can simplify the select into an fabs node
3707 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
3708 // Allow either -0.0 or 0.0
3709 if (CFP->getValue() == 0.0) {
3710 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
3711 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
3712 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
3713 N2 == N3.getOperand(0))
3714 return DAG.getNode(ISD::FABS, VT, N0);
3716 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
3717 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
3718 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
3719 N2.getOperand(0) == N3)
3720 return DAG.getNode(ISD::FABS, VT, N3);
3724 // Check to see if we can perform the "gzip trick", transforming
3725 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
3726 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
3727 MVT::isInteger(N0.getValueType()) &&
3728 MVT::isInteger(N2.getValueType()) &&
3729 (N1C->isNullValue() || // (a < 0) ? b : 0
3730 (N1C->getValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
3731 MVT::ValueType XType = N0.getValueType();
3732 MVT::ValueType AType = N2.getValueType();
3733 if (XType >= AType) {
3734 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
3735 // single-bit constant.
3736 if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
3737 unsigned ShCtV = Log2_64(N2C->getValue());
3738 ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
3739 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
3740 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
3741 AddToWorkList(Shift.Val);
3742 if (XType > AType) {
3743 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
3744 AddToWorkList(Shift.Val);
3746 return DAG.getNode(ISD::AND, AType, Shift, N2);
3748 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
3749 DAG.getConstant(MVT::getSizeInBits(XType)-1,
3750 TLI.getShiftAmountTy()));
3751 AddToWorkList(Shift.Val);
3752 if (XType > AType) {
3753 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
3754 AddToWorkList(Shift.Val);
3756 return DAG.getNode(ISD::AND, AType, Shift, N2);
3760 // fold select C, 16, 0 -> shl C, 4
3761 if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
3762 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
3763 // Get a SetCC of the condition
3764 // FIXME: Should probably make sure that setcc is legal if we ever have a
3765 // target where it isn't.
3766 SDOperand Temp, SCC;
3767 // cast from setcc result type to select result type
3768 if (AfterLegalize) {
3769 SCC = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
3770 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
3772 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
3773 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
3775 AddToWorkList(SCC.Val);
3776 AddToWorkList(Temp.Val);
3777 // shl setcc result by log2 n2c
3778 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
3779 DAG.getConstant(Log2_64(N2C->getValue()),
3780 TLI.getShiftAmountTy()));
3783 // Check to see if this is the equivalent of setcc
3784 // FIXME: Turn all of these into setcc if setcc if setcc is legal
3785 // otherwise, go ahead with the folds.
3786 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
3787 MVT::ValueType XType = N0.getValueType();
3788 if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
3789 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
3790 if (Res.getValueType() != VT)
3791 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
3795 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
3796 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
3797 TLI.isOperationLegal(ISD::CTLZ, XType)) {
3798 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
3799 return DAG.getNode(ISD::SRL, XType, Ctlz,
3800 DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
3801 TLI.getShiftAmountTy()));
3803 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
3804 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
3805 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
3807 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
3808 DAG.getConstant(~0ULL, XType));
3809 return DAG.getNode(ISD::SRL, XType,
3810 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
3811 DAG.getConstant(MVT::getSizeInBits(XType)-1,
3812 TLI.getShiftAmountTy()));
3814 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
3815 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
3816 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
3817 DAG.getConstant(MVT::getSizeInBits(XType)-1,
3818 TLI.getShiftAmountTy()));
3819 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
3823 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
3824 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
3825 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
3826 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) {
3827 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0))) {
3828 MVT::ValueType XType = N0.getValueType();
3829 if (SubC->isNullValue() && MVT::isInteger(XType)) {
3830 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
3831 DAG.getConstant(MVT::getSizeInBits(XType)-1,
3832 TLI.getShiftAmountTy()));
3833 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
3834 AddToWorkList(Shift.Val);
3835 AddToWorkList(Add.Val);
3836 return DAG.getNode(ISD::XOR, XType, Add, Shift);
3844 SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
3845 SDOperand N1, ISD::CondCode Cond,
3846 bool foldBooleans) {
3847 // These setcc operations always fold.
3851 case ISD::SETFALSE2: return DAG.getConstant(0, VT);
3853 case ISD::SETTRUE2: return DAG.getConstant(1, VT);
3856 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
3857 uint64_t C1 = N1C->getValue();
3858 if (isa<ConstantSDNode>(N0.Val)) {
3859 return DAG.FoldSetCC(VT, N0, N1, Cond);
3861 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3862 // equality comparison, then we're just comparing whether X itself is
3864 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
3865 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
3866 N0.getOperand(1).getOpcode() == ISD::Constant) {
3867 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
3868 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3869 ShAmt == Log2_32(MVT::getSizeInBits(N0.getValueType()))) {
3870 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
3871 // (srl (ctlz x), 5) == 0 -> X != 0
3872 // (srl (ctlz x), 5) != 1 -> X != 0
3875 // (srl (ctlz x), 5) != 0 -> X == 0
3876 // (srl (ctlz x), 5) == 1 -> X == 0
3879 SDOperand Zero = DAG.getConstant(0, N0.getValueType());
3880 return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0),
3885 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3886 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
3887 unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
3889 // If the comparison constant has bits in the upper part, the
3890 // zero-extended value could never match.
3891 if (C1 & (~0ULL << InSize)) {
3892 unsigned VSize = MVT::getSizeInBits(N0.getValueType());
3896 case ISD::SETEQ: return DAG.getConstant(0, VT);
3899 case ISD::SETNE: return DAG.getConstant(1, VT);
3902 // True if the sign bit of C1 is set.
3903 return DAG.getConstant((C1 & (1ULL << VSize)) != 0, VT);
3906 // True if the sign bit of C1 isn't set.
3907 return DAG.getConstant((C1 & (1ULL << VSize)) == 0, VT);
3913 // Otherwise, we can perform the comparison with the low bits.
3921 return DAG.getSetCC(VT, N0.getOperand(0),
3922 DAG.getConstant(C1, N0.getOperand(0).getValueType()),
3925 break; // todo, be more careful with signed comparisons
3927 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3928 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3929 MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
3930 unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
3931 MVT::ValueType ExtDstTy = N0.getValueType();
3932 unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
3934 // If the extended part has any inconsistent bits, it cannot ever
3935 // compare equal. In other words, they have to be all ones or all
3938 (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
3939 if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
3940 return DAG.getConstant(Cond == ISD::SETNE, VT);
3943 MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
3944 if (Op0Ty == ExtSrcTy) {
3945 ZextOp = N0.getOperand(0);
3947 int64_t Imm = ~0ULL >> (64-ExtSrcTyBits);
3948 ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
3949 DAG.getConstant(Imm, Op0Ty));
3951 AddToWorkList(ZextOp.Val);
3952 // Otherwise, make this a use of a zext.
3953 return DAG.getSetCC(VT, ZextOp,
3954 DAG.getConstant(C1 & (~0ULL>>(64-ExtSrcTyBits)),
3957 } else if ((N1C->getValue() == 0 || N1C->getValue() == 1) &&
3958 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3960 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
3961 if (N0.getOpcode() == ISD::SETCC) {
3962 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getValue() != 1);
3966 // Invert the condition.
3967 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
3968 CC = ISD::getSetCCInverse(CC,
3969 MVT::isInteger(N0.getOperand(0).getValueType()));
3970 return DAG.getSetCC(VT, N0.getOperand(0), N0.getOperand(1), CC);
3973 if ((N0.getOpcode() == ISD::XOR ||
3974 (N0.getOpcode() == ISD::AND &&
3975 N0.getOperand(0).getOpcode() == ISD::XOR &&
3976 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
3977 isa<ConstantSDNode>(N0.getOperand(1)) &&
3978 cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
3979 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
3980 // can only do this if the top bits are known zero.
3981 if (TLI.MaskedValueIsZero(N0,
3982 MVT::getIntVTBitMask(N0.getValueType())-1)){
3983 // Okay, get the un-inverted input value.
3985 if (N0.getOpcode() == ISD::XOR)
3986 Val = N0.getOperand(0);
3988 assert(N0.getOpcode() == ISD::AND &&
3989 N0.getOperand(0).getOpcode() == ISD::XOR);
3990 // ((X^1)&1)^1 -> X & 1
3991 Val = DAG.getNode(ISD::AND, N0.getValueType(),
3992 N0.getOperand(0).getOperand(0),
3995 return DAG.getSetCC(VT, Val, N1,
3996 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4001 uint64_t MinVal, MaxVal;
4002 unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
4003 if (ISD::isSignedIntSetCC(Cond)) {
4004 MinVal = 1ULL << (OperandBitSize-1);
4005 if (OperandBitSize != 1) // Avoid X >> 64, which is undefined.
4006 MaxVal = ~0ULL >> (65-OperandBitSize);
4011 MaxVal = ~0ULL >> (64-OperandBitSize);
4014 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
4015 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
4016 if (C1 == MinVal) return DAG.getConstant(1, VT); // X >= MIN --> true
4017 --C1; // X >= C0 --> X > (C0-1)
4018 return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
4019 (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
4022 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
4023 if (C1 == MaxVal) return DAG.getConstant(1, VT); // X <= MAX --> true
4024 ++C1; // X <= C0 --> X < (C0+1)
4025 return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
4026 (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
4029 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
4030 return DAG.getConstant(0, VT); // X < MIN --> false
4032 // Canonicalize setgt X, Min --> setne X, Min
4033 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
4034 return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
4035 // Canonicalize setlt X, Max --> setne X, Max
4036 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
4037 return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
4039 // If we have setult X, 1, turn it into seteq X, 0
4040 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
4041 return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
4043 // If we have setugt X, Max-1, turn it into seteq X, Max
4044 else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
4045 return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
4048 // If we have "setcc X, C0", check to see if we can shrink the immediate
4051 // SETUGT X, SINTMAX -> SETLT X, 0
4052 if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
4053 C1 == (~0ULL >> (65-OperandBitSize)))
4054 return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
4057 // FIXME: Implement the rest of these.
4059 // Fold bit comparisons when we can.
4060 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4061 VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
4062 if (ConstantSDNode *AndRHS =
4063 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4064 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
4065 // Perform the xform if the AND RHS is a single bit.
4066 if (isPowerOf2_64(AndRHS->getValue())) {
4067 return DAG.getNode(ISD::SRL, VT, N0,
4068 DAG.getConstant(Log2_64(AndRHS->getValue()),
4069 TLI.getShiftAmountTy()));
4071 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
4072 // (X & 8) == 8 --> (X & 8) >> 3
4073 // Perform the xform if C1 is a single bit.
4074 if (isPowerOf2_64(C1)) {
4075 return DAG.getNode(ISD::SRL, VT, N0,
4076 DAG.getConstant(Log2_64(C1),TLI.getShiftAmountTy()));
4081 } else if (isa<ConstantSDNode>(N0.Val)) {
4082 // Ensure that the constant occurs on the RHS.
4083 return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
4086 if (isa<ConstantFPSDNode>(N0.Val)) {
4087 // Constant fold or commute setcc.
4088 SDOperand O = DAG.FoldSetCC(VT, N0, N1, Cond);
4089 if (O.Val) return O;
4093 // We can always fold X == X for integer setcc's.
4094 if (MVT::isInteger(N0.getValueType()))
4095 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
4096 unsigned UOF = ISD::getUnorderedFlavor(Cond);
4097 if (UOF == 2) // FP operators that are undefined on NaNs.
4098 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
4099 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
4100 return DAG.getConstant(UOF, VT);
4101 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
4102 // if it is not already.
4103 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
4104 if (NewCond != Cond)
4105 return DAG.getSetCC(VT, N0, N1, NewCond);
4108 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4109 MVT::isInteger(N0.getValueType())) {
4110 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
4111 N0.getOpcode() == ISD::XOR) {
4112 // Simplify (X+Y) == (X+Z) --> Y == Z
4113 if (N0.getOpcode() == N1.getOpcode()) {
4114 if (N0.getOperand(0) == N1.getOperand(0))
4115 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
4116 if (N0.getOperand(1) == N1.getOperand(1))
4117 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
4118 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
4119 // If X op Y == Y op X, try other combinations.
4120 if (N0.getOperand(0) == N1.getOperand(1))
4121 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
4122 if (N0.getOperand(1) == N1.getOperand(0))
4123 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
4127 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
4128 if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4129 // Turn (X+C1) == C2 --> X == C2-C1
4130 if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
4131 return DAG.getSetCC(VT, N0.getOperand(0),
4132 DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
4133 N0.getValueType()), Cond);
4136 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
4137 if (N0.getOpcode() == ISD::XOR)
4138 // If we know that all of the inverted bits are zero, don't bother
4139 // performing the inversion.
4140 if (TLI.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getValue()))
4141 return DAG.getSetCC(VT, N0.getOperand(0),
4142 DAG.getConstant(LHSR->getValue()^RHSC->getValue(),
4143 N0.getValueType()), Cond);
4146 // Turn (C1-X) == C2 --> X == C1-C2
4147 if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
4148 if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
4149 return DAG.getSetCC(VT, N0.getOperand(1),
4150 DAG.getConstant(SUBC->getValue()-RHSC->getValue(),
4151 N0.getValueType()), Cond);
4156 // Simplify (X+Z) == X --> Z == 0
4157 if (N0.getOperand(0) == N1)
4158 return DAG.getSetCC(VT, N0.getOperand(1),
4159 DAG.getConstant(0, N0.getValueType()), Cond);
4160 if (N0.getOperand(1) == N1) {
4161 if (DAG.isCommutativeBinOp(N0.getOpcode()))
4162 return DAG.getSetCC(VT, N0.getOperand(0),
4163 DAG.getConstant(0, N0.getValueType()), Cond);
4165 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
4166 // (Z-X) == X --> Z == X<<1
4167 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
4169 DAG.getConstant(1,TLI.getShiftAmountTy()));
4170 AddToWorkList(SH.Val);
4171 return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
4176 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
4177 N1.getOpcode() == ISD::XOR) {
4178 // Simplify X == (X+Z) --> Z == 0
4179 if (N1.getOperand(0) == N0) {
4180 return DAG.getSetCC(VT, N1.getOperand(1),
4181 DAG.getConstant(0, N1.getValueType()), Cond);
4182 } else if (N1.getOperand(1) == N0) {
4183 if (DAG.isCommutativeBinOp(N1.getOpcode())) {
4184 return DAG.getSetCC(VT, N1.getOperand(0),
4185 DAG.getConstant(0, N1.getValueType()), Cond);
4187 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
4188 // X == (Z-X) --> X<<1 == Z
4189 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0,
4190 DAG.getConstant(1,TLI.getShiftAmountTy()));
4191 AddToWorkList(SH.Val);
4192 return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
4198 // Fold away ALL boolean setcc's.
4200 if (N0.getValueType() == MVT::i1 && foldBooleans) {
4202 default: assert(0 && "Unknown integer setcc!");
4203 case ISD::SETEQ: // X == Y -> (X^Y)^1
4204 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
4205 N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
4206 AddToWorkList(Temp.Val);
4208 case ISD::SETNE: // X != Y --> (X^Y)
4209 N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
4211 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> X^1 & Y
4212 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> X^1 & Y
4213 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
4214 N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
4215 AddToWorkList(Temp.Val);
4217 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> Y^1 & X
4218 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> Y^1 & X
4219 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
4220 N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
4221 AddToWorkList(Temp.Val);
4223 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> X^1 | Y
4224 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> X^1 | Y
4225 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
4226 N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
4227 AddToWorkList(Temp.Val);
4229 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> Y^1 | X
4230 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> Y^1 | X
4231 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
4232 N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
4235 if (VT != MVT::i1) {
4236 AddToWorkList(N0.Val);
4237 // FIXME: If running after legalize, we probably can't do this.
4238 N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
4243 // Could not fold it.
4247 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
4248 /// return a DAG expression to select that will generate the same value by
4249 /// multiplying by a magic number. See:
4250 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4251 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
4252 std::vector<SDNode*> Built;
4253 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
4255 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4261 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
4262 /// return a DAG expression to select that will generate the same value by
4263 /// multiplying by a magic number. See:
4264 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4265 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
4266 std::vector<SDNode*> Built;
4267 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
4269 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4275 /// FindBaseOffset - Return true if base is known not to alias with anything
4276 /// but itself. Provides base object and offset as results.
4277 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
4278 // Assume it is a primitive operation.
4279 Base = Ptr; Offset = 0;
4281 // If it's an adding a simple constant then integrate the offset.
4282 if (Base.getOpcode() == ISD::ADD) {
4283 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
4284 Base = Base.getOperand(0);
4285 Offset += C->getValue();
4289 // If it's any of the following then it can't alias with anything but itself.
4290 return isa<FrameIndexSDNode>(Base) ||
4291 isa<ConstantPoolSDNode>(Base) ||
4292 isa<GlobalAddressSDNode>(Base);
4295 /// isAlias - Return true if there is any possibility that the two addresses
4297 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
4298 const Value *SrcValue1, int SrcValueOffset1,
4299 SDOperand Ptr2, int64_t Size2,
4300 const Value *SrcValue2, int SrcValueOffset2)
4302 // If they are the same then they must be aliases.
4303 if (Ptr1 == Ptr2) return true;
4305 // Gather base node and offset information.
4306 SDOperand Base1, Base2;
4307 int64_t Offset1, Offset2;
4308 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
4309 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
4311 // If they have a same base address then...
4312 if (Base1 == Base2) {
4313 // Check to see if the addresses overlap.
4314 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
4317 // If we know both bases then they can't alias.
4318 if (KnownBase1 && KnownBase2) return false;
4320 if (CombinerGlobalAA) {
4321 // Use alias analysis information.
4322 int Overlap1 = Size1 + SrcValueOffset1 + Offset1;
4323 int Overlap2 = Size2 + SrcValueOffset2 + Offset2;
4324 AliasAnalysis::AliasResult AAResult =
4325 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
4326 if (AAResult == AliasAnalysis::NoAlias)
4330 // Otherwise we have to assume they alias.
4334 /// FindAliasInfo - Extracts the relevant alias information from the memory
4335 /// node. Returns true if the operand was a load.
4336 bool DAGCombiner::FindAliasInfo(SDNode *N,
4337 SDOperand &Ptr, int64_t &Size,
4338 const Value *&SrcValue, int &SrcValueOffset) {
4339 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4340 Ptr = LD->getBasePtr();
4341 Size = MVT::getSizeInBits(LD->getLoadedVT()) >> 3;
4342 SrcValue = LD->getSrcValue();
4343 SrcValueOffset = LD->getSrcValueOffset();
4345 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4346 Ptr = ST->getBasePtr();
4347 Size = MVT::getSizeInBits(ST->getStoredVT()) >> 3;
4348 SrcValue = ST->getSrcValue();
4349 SrcValueOffset = ST->getSrcValueOffset();
4351 assert(0 && "FindAliasInfo expected a memory operand");
4357 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
4358 /// looking for aliasing nodes and adding them to the Aliases vector.
4359 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
4360 SmallVector<SDOperand, 8> &Aliases) {
4361 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
4362 std::set<SDNode *> Visited; // Visited node set.
4364 // Get alias information for node.
4367 const Value *SrcValue;
4369 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
4372 Chains.push_back(OriginalChain);
4374 // Look at each chain and determine if it is an alias. If so, add it to the
4375 // aliases list. If not, then continue up the chain looking for the next
4377 while (!Chains.empty()) {
4378 SDOperand Chain = Chains.back();
4381 // Don't bother if we've been before.
4382 if (Visited.find(Chain.Val) != Visited.end()) continue;
4383 Visited.insert(Chain.Val);
4385 switch (Chain.getOpcode()) {
4386 case ISD::EntryToken:
4387 // Entry token is ideal chain operand, but handled in FindBetterChain.
4392 // Get alias information for Chain.
4395 const Value *OpSrcValue;
4396 int OpSrcValueOffset;
4397 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
4398 OpSrcValue, OpSrcValueOffset);
4400 // If chain is alias then stop here.
4401 if (!(IsLoad && IsOpLoad) &&
4402 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
4403 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
4404 Aliases.push_back(Chain);
4406 // Look further up the chain.
4407 Chains.push_back(Chain.getOperand(0));
4408 // Clean up old chain.
4409 AddToWorkList(Chain.Val);
4414 case ISD::TokenFactor:
4415 // We have to check each of the operands of the token factor, so we queue
4416 // then up. Adding the operands to the queue (stack) in reverse order
4417 // maintains the original order and increases the likelihood that getNode
4418 // will find a matching token factor (CSE.)
4419 for (unsigned n = Chain.getNumOperands(); n;)
4420 Chains.push_back(Chain.getOperand(--n));
4421 // Eliminate the token factor if we can.
4422 AddToWorkList(Chain.Val);
4426 // For all other instructions we will just have to take what we can get.
4427 Aliases.push_back(Chain);
4433 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
4434 /// for a better chain (aliasing node.)
4435 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
4436 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
4438 // Accumulate all the aliases to this node.
4439 GatherAllAliases(N, OldChain, Aliases);
4441 if (Aliases.size() == 0) {
4442 // If no operands then chain to entry token.
4443 return DAG.getEntryNode();
4444 } else if (Aliases.size() == 1) {
4445 // If a single operand then chain to it. We don't need to revisit it.
4449 // Construct a custom tailored token factor.
4450 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4451 &Aliases[0], Aliases.size());
4453 // Make sure the old chain gets cleaned up.
4454 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
4459 // SelectionDAG::Combine - This is the entry point for the file.
4461 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
4462 /// run - This is the main entry point to this class.
4464 DAGCombiner(*this, AA).Run(RunningAfterLegalize);