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"
46 static Statistic<> NodesCombined ("dagcombiner",
47 "Number of dag nodes combined");
49 static Statistic<> PreIndexedNodes ("pre_indexed_ops",
50 "Number of pre-indexed nodes created");
51 static Statistic<> PostIndexedNodes ("post_indexed_ops",
52 "Number of post-indexed nodes created");
55 CombinerAA("combiner-alias-analysis", cl::Hidden,
56 cl::desc("Turn on alias analysis during testing"));
59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60 cl::desc("Include global information in alias analysis"));
62 //------------------------------ DAGCombiner ---------------------------------//
64 class VISIBILITY_HIDDEN DAGCombiner {
69 // Worklist of all of the nodes that need to be simplified.
70 std::vector<SDNode*> WorkList;
72 // AA - Used for DAG load/store alias analysis.
75 /// AddUsersToWorkList - When an instruction is simplified, add all users of
76 /// the instruction to the work lists because they might get more simplified
79 void AddUsersToWorkList(SDNode *N) {
80 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
85 /// removeFromWorkList - remove all instances of N from the worklist.
87 void removeFromWorkList(SDNode *N) {
88 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
93 /// AddToWorkList - Add to the work list making sure it's instance is at the
94 /// the back (next to be processed.)
95 void AddToWorkList(SDNode *N) {
96 removeFromWorkList(N);
97 WorkList.push_back(N);
100 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
102 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
104 DEBUG(std::cerr << "\nReplacing.1 "; N->dump();
105 std::cerr << "\nWith: "; To[0].Val->dump(&DAG);
106 std::cerr << " and " << NumTo-1 << " other values\n");
107 std::vector<SDNode*> NowDead;
108 DAG.ReplaceAllUsesWith(N, To, &NowDead);
111 // Push the new nodes and any users onto the worklist
112 for (unsigned i = 0, e = NumTo; i != e; ++i) {
113 AddToWorkList(To[i].Val);
114 AddUsersToWorkList(To[i].Val);
118 // Nodes can be reintroduced into the worklist. Make sure we do not
119 // process a node that has been replaced.
120 removeFromWorkList(N);
121 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
122 removeFromWorkList(NowDead[i]);
124 // Finally, since the node is now dead, remove it from the graph.
126 return SDOperand(N, 0);
129 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
130 return CombineTo(N, &Res, 1, AddTo);
133 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
135 SDOperand To[] = { Res0, Res1 };
136 return CombineTo(N, To, 2, AddTo);
140 /// SimplifyDemandedBits - Check the specified integer node value to see if
141 /// it can be simplified or if things it uses can be simplified by bit
142 /// propagation. If so, return true.
143 bool SimplifyDemandedBits(SDOperand Op) {
144 TargetLowering::TargetLoweringOpt TLO(DAG);
145 uint64_t KnownZero, KnownOne;
146 uint64_t Demanded = MVT::getIntVTBitMask(Op.getValueType());
147 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
151 AddToWorkList(Op.Val);
153 // Replace the old value with the new one.
155 DEBUG(std::cerr << "\nReplacing.2 "; TLO.Old.Val->dump();
156 std::cerr << "\nWith: "; TLO.New.Val->dump(&DAG);
159 std::vector<SDNode*> NowDead;
160 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, NowDead);
162 // Push the new node and any (possibly new) users onto the worklist.
163 AddToWorkList(TLO.New.Val);
164 AddUsersToWorkList(TLO.New.Val);
166 // Nodes can end up on the worklist more than once. Make sure we do
167 // not process a node that has been replaced.
168 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
169 removeFromWorkList(NowDead[i]);
171 // Finally, if the node is now dead, remove it from the graph. The node
172 // may not be dead if the replacement process recursively simplified to
173 // something else needing this node.
174 if (TLO.Old.Val->use_empty()) {
175 removeFromWorkList(TLO.Old.Val);
176 DAG.DeleteNode(TLO.Old.Val);
181 /// CombineToPreIndexedLoadStore - Try turning a load / store and a
182 /// pre-indexed load / store when the base pointer is a add or subtract
183 /// and it has other uses besides the load / store. After the
184 /// transformation, the new indexed load / store has effectively folded
185 /// the add / subtract in and all of its other uses are redirected to the
186 /// new load / store.
187 bool CombineToPreIndexedLoadStore(SDNode *N) {
194 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
195 VT = LD->getLoadedVT();
196 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
197 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
199 Ptr = LD->getBasePtr();
200 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
201 VT = ST->getStoredVT();
202 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
203 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
205 Ptr = ST->getBasePtr();
210 if ((Ptr.getOpcode() == ISD::ADD || Ptr.getOpcode() == ISD::SUB) &&
211 Ptr.Val->use_size() > 1) {
214 ISD::MemIndexedMode AM = ISD::UNINDEXED;
215 if (TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) {
216 // Try turning it into a pre-indexed load / store except when
217 // 1) Another use of base ptr is a predecessor of N. If ptr is folded
218 // that would create a cycle.
219 // 2) All uses are load / store ops that use it as base ptr.
221 // Now check for #1 and #2.
222 bool RealUse = false;
223 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
224 E = Ptr.Val->use_end(); I != E; ++I) {
228 if (Use->isPredecessor(N))
231 if (!((Use->getOpcode() == ISD::LOAD &&
232 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
233 (Use->getOpcode() == ISD::STORE) &&
234 cast<StoreSDNode>(Use)->getBasePtr() == Ptr))
240 SDOperand Result = isLoad
241 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
242 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
245 DEBUG(std::cerr << "\nReplacing.4 "; N->dump();
246 std::cerr << "\nWith: "; Result.Val->dump(&DAG);
248 std::vector<SDNode*> NowDead;
250 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
252 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
255 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
259 // Nodes can end up on the worklist more than once. Make sure we do
260 // not process a node that has been replaced.
261 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
262 removeFromWorkList(NowDead[i]);
263 // Finally, since the node is now dead, remove it from the graph.
266 // Replace the uses of Ptr with uses of the updated base value.
267 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
269 removeFromWorkList(Ptr.Val);
270 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
271 removeFromWorkList(NowDead[i]);
272 DAG.DeleteNode(Ptr.Val);
280 /// CombineToPostIndexedLoadStore - Try combine a load / store with a
281 /// add / sub of the base pointer node into a post-indexed load / store.
282 /// The transformation folded the add / subtract into the new indexed
283 /// load / store effectively and all of its uses are redirected to the
284 /// new load / store.
285 bool CombineToPostIndexedLoadStore(SDNode *N) {
292 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
293 VT = LD->getLoadedVT();
294 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
295 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
297 Ptr = LD->getBasePtr();
298 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
299 VT = ST->getStoredVT();
300 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
301 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
303 Ptr = ST->getBasePtr();
308 if (Ptr.Val->use_size() > 1) {
309 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
310 E = Ptr.Val->use_end(); I != E; ++I) {
313 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
318 ISD::MemIndexedMode AM = ISD::UNINDEXED;
319 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
321 std::swap(BasePtr, Offset);
325 // Try turning it into a post-indexed load / store except when
326 // 1) Op must be independent of N, i.e. Op is neither a predecessor
327 // nor a successor of N. Otherwise, if Op is folded that would
329 // 2) All uses are load / store ops that use it as base ptr.
332 bool TryNext = false;
333 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
334 EE = BasePtr.Val->use_end(); II != EE; ++II) {
339 // If all the uses are load / store addresses, then don't do the
341 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
342 bool RealUse = false;
343 for (SDNode::use_iterator III = Use->use_begin(),
344 EEE = Use->use_end(); III != EEE; ++III) {
345 SDNode *UseUse = *III;
346 if (!((UseUse->getOpcode() == ISD::LOAD &&
347 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
348 (UseUse->getOpcode() == ISD::STORE) &&
349 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use))
363 if (!Op->isPredecessor(N) && !N->isPredecessor(Op)) {
364 SDOperand Result = isLoad
365 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
366 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
369 DEBUG(std::cerr << "\nReplacing.5 "; N->dump();
370 std::cerr << "\nWith: "; Result.Val->dump(&DAG);
372 std::vector<SDNode*> NowDead;
374 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
376 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
379 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
383 // Nodes can end up on the worklist more than once. Make sure we do
384 // not process a node that has been replaced.
385 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
386 removeFromWorkList(NowDead[i]);
387 // Finally, since the node is now dead, remove it from the graph.
390 // Replace the uses of Use with uses of the updated base value.
391 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
392 Result.getValue(isLoad ? 1 : 0),
394 removeFromWorkList(Op);
395 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
396 removeFromWorkList(NowDead[i]);
407 /// visit - call the node-specific routine that knows how to fold each
408 /// particular type of node.
409 SDOperand visit(SDNode *N);
411 // Visitation implementation - Implement dag node combining for different
412 // node types. The semantics are as follows:
414 // SDOperand.Val == 0 - No change was made
415 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
416 // otherwise - N should be replaced by the returned Operand.
418 SDOperand visitTokenFactor(SDNode *N);
419 SDOperand visitADD(SDNode *N);
420 SDOperand visitSUB(SDNode *N);
421 SDOperand visitMUL(SDNode *N);
422 SDOperand visitSDIV(SDNode *N);
423 SDOperand visitUDIV(SDNode *N);
424 SDOperand visitSREM(SDNode *N);
425 SDOperand visitUREM(SDNode *N);
426 SDOperand visitMULHU(SDNode *N);
427 SDOperand visitMULHS(SDNode *N);
428 SDOperand visitAND(SDNode *N);
429 SDOperand visitOR(SDNode *N);
430 SDOperand visitXOR(SDNode *N);
431 SDOperand visitVBinOp(SDNode *N, ISD::NodeType IntOp, ISD::NodeType FPOp);
432 SDOperand visitSHL(SDNode *N);
433 SDOperand visitSRA(SDNode *N);
434 SDOperand visitSRL(SDNode *N);
435 SDOperand visitCTLZ(SDNode *N);
436 SDOperand visitCTTZ(SDNode *N);
437 SDOperand visitCTPOP(SDNode *N);
438 SDOperand visitSELECT(SDNode *N);
439 SDOperand visitSELECT_CC(SDNode *N);
440 SDOperand visitSETCC(SDNode *N);
441 SDOperand visitSIGN_EXTEND(SDNode *N);
442 SDOperand visitZERO_EXTEND(SDNode *N);
443 SDOperand visitANY_EXTEND(SDNode *N);
444 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
445 SDOperand visitTRUNCATE(SDNode *N);
446 SDOperand visitBIT_CONVERT(SDNode *N);
447 SDOperand visitVBIT_CONVERT(SDNode *N);
448 SDOperand visitFADD(SDNode *N);
449 SDOperand visitFSUB(SDNode *N);
450 SDOperand visitFMUL(SDNode *N);
451 SDOperand visitFDIV(SDNode *N);
452 SDOperand visitFREM(SDNode *N);
453 SDOperand visitFCOPYSIGN(SDNode *N);
454 SDOperand visitSINT_TO_FP(SDNode *N);
455 SDOperand visitUINT_TO_FP(SDNode *N);
456 SDOperand visitFP_TO_SINT(SDNode *N);
457 SDOperand visitFP_TO_UINT(SDNode *N);
458 SDOperand visitFP_ROUND(SDNode *N);
459 SDOperand visitFP_ROUND_INREG(SDNode *N);
460 SDOperand visitFP_EXTEND(SDNode *N);
461 SDOperand visitFNEG(SDNode *N);
462 SDOperand visitFABS(SDNode *N);
463 SDOperand visitBRCOND(SDNode *N);
464 SDOperand visitBR_CC(SDNode *N);
465 SDOperand visitLOAD(SDNode *N);
466 SDOperand visitSTORE(SDNode *N);
467 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
468 SDOperand visitVINSERT_VECTOR_ELT(SDNode *N);
469 SDOperand visitVBUILD_VECTOR(SDNode *N);
470 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
471 SDOperand visitVVECTOR_SHUFFLE(SDNode *N);
473 SDOperand XformToShuffleWithZero(SDNode *N);
474 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
476 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
477 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
478 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
479 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
480 SDOperand N3, ISD::CondCode CC);
481 SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
482 ISD::CondCode Cond, bool foldBooleans = true);
483 SDOperand ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(SDNode *, MVT::ValueType);
484 SDOperand BuildSDIV(SDNode *N);
485 SDOperand BuildUDIV(SDNode *N);
486 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
488 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
489 /// looking for aliasing nodes and adding them to the Aliases vector.
490 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
491 SmallVector<SDOperand, 8> &Aliases);
493 /// isAlias - Return true if there is any possibility that the two addresses
495 bool isAlias(SDOperand Ptr1, int64_t Size1,
496 const Value *SrcValue1, int SrcValueOffset1,
497 SDOperand Ptr2, int64_t Size2,
498 const Value *SrcValue2, int SrcValueOffset2);
500 /// FindAliasInfo - Extracts the relevant alias information from the memory
501 /// node. Returns true if the operand was a load.
502 bool FindAliasInfo(SDNode *N,
503 SDOperand &Ptr, int64_t &Size,
504 const Value *&SrcValue, int &SrcValueOffset);
506 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
507 /// looking for a better chain (aliasing node.)
508 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
511 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
513 TLI(D.getTargetLoweringInfo()),
514 AfterLegalize(false),
517 /// Run - runs the dag combiner on all nodes in the work list
518 void Run(bool RunningAfterLegalize);
522 //===----------------------------------------------------------------------===//
523 // TargetLowering::DAGCombinerInfo implementation
524 //===----------------------------------------------------------------------===//
526 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
527 ((DAGCombiner*)DC)->AddToWorkList(N);
530 SDOperand TargetLowering::DAGCombinerInfo::
531 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
532 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
535 SDOperand TargetLowering::DAGCombinerInfo::
536 CombineTo(SDNode *N, SDOperand Res) {
537 return ((DAGCombiner*)DC)->CombineTo(N, Res);
541 SDOperand TargetLowering::DAGCombinerInfo::
542 CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
543 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
549 //===----------------------------------------------------------------------===//
552 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
553 // that selects between the values 1 and 0, making it equivalent to a setcc.
554 // Also, set the incoming LHS, RHS, and CC references to the appropriate
555 // nodes based on the type of node we are checking. This simplifies life a
556 // bit for the callers.
557 static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
559 if (N.getOpcode() == ISD::SETCC) {
560 LHS = N.getOperand(0);
561 RHS = N.getOperand(1);
562 CC = N.getOperand(2);
565 if (N.getOpcode() == ISD::SELECT_CC &&
566 N.getOperand(2).getOpcode() == ISD::Constant &&
567 N.getOperand(3).getOpcode() == ISD::Constant &&
568 cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
569 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
570 LHS = N.getOperand(0);
571 RHS = N.getOperand(1);
572 CC = N.getOperand(4);
578 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
579 // one use. If this is true, it allows the users to invert the operation for
580 // free when it is profitable to do so.
581 static bool isOneUseSetCC(SDOperand N) {
582 SDOperand N0, N1, N2;
583 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
588 SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
589 MVT::ValueType VT = N0.getValueType();
590 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
591 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
592 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
593 if (isa<ConstantSDNode>(N1)) {
594 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
595 AddToWorkList(OpNode.Val);
596 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
597 } else if (N0.hasOneUse()) {
598 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
599 AddToWorkList(OpNode.Val);
600 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
603 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
604 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
605 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
606 if (isa<ConstantSDNode>(N0)) {
607 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
608 AddToWorkList(OpNode.Val);
609 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
610 } else if (N1.hasOneUse()) {
611 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
612 AddToWorkList(OpNode.Val);
613 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
619 void DAGCombiner::Run(bool RunningAfterLegalize) {
620 // set the instance variable, so that the various visit routines may use it.
621 AfterLegalize = RunningAfterLegalize;
623 // Add all the dag nodes to the worklist.
624 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
625 E = DAG.allnodes_end(); I != E; ++I)
626 WorkList.push_back(I);
628 // Create a dummy node (which is not added to allnodes), that adds a reference
629 // to the root node, preventing it from being deleted, and tracking any
630 // changes of the root.
631 HandleSDNode Dummy(DAG.getRoot());
633 // The root of the dag may dangle to deleted nodes until the dag combiner is
634 // done. Set it to null to avoid confusion.
635 DAG.setRoot(SDOperand());
637 /// DagCombineInfo - Expose the DAG combiner to the target combiner impls.
638 TargetLowering::DAGCombinerInfo
639 DagCombineInfo(DAG, !RunningAfterLegalize, this);
641 // while the worklist isn't empty, inspect the node on the end of it and
642 // try and combine it.
643 while (!WorkList.empty()) {
644 SDNode *N = WorkList.back();
647 // If N has no uses, it is dead. Make sure to revisit all N's operands once
648 // N is deleted from the DAG, since they too may now be dead or may have a
649 // reduced number of uses, allowing other xforms.
650 if (N->use_empty() && N != &Dummy) {
651 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
652 AddToWorkList(N->getOperand(i).Val);
658 SDOperand RV = visit(N);
660 // If nothing happened, try a target-specific DAG combine.
662 assert(N->getOpcode() != ISD::DELETED_NODE &&
663 "Node was deleted but visit returned NULL!");
664 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
665 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode()))
666 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
671 // If we get back the same node we passed in, rather than a new node or
672 // zero, we know that the node must have defined multiple values and
673 // CombineTo was used. Since CombineTo takes care of the worklist
674 // mechanics for us, we have no work to do in this case.
676 assert(N->getOpcode() != ISD::DELETED_NODE &&
677 RV.Val->getOpcode() != ISD::DELETED_NODE &&
678 "Node was deleted but visit returned new node!");
680 DEBUG(std::cerr << "\nReplacing.3 "; N->dump();
681 std::cerr << "\nWith: "; RV.Val->dump(&DAG);
683 std::vector<SDNode*> NowDead;
684 if (N->getNumValues() == RV.Val->getNumValues())
685 DAG.ReplaceAllUsesWith(N, RV.Val, &NowDead);
687 assert(N->getValueType(0) == RV.getValueType() && "Type mismatch");
689 DAG.ReplaceAllUsesWith(N, &OpV, &NowDead);
692 // Push the new node and any users onto the worklist
693 AddToWorkList(RV.Val);
694 AddUsersToWorkList(RV.Val);
696 // Nodes can be reintroduced into the worklist. Make sure we do not
697 // process a node that has been replaced.
698 removeFromWorkList(N);
699 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
700 removeFromWorkList(NowDead[i]);
702 // Finally, since the node is now dead, remove it from the graph.
708 // If the root changed (e.g. it was a dead load, update the root).
709 DAG.setRoot(Dummy.getValue());
712 SDOperand DAGCombiner::visit(SDNode *N) {
713 switch(N->getOpcode()) {
715 case ISD::TokenFactor: return visitTokenFactor(N);
716 case ISD::ADD: return visitADD(N);
717 case ISD::SUB: return visitSUB(N);
718 case ISD::MUL: return visitMUL(N);
719 case ISD::SDIV: return visitSDIV(N);
720 case ISD::UDIV: return visitUDIV(N);
721 case ISD::SREM: return visitSREM(N);
722 case ISD::UREM: return visitUREM(N);
723 case ISD::MULHU: return visitMULHU(N);
724 case ISD::MULHS: return visitMULHS(N);
725 case ISD::AND: return visitAND(N);
726 case ISD::OR: return visitOR(N);
727 case ISD::XOR: return visitXOR(N);
728 case ISD::SHL: return visitSHL(N);
729 case ISD::SRA: return visitSRA(N);
730 case ISD::SRL: return visitSRL(N);
731 case ISD::CTLZ: return visitCTLZ(N);
732 case ISD::CTTZ: return visitCTTZ(N);
733 case ISD::CTPOP: return visitCTPOP(N);
734 case ISD::SELECT: return visitSELECT(N);
735 case ISD::SELECT_CC: return visitSELECT_CC(N);
736 case ISD::SETCC: return visitSETCC(N);
737 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
738 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
739 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
740 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
741 case ISD::TRUNCATE: return visitTRUNCATE(N);
742 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
743 case ISD::VBIT_CONVERT: return visitVBIT_CONVERT(N);
744 case ISD::FADD: return visitFADD(N);
745 case ISD::FSUB: return visitFSUB(N);
746 case ISD::FMUL: return visitFMUL(N);
747 case ISD::FDIV: return visitFDIV(N);
748 case ISD::FREM: return visitFREM(N);
749 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
750 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
751 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
752 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
753 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
754 case ISD::FP_ROUND: return visitFP_ROUND(N);
755 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
756 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
757 case ISD::FNEG: return visitFNEG(N);
758 case ISD::FABS: return visitFABS(N);
759 case ISD::BRCOND: return visitBRCOND(N);
760 case ISD::BR_CC: return visitBR_CC(N);
761 case ISD::LOAD: return visitLOAD(N);
762 case ISD::STORE: return visitSTORE(N);
763 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
764 case ISD::VINSERT_VECTOR_ELT: return visitVINSERT_VECTOR_ELT(N);
765 case ISD::VBUILD_VECTOR: return visitVBUILD_VECTOR(N);
766 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
767 case ISD::VVECTOR_SHUFFLE: return visitVVECTOR_SHUFFLE(N);
768 case ISD::VADD: return visitVBinOp(N, ISD::ADD , ISD::FADD);
769 case ISD::VSUB: return visitVBinOp(N, ISD::SUB , ISD::FSUB);
770 case ISD::VMUL: return visitVBinOp(N, ISD::MUL , ISD::FMUL);
771 case ISD::VSDIV: return visitVBinOp(N, ISD::SDIV, ISD::FDIV);
772 case ISD::VUDIV: return visitVBinOp(N, ISD::UDIV, ISD::UDIV);
773 case ISD::VAND: return visitVBinOp(N, ISD::AND , ISD::AND);
774 case ISD::VOR: return visitVBinOp(N, ISD::OR , ISD::OR);
775 case ISD::VXOR: return visitVBinOp(N, ISD::XOR , ISD::XOR);
780 /// getInputChainForNode - Given a node, return its input chain if it has one,
781 /// otherwise return a null sd operand.
782 static SDOperand getInputChainForNode(SDNode *N) {
783 if (unsigned NumOps = N->getNumOperands()) {
784 if (N->getOperand(0).getValueType() == MVT::Other)
785 return N->getOperand(0);
786 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
787 return N->getOperand(NumOps-1);
788 for (unsigned i = 1; i < NumOps-1; ++i)
789 if (N->getOperand(i).getValueType() == MVT::Other)
790 return N->getOperand(i);
792 return SDOperand(0, 0);
795 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
796 // If N has two operands, where one has an input chain equal to the other,
797 // the 'other' chain is redundant.
798 if (N->getNumOperands() == 2) {
799 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
800 return N->getOperand(0);
801 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
802 return N->getOperand(1);
806 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
807 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
808 bool Changed = false; // If we should replace this token factor.
810 // Start out with this token factor.
813 // Iterate through token factors. The TFs grows when new token factors are
815 for (unsigned i = 0; i < TFs.size(); ++i) {
818 // Check each of the operands.
819 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
820 SDOperand Op = TF->getOperand(i);
822 switch (Op.getOpcode()) {
823 case ISD::EntryToken:
824 // Entry tokens don't need to be added to the list. They are
829 case ISD::TokenFactor:
830 if ((CombinerAA || Op.hasOneUse()) &&
831 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
832 // Queue up for processing.
833 TFs.push_back(Op.Val);
834 // Clean up in case the token factor is removed.
835 AddToWorkList(Op.Val);
842 // Only add if not there prior.
843 if (std::find(Ops.begin(), Ops.end(), Op) == Ops.end())
852 // If we've change things around then replace token factor.
854 if (Ops.size() == 0) {
855 // The entry token is the only possible outcome.
856 Result = DAG.getEntryNode();
858 // New and improved token factor.
859 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
862 // Don't add users to work list.
863 return CombineTo(N, Result, false);
869 SDOperand DAGCombiner::visitADD(SDNode *N) {
870 SDOperand N0 = N->getOperand(0);
871 SDOperand N1 = N->getOperand(1);
872 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
873 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
874 MVT::ValueType VT = N0.getValueType();
876 // fold (add c1, c2) -> c1+c2
878 return DAG.getNode(ISD::ADD, VT, N0, N1);
879 // canonicalize constant to RHS
881 return DAG.getNode(ISD::ADD, VT, N1, N0);
882 // fold (add x, 0) -> x
883 if (N1C && N1C->isNullValue())
885 // fold ((c1-A)+c2) -> (c1+c2)-A
886 if (N1C && N0.getOpcode() == ISD::SUB)
887 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
888 return DAG.getNode(ISD::SUB, VT,
889 DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
892 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
895 // fold ((0-A) + B) -> B-A
896 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
897 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
898 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
899 // fold (A + (0-B)) -> A-B
900 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
901 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
902 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
903 // fold (A+(B-A)) -> B
904 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
905 return N1.getOperand(0);
907 if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
908 return SDOperand(N, 0);
910 // fold (a+b) -> (a|b) iff a and b share no bits.
911 if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
912 uint64_t LHSZero, LHSOne;
913 uint64_t RHSZero, RHSOne;
914 uint64_t Mask = MVT::getIntVTBitMask(VT);
915 TLI.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
917 TLI.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
919 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
920 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
921 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
922 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
923 return DAG.getNode(ISD::OR, VT, N0, N1);
930 SDOperand DAGCombiner::visitSUB(SDNode *N) {
931 SDOperand N0 = N->getOperand(0);
932 SDOperand N1 = N->getOperand(1);
933 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
934 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
935 MVT::ValueType VT = N0.getValueType();
937 // fold (sub x, x) -> 0
939 return DAG.getConstant(0, N->getValueType(0));
940 // fold (sub c1, c2) -> c1-c2
942 return DAG.getNode(ISD::SUB, VT, N0, N1);
943 // fold (sub x, c) -> (add x, -c)
945 return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
947 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
948 return N0.getOperand(1);
950 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
951 return N0.getOperand(0);
955 SDOperand DAGCombiner::visitMUL(SDNode *N) {
956 SDOperand N0 = N->getOperand(0);
957 SDOperand N1 = N->getOperand(1);
958 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
959 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
960 MVT::ValueType VT = N0.getValueType();
962 // fold (mul c1, c2) -> c1*c2
964 return DAG.getNode(ISD::MUL, VT, N0, N1);
965 // canonicalize constant to RHS
967 return DAG.getNode(ISD::MUL, VT, N1, N0);
968 // fold (mul x, 0) -> 0
969 if (N1C && N1C->isNullValue())
971 // fold (mul x, -1) -> 0-x
972 if (N1C && N1C->isAllOnesValue())
973 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
974 // fold (mul x, (1 << c)) -> x << c
975 if (N1C && isPowerOf2_64(N1C->getValue()))
976 return DAG.getNode(ISD::SHL, VT, N0,
977 DAG.getConstant(Log2_64(N1C->getValue()),
978 TLI.getShiftAmountTy()));
979 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
980 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
981 // FIXME: If the input is something that is easily negated (e.g. a
982 // single-use add), we should put the negate there.
983 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
984 DAG.getNode(ISD::SHL, VT, N0,
985 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
986 TLI.getShiftAmountTy())));
989 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
990 if (N1C && N0.getOpcode() == ISD::SHL &&
991 isa<ConstantSDNode>(N0.getOperand(1))) {
992 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
993 AddToWorkList(C3.Val);
994 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
997 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1000 SDOperand Sh(0,0), Y(0,0);
1001 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1002 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1003 N0.Val->hasOneUse()) {
1005 } else if (N1.getOpcode() == ISD::SHL &&
1006 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1010 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1011 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1014 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1015 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1016 isa<ConstantSDNode>(N0.getOperand(1))) {
1017 return DAG.getNode(ISD::ADD, VT,
1018 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1019 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1023 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1029 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1030 SDOperand N0 = N->getOperand(0);
1031 SDOperand N1 = N->getOperand(1);
1032 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1033 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1034 MVT::ValueType VT = N->getValueType(0);
1036 // fold (sdiv c1, c2) -> c1/c2
1037 if (N0C && N1C && !N1C->isNullValue())
1038 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1039 // fold (sdiv X, 1) -> X
1040 if (N1C && N1C->getSignExtended() == 1LL)
1042 // fold (sdiv X, -1) -> 0-X
1043 if (N1C && N1C->isAllOnesValue())
1044 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1045 // If we know the sign bits of both operands are zero, strength reduce to a
1046 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1047 uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1048 if (TLI.MaskedValueIsZero(N1, SignBit) &&
1049 TLI.MaskedValueIsZero(N0, SignBit))
1050 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1051 // fold (sdiv X, pow2) -> simple ops after legalize
1052 if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
1053 (isPowerOf2_64(N1C->getSignExtended()) ||
1054 isPowerOf2_64(-N1C->getSignExtended()))) {
1055 // If dividing by powers of two is cheap, then don't perform the following
1057 if (TLI.isPow2DivCheap())
1059 int64_t pow2 = N1C->getSignExtended();
1060 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1061 unsigned lg2 = Log2_64(abs2);
1062 // Splat the sign bit into the register
1063 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1064 DAG.getConstant(MVT::getSizeInBits(VT)-1,
1065 TLI.getShiftAmountTy()));
1066 AddToWorkList(SGN.Val);
1067 // Add (N0 < 0) ? abs2 - 1 : 0;
1068 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1069 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
1070 TLI.getShiftAmountTy()));
1071 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1072 AddToWorkList(SRL.Val);
1073 AddToWorkList(ADD.Val); // Divide by pow2
1074 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1075 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1076 // If we're dividing by a positive value, we're done. Otherwise, we must
1077 // negate the result.
1080 AddToWorkList(SRA.Val);
1081 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1083 // if integer divide is expensive and we satisfy the requirements, emit an
1084 // alternate sequence.
1085 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1086 !TLI.isIntDivCheap()) {
1087 SDOperand Op = BuildSDIV(N);
1088 if (Op.Val) return Op;
1093 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1094 SDOperand N0 = N->getOperand(0);
1095 SDOperand N1 = N->getOperand(1);
1096 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1097 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1098 MVT::ValueType VT = N->getValueType(0);
1100 // fold (udiv c1, c2) -> c1/c2
1101 if (N0C && N1C && !N1C->isNullValue())
1102 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1103 // fold (udiv x, (1 << c)) -> x >>u c
1104 if (N1C && isPowerOf2_64(N1C->getValue()))
1105 return DAG.getNode(ISD::SRL, VT, N0,
1106 DAG.getConstant(Log2_64(N1C->getValue()),
1107 TLI.getShiftAmountTy()));
1108 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1109 if (N1.getOpcode() == ISD::SHL) {
1110 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1111 if (isPowerOf2_64(SHC->getValue())) {
1112 MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
1113 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1114 DAG.getConstant(Log2_64(SHC->getValue()),
1116 AddToWorkList(Add.Val);
1117 return DAG.getNode(ISD::SRL, VT, N0, Add);
1121 // fold (udiv x, c) -> alternate
1122 if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
1123 SDOperand Op = BuildUDIV(N);
1124 if (Op.Val) return Op;
1129 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1130 SDOperand N0 = N->getOperand(0);
1131 SDOperand N1 = N->getOperand(1);
1132 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1133 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1134 MVT::ValueType VT = N->getValueType(0);
1136 // fold (srem c1, c2) -> c1%c2
1137 if (N0C && N1C && !N1C->isNullValue())
1138 return DAG.getNode(ISD::SREM, VT, N0, N1);
1139 // If we know the sign bits of both operands are zero, strength reduce to a
1140 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1141 uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1142 if (TLI.MaskedValueIsZero(N1, SignBit) &&
1143 TLI.MaskedValueIsZero(N0, SignBit))
1144 return DAG.getNode(ISD::UREM, VT, N0, N1);
1146 // Unconditionally lower X%C -> X-X/C*C. This allows the X/C logic to hack on
1147 // the remainder operation.
1148 if (N1C && !N1C->isNullValue()) {
1149 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1150 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
1151 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1152 AddToWorkList(Div.Val);
1153 AddToWorkList(Mul.Val);
1160 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1161 SDOperand N0 = N->getOperand(0);
1162 SDOperand N1 = N->getOperand(1);
1163 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1164 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1165 MVT::ValueType VT = N->getValueType(0);
1167 // fold (urem c1, c2) -> c1%c2
1168 if (N0C && N1C && !N1C->isNullValue())
1169 return DAG.getNode(ISD::UREM, VT, N0, N1);
1170 // fold (urem x, pow2) -> (and x, pow2-1)
1171 if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
1172 return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
1173 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1174 if (N1.getOpcode() == ISD::SHL) {
1175 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1176 if (isPowerOf2_64(SHC->getValue())) {
1177 SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
1178 AddToWorkList(Add.Val);
1179 return DAG.getNode(ISD::AND, VT, N0, Add);
1184 // Unconditionally lower X%C -> X-X/C*C. This allows the X/C logic to hack on
1185 // the remainder operation.
1186 if (N1C && !N1C->isNullValue()) {
1187 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1188 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
1189 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1190 AddToWorkList(Div.Val);
1191 AddToWorkList(Mul.Val);
1198 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1199 SDOperand N0 = N->getOperand(0);
1200 SDOperand N1 = N->getOperand(1);
1201 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1203 // fold (mulhs x, 0) -> 0
1204 if (N1C && N1C->isNullValue())
1206 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1207 if (N1C && N1C->getValue() == 1)
1208 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1209 DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1210 TLI.getShiftAmountTy()));
1214 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1215 SDOperand N0 = N->getOperand(0);
1216 SDOperand N1 = N->getOperand(1);
1217 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1219 // fold (mulhu x, 0) -> 0
1220 if (N1C && N1C->isNullValue())
1222 // fold (mulhu x, 1) -> 0
1223 if (N1C && N1C->getValue() == 1)
1224 return DAG.getConstant(0, N0.getValueType());
1228 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1229 /// two operands of the same opcode, try to simplify it.
1230 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1231 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1232 MVT::ValueType VT = N0.getValueType();
1233 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1235 // For each of OP in AND/OR/XOR:
1236 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1237 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1238 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1239 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1240 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1241 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1242 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1243 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1244 N0.getOperand(0).getValueType(),
1245 N0.getOperand(0), N1.getOperand(0));
1246 AddToWorkList(ORNode.Val);
1247 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1250 // For each of OP in SHL/SRL/SRA/AND...
1251 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1252 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1253 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1254 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1255 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1256 N0.getOperand(1) == N1.getOperand(1)) {
1257 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1258 N0.getOperand(0).getValueType(),
1259 N0.getOperand(0), N1.getOperand(0));
1260 AddToWorkList(ORNode.Val);
1261 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1267 SDOperand DAGCombiner::visitAND(SDNode *N) {
1268 SDOperand N0 = N->getOperand(0);
1269 SDOperand N1 = N->getOperand(1);
1270 SDOperand LL, LR, RL, RR, CC0, CC1;
1271 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1272 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1273 MVT::ValueType VT = N1.getValueType();
1275 // fold (and c1, c2) -> c1&c2
1277 return DAG.getNode(ISD::AND, VT, N0, N1);
1278 // canonicalize constant to RHS
1280 return DAG.getNode(ISD::AND, VT, N1, N0);
1281 // fold (and x, -1) -> x
1282 if (N1C && N1C->isAllOnesValue())
1284 // if (and x, c) is known to be zero, return 0
1285 if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1286 return DAG.getConstant(0, VT);
1288 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1291 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1292 if (N1C && N0.getOpcode() == ISD::OR)
1293 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1294 if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
1296 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1297 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1298 unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
1299 if (TLI.MaskedValueIsZero(N0.getOperand(0),
1300 ~N1C->getValue() & InMask)) {
1301 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1304 // Replace uses of the AND with uses of the Zero extend node.
1307 // We actually want to replace all uses of the any_extend with the
1308 // zero_extend, to avoid duplicating things. This will later cause this
1309 // AND to be folded.
1310 CombineTo(N0.Val, Zext);
1311 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1314 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1315 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1316 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1317 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1319 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1320 MVT::isInteger(LL.getValueType())) {
1321 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1322 if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
1323 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1324 AddToWorkList(ORNode.Val);
1325 return DAG.getSetCC(VT, ORNode, LR, Op1);
1327 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1328 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1329 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1330 AddToWorkList(ANDNode.Val);
1331 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1333 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1334 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1335 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1336 AddToWorkList(ORNode.Val);
1337 return DAG.getSetCC(VT, ORNode, LR, Op1);
1340 // canonicalize equivalent to ll == rl
1341 if (LL == RR && LR == RL) {
1342 Op1 = ISD::getSetCCSwappedOperands(Op1);
1345 if (LL == RL && LR == RR) {
1346 bool isInteger = MVT::isInteger(LL.getValueType());
1347 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1348 if (Result != ISD::SETCC_INVALID)
1349 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1353 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1354 if (N0.getOpcode() == N1.getOpcode()) {
1355 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1356 if (Tmp.Val) return Tmp;
1359 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1360 // fold (and (sra)) -> (and (srl)) when possible.
1361 if (!MVT::isVector(VT) &&
1362 SimplifyDemandedBits(SDOperand(N, 0)))
1363 return SDOperand(N, 0);
1364 // fold (zext_inreg (extload x)) -> (zextload x)
1365 if (ISD::isEXTLoad(N0.Val)) {
1366 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1367 MVT::ValueType EVT = LN0->getLoadedVT();
1368 // If we zero all the possible extended bits, then we can turn this into
1369 // a zextload if we are running before legalize or the operation is legal.
1370 if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1371 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1372 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1373 LN0->getBasePtr(), LN0->getSrcValue(),
1374 LN0->getSrcValueOffset(), EVT);
1376 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1377 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1380 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1381 if (ISD::isSEXTLoad(N0.Val) && N0.hasOneUse()) {
1382 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1383 MVT::ValueType EVT = LN0->getLoadedVT();
1384 // If we zero all the possible extended bits, then we can turn this into
1385 // a zextload if we are running before legalize or the operation is legal.
1386 if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1387 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1388 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1389 LN0->getBasePtr(), LN0->getSrcValue(),
1390 LN0->getSrcValueOffset(), EVT);
1392 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1393 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1397 // fold (and (load x), 255) -> (zextload x, i8)
1398 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1399 if (N1C && N0.getOpcode() == ISD::LOAD) {
1400 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1401 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1403 MVT::ValueType EVT, LoadedVT;
1404 if (N1C->getValue() == 255)
1406 else if (N1C->getValue() == 65535)
1408 else if (N1C->getValue() == ~0U)
1413 LoadedVT = LN0->getLoadedVT();
1414 if (EVT != MVT::Other && LoadedVT > EVT &&
1415 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1416 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1417 // For big endian targets, we need to add an offset to the pointer to
1418 // load the correct bytes. For little endian systems, we merely need to
1419 // read fewer bytes from the same pointer.
1421 (MVT::getSizeInBits(LoadedVT) - MVT::getSizeInBits(EVT)) / 8;
1422 SDOperand NewPtr = LN0->getBasePtr();
1423 if (!TLI.isLittleEndian())
1424 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1425 DAG.getConstant(PtrOff, PtrType));
1426 AddToWorkList(NewPtr.Val);
1428 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1429 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT);
1431 CombineTo(N0.Val, Load, Load.getValue(1));
1432 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1440 SDOperand DAGCombiner::visitOR(SDNode *N) {
1441 SDOperand N0 = N->getOperand(0);
1442 SDOperand N1 = N->getOperand(1);
1443 SDOperand LL, LR, RL, RR, CC0, CC1;
1444 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1445 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1446 MVT::ValueType VT = N1.getValueType();
1447 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1449 // fold (or c1, c2) -> c1|c2
1451 return DAG.getNode(ISD::OR, VT, N0, N1);
1452 // canonicalize constant to RHS
1454 return DAG.getNode(ISD::OR, VT, N1, N0);
1455 // fold (or x, 0) -> x
1456 if (N1C && N1C->isNullValue())
1458 // fold (or x, -1) -> -1
1459 if (N1C && N1C->isAllOnesValue())
1461 // fold (or x, c) -> c iff (x & ~c) == 0
1463 TLI.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
1466 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1469 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1470 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1471 isa<ConstantSDNode>(N0.getOperand(1))) {
1472 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1473 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1475 DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1477 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1478 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1479 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1480 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1482 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1483 MVT::isInteger(LL.getValueType())) {
1484 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1485 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1486 if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1487 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1488 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1489 AddToWorkList(ORNode.Val);
1490 return DAG.getSetCC(VT, ORNode, LR, Op1);
1492 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1493 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1494 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1495 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1496 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1497 AddToWorkList(ANDNode.Val);
1498 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1501 // canonicalize equivalent to ll == rl
1502 if (LL == RR && LR == RL) {
1503 Op1 = ISD::getSetCCSwappedOperands(Op1);
1506 if (LL == RL && LR == RR) {
1507 bool isInteger = MVT::isInteger(LL.getValueType());
1508 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1509 if (Result != ISD::SETCC_INVALID)
1510 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1514 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1515 if (N0.getOpcode() == N1.getOpcode()) {
1516 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1517 if (Tmp.Val) return Tmp;
1520 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1521 if (N0.getOpcode() == ISD::AND &&
1522 N1.getOpcode() == ISD::AND &&
1523 N0.getOperand(1).getOpcode() == ISD::Constant &&
1524 N1.getOperand(1).getOpcode() == ISD::Constant &&
1525 // Don't increase # computations.
1526 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1527 // We can only do this xform if we know that bits from X that are set in C2
1528 // but not in C1 are already zero. Likewise for Y.
1529 uint64_t LHSMask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1530 uint64_t RHSMask = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
1532 if (TLI.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1533 TLI.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1534 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1535 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1540 // See if this is some rotate idiom.
1541 if (SDNode *Rot = MatchRotate(N0, N1))
1542 return SDOperand(Rot, 0);
1548 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1549 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1550 if (Op.getOpcode() == ISD::AND) {
1551 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1552 Mask = Op.getOperand(1);
1553 Op = Op.getOperand(0);
1559 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1567 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1568 // idioms for rotate, and if the target supports rotation instructions, generate
1570 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1571 // Must be a legal type. Expanded an promoted things won't work with rotates.
1572 MVT::ValueType VT = LHS.getValueType();
1573 if (!TLI.isTypeLegal(VT)) return 0;
1575 // The target must have at least one rotate flavor.
1576 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1577 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1578 if (!HasROTL && !HasROTR) return 0;
1580 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1581 SDOperand LHSShift; // The shift.
1582 SDOperand LHSMask; // AND value if any.
1583 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1584 return 0; // Not part of a rotate.
1586 SDOperand RHSShift; // The shift.
1587 SDOperand RHSMask; // AND value if any.
1588 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1589 return 0; // Not part of a rotate.
1591 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1592 return 0; // Not shifting the same value.
1594 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1595 return 0; // Shifts must disagree.
1597 // Canonicalize shl to left side in a shl/srl pair.
1598 if (RHSShift.getOpcode() == ISD::SHL) {
1599 std::swap(LHS, RHS);
1600 std::swap(LHSShift, RHSShift);
1601 std::swap(LHSMask , RHSMask );
1604 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1606 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1607 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1608 if (LHSShift.getOperand(1).getOpcode() == ISD::Constant &&
1609 RHSShift.getOperand(1).getOpcode() == ISD::Constant) {
1610 uint64_t LShVal = cast<ConstantSDNode>(LHSShift.getOperand(1))->getValue();
1611 uint64_t RShVal = cast<ConstantSDNode>(RHSShift.getOperand(1))->getValue();
1612 if ((LShVal + RShVal) != OpSizeInBits)
1617 Rot = DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1618 LHSShift.getOperand(1));
1620 Rot = DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1621 RHSShift.getOperand(1));
1623 // If there is an AND of either shifted operand, apply it to the result.
1624 if (LHSMask.Val || RHSMask.Val) {
1625 uint64_t Mask = MVT::getIntVTBitMask(VT);
1628 uint64_t RHSBits = (1ULL << LShVal)-1;
1629 Mask &= cast<ConstantSDNode>(LHSMask)->getValue() | RHSBits;
1632 uint64_t LHSBits = ~((1ULL << (OpSizeInBits-RShVal))-1);
1633 Mask &= cast<ConstantSDNode>(RHSMask)->getValue() | LHSBits;
1636 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
1642 // If there is a mask here, and we have a variable shift, we can't be sure
1643 // that we're masking out the right stuff.
1644 if (LHSMask.Val || RHSMask.Val)
1647 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
1648 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
1649 if (RHSShift.getOperand(1).getOpcode() == ISD::SUB &&
1650 LHSShift.getOperand(1) == RHSShift.getOperand(1).getOperand(1)) {
1651 if (ConstantSDNode *SUBC =
1652 dyn_cast<ConstantSDNode>(RHSShift.getOperand(1).getOperand(0))) {
1653 if (SUBC->getValue() == OpSizeInBits)
1655 return DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1656 LHSShift.getOperand(1)).Val;
1658 return DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1659 LHSShift.getOperand(1)).Val;
1663 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
1664 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
1665 if (LHSShift.getOperand(1).getOpcode() == ISD::SUB &&
1666 RHSShift.getOperand(1) == LHSShift.getOperand(1).getOperand(1)) {
1667 if (ConstantSDNode *SUBC =
1668 dyn_cast<ConstantSDNode>(LHSShift.getOperand(1).getOperand(0))) {
1669 if (SUBC->getValue() == OpSizeInBits)
1671 return DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1672 LHSShift.getOperand(1)).Val;
1674 return DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1675 RHSShift.getOperand(1)).Val;
1683 SDOperand DAGCombiner::visitXOR(SDNode *N) {
1684 SDOperand N0 = N->getOperand(0);
1685 SDOperand N1 = N->getOperand(1);
1686 SDOperand LHS, RHS, CC;
1687 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1688 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1689 MVT::ValueType VT = N0.getValueType();
1691 // fold (xor c1, c2) -> c1^c2
1693 return DAG.getNode(ISD::XOR, VT, N0, N1);
1694 // canonicalize constant to RHS
1696 return DAG.getNode(ISD::XOR, VT, N1, N0);
1697 // fold (xor x, 0) -> x
1698 if (N1C && N1C->isNullValue())
1701 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
1704 // fold !(x cc y) -> (x !cc y)
1705 if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
1706 bool isInt = MVT::isInteger(LHS.getValueType());
1707 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
1709 if (N0.getOpcode() == ISD::SETCC)
1710 return DAG.getSetCC(VT, LHS, RHS, NotCC);
1711 if (N0.getOpcode() == ISD::SELECT_CC)
1712 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
1713 assert(0 && "Unhandled SetCC Equivalent!");
1716 // fold !(x or y) -> (!x and !y) iff x or y are setcc
1717 if (N1C && N1C->getValue() == 1 &&
1718 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1719 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1720 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
1721 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1722 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
1723 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
1724 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1725 return DAG.getNode(NewOpcode, VT, LHS, RHS);
1728 // fold !(x or y) -> (!x and !y) iff x or y are constants
1729 if (N1C && N1C->isAllOnesValue() &&
1730 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1731 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1732 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
1733 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1734 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
1735 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
1736 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1737 return DAG.getNode(NewOpcode, VT, LHS, RHS);
1740 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
1741 if (N1C && N0.getOpcode() == ISD::XOR) {
1742 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
1743 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1745 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
1746 DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
1748 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
1749 DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
1751 // fold (xor x, x) -> 0
1753 if (!MVT::isVector(VT)) {
1754 return DAG.getConstant(0, VT);
1755 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1756 // Produce a vector of zeros.
1757 SDOperand El = DAG.getConstant(0, MVT::getVectorBaseType(VT));
1758 std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
1759 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1763 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
1764 if (N0.getOpcode() == N1.getOpcode()) {
1765 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1766 if (Tmp.Val) return Tmp;
1769 // Simplify the expression using non-local knowledge.
1770 if (!MVT::isVector(VT) &&
1771 SimplifyDemandedBits(SDOperand(N, 0)))
1772 return SDOperand(N, 0);
1777 SDOperand DAGCombiner::visitSHL(SDNode *N) {
1778 SDOperand N0 = N->getOperand(0);
1779 SDOperand N1 = N->getOperand(1);
1780 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1781 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1782 MVT::ValueType VT = N0.getValueType();
1783 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1785 // fold (shl c1, c2) -> c1<<c2
1787 return DAG.getNode(ISD::SHL, VT, N0, N1);
1788 // fold (shl 0, x) -> 0
1789 if (N0C && N0C->isNullValue())
1791 // fold (shl x, c >= size(x)) -> undef
1792 if (N1C && N1C->getValue() >= OpSizeInBits)
1793 return DAG.getNode(ISD::UNDEF, VT);
1794 // fold (shl x, 0) -> x
1795 if (N1C && N1C->isNullValue())
1797 // if (shl x, c) is known to be zero, return 0
1798 if (TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1799 return DAG.getConstant(0, VT);
1800 if (SimplifyDemandedBits(SDOperand(N, 0)))
1801 return SDOperand(N, 0);
1802 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
1803 if (N1C && N0.getOpcode() == ISD::SHL &&
1804 N0.getOperand(1).getOpcode() == ISD::Constant) {
1805 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1806 uint64_t c2 = N1C->getValue();
1807 if (c1 + c2 > OpSizeInBits)
1808 return DAG.getConstant(0, VT);
1809 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
1810 DAG.getConstant(c1 + c2, N1.getValueType()));
1812 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
1813 // (srl (and x, -1 << c1), c1-c2)
1814 if (N1C && N0.getOpcode() == ISD::SRL &&
1815 N0.getOperand(1).getOpcode() == ISD::Constant) {
1816 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1817 uint64_t c2 = N1C->getValue();
1818 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1819 DAG.getConstant(~0ULL << c1, VT));
1821 return DAG.getNode(ISD::SHL, VT, Mask,
1822 DAG.getConstant(c2-c1, N1.getValueType()));
1824 return DAG.getNode(ISD::SRL, VT, Mask,
1825 DAG.getConstant(c1-c2, N1.getValueType()));
1827 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
1828 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
1829 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1830 DAG.getConstant(~0ULL << N1C->getValue(), VT));
1831 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1<<c2)
1832 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1833 isa<ConstantSDNode>(N0.getOperand(1))) {
1834 return DAG.getNode(ISD::ADD, VT,
1835 DAG.getNode(ISD::SHL, VT, N0.getOperand(0), N1),
1836 DAG.getNode(ISD::SHL, VT, N0.getOperand(1), N1));
1841 SDOperand DAGCombiner::visitSRA(SDNode *N) {
1842 SDOperand N0 = N->getOperand(0);
1843 SDOperand N1 = N->getOperand(1);
1844 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1845 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1846 MVT::ValueType VT = N0.getValueType();
1848 // fold (sra c1, c2) -> c1>>c2
1850 return DAG.getNode(ISD::SRA, VT, N0, N1);
1851 // fold (sra 0, x) -> 0
1852 if (N0C && N0C->isNullValue())
1854 // fold (sra -1, x) -> -1
1855 if (N0C && N0C->isAllOnesValue())
1857 // fold (sra x, c >= size(x)) -> undef
1858 if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
1859 return DAG.getNode(ISD::UNDEF, VT);
1860 // fold (sra x, 0) -> x
1861 if (N1C && N1C->isNullValue())
1863 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
1865 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
1866 unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
1869 default: EVT = MVT::Other; break;
1870 case 1: EVT = MVT::i1; break;
1871 case 8: EVT = MVT::i8; break;
1872 case 16: EVT = MVT::i16; break;
1873 case 32: EVT = MVT::i32; break;
1875 if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
1876 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
1877 DAG.getValueType(EVT));
1880 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
1881 if (N1C && N0.getOpcode() == ISD::SRA) {
1882 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1883 unsigned Sum = N1C->getValue() + C1->getValue();
1884 if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
1885 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
1886 DAG.getConstant(Sum, N1C->getValueType(0)));
1890 // Simplify, based on bits shifted out of the LHS.
1891 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
1892 return SDOperand(N, 0);
1895 // If the sign bit is known to be zero, switch this to a SRL.
1896 if (TLI.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
1897 return DAG.getNode(ISD::SRL, VT, N0, N1);
1901 SDOperand DAGCombiner::visitSRL(SDNode *N) {
1902 SDOperand N0 = N->getOperand(0);
1903 SDOperand N1 = N->getOperand(1);
1904 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1905 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1906 MVT::ValueType VT = N0.getValueType();
1907 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1909 // fold (srl c1, c2) -> c1 >>u c2
1911 return DAG.getNode(ISD::SRL, VT, N0, N1);
1912 // fold (srl 0, x) -> 0
1913 if (N0C && N0C->isNullValue())
1915 // fold (srl x, c >= size(x)) -> undef
1916 if (N1C && N1C->getValue() >= OpSizeInBits)
1917 return DAG.getNode(ISD::UNDEF, VT);
1918 // fold (srl x, 0) -> x
1919 if (N1C && N1C->isNullValue())
1921 // if (srl x, c) is known to be zero, return 0
1922 if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
1923 return DAG.getConstant(0, VT);
1924 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
1925 if (N1C && N0.getOpcode() == ISD::SRL &&
1926 N0.getOperand(1).getOpcode() == ISD::Constant) {
1927 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1928 uint64_t c2 = N1C->getValue();
1929 if (c1 + c2 > OpSizeInBits)
1930 return DAG.getConstant(0, VT);
1931 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
1932 DAG.getConstant(c1 + c2, N1.getValueType()));
1935 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
1936 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1937 // Shifting in all undef bits?
1938 MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
1939 if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
1940 return DAG.getNode(ISD::UNDEF, VT);
1942 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
1943 AddToWorkList(SmallShift.Val);
1944 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
1947 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
1948 // bit, which is unmodified by sra.
1949 if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
1950 if (N0.getOpcode() == ISD::SRA)
1951 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
1954 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
1955 if (N1C && N0.getOpcode() == ISD::CTLZ &&
1956 N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
1957 uint64_t KnownZero, KnownOne, Mask = MVT::getIntVTBitMask(VT);
1958 TLI.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
1960 // If any of the input bits are KnownOne, then the input couldn't be all
1961 // zeros, thus the result of the srl will always be zero.
1962 if (KnownOne) return DAG.getConstant(0, VT);
1964 // If all of the bits input the to ctlz node are known to be zero, then
1965 // the result of the ctlz is "32" and the result of the shift is one.
1966 uint64_t UnknownBits = ~KnownZero & Mask;
1967 if (UnknownBits == 0) return DAG.getConstant(1, VT);
1969 // Otherwise, check to see if there is exactly one bit input to the ctlz.
1970 if ((UnknownBits & (UnknownBits-1)) == 0) {
1971 // Okay, we know that only that the single bit specified by UnknownBits
1972 // could be set on input to the CTLZ node. If this bit is set, the SRL
1973 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
1974 // to an SRL,XOR pair, which is likely to simplify more.
1975 unsigned ShAmt = CountTrailingZeros_64(UnknownBits);
1976 SDOperand Op = N0.getOperand(0);
1978 Op = DAG.getNode(ISD::SRL, VT, Op,
1979 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
1980 AddToWorkList(Op.Val);
1982 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
1989 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
1990 SDOperand N0 = N->getOperand(0);
1991 MVT::ValueType VT = N->getValueType(0);
1993 // fold (ctlz c1) -> c2
1994 if (isa<ConstantSDNode>(N0))
1995 return DAG.getNode(ISD::CTLZ, VT, N0);
1999 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2000 SDOperand N0 = N->getOperand(0);
2001 MVT::ValueType VT = N->getValueType(0);
2003 // fold (cttz c1) -> c2
2004 if (isa<ConstantSDNode>(N0))
2005 return DAG.getNode(ISD::CTTZ, VT, N0);
2009 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2010 SDOperand N0 = N->getOperand(0);
2011 MVT::ValueType VT = N->getValueType(0);
2013 // fold (ctpop c1) -> c2
2014 if (isa<ConstantSDNode>(N0))
2015 return DAG.getNode(ISD::CTPOP, VT, N0);
2019 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2020 SDOperand N0 = N->getOperand(0);
2021 SDOperand N1 = N->getOperand(1);
2022 SDOperand N2 = N->getOperand(2);
2023 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2024 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2025 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2026 MVT::ValueType VT = N->getValueType(0);
2028 // fold select C, X, X -> X
2031 // fold select true, X, Y -> X
2032 if (N0C && !N0C->isNullValue())
2034 // fold select false, X, Y -> Y
2035 if (N0C && N0C->isNullValue())
2037 // fold select C, 1, X -> C | X
2038 if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
2039 return DAG.getNode(ISD::OR, VT, N0, N2);
2040 // fold select C, 0, X -> ~C & X
2041 // FIXME: this should check for C type == X type, not i1?
2042 if (MVT::i1 == VT && N1C && N1C->isNullValue()) {
2043 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2044 AddToWorkList(XORNode.Val);
2045 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2047 // fold select C, X, 1 -> ~C | X
2048 if (MVT::i1 == VT && N2C && N2C->getValue() == 1) {
2049 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2050 AddToWorkList(XORNode.Val);
2051 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2053 // fold select C, X, 0 -> C & X
2054 // FIXME: this should check for C type == X type, not i1?
2055 if (MVT::i1 == VT && N2C && N2C->isNullValue())
2056 return DAG.getNode(ISD::AND, VT, N0, N1);
2057 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2058 if (MVT::i1 == VT && N0 == N1)
2059 return DAG.getNode(ISD::OR, VT, N0, N2);
2060 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2061 if (MVT::i1 == VT && N0 == N2)
2062 return DAG.getNode(ISD::AND, VT, N0, N1);
2064 // If we can fold this based on the true/false value, do so.
2065 if (SimplifySelectOps(N, N1, N2))
2066 return SDOperand(N, 0); // Don't revisit N.
2068 // fold selects based on a setcc into other things, such as min/max/abs
2069 if (N0.getOpcode() == ISD::SETCC)
2071 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2072 // having to say they don't support SELECT_CC on every type the DAG knows
2073 // about, since there is no way to mark an opcode illegal at all value types
2074 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2075 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2076 N1, N2, N0.getOperand(2));
2078 return SimplifySelect(N0, N1, N2);
2082 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2083 SDOperand N0 = N->getOperand(0);
2084 SDOperand N1 = N->getOperand(1);
2085 SDOperand N2 = N->getOperand(2);
2086 SDOperand N3 = N->getOperand(3);
2087 SDOperand N4 = N->getOperand(4);
2088 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2090 // fold select_cc lhs, rhs, x, x, cc -> x
2094 // Determine if the condition we're dealing with is constant
2095 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
2096 if (SCC.Val) AddToWorkList(SCC.Val);
2098 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2099 if (SCCC->getValue())
2100 return N2; // cond always true -> true val
2102 return N3; // cond always false -> false val
2105 // Fold to a simpler select_cc
2106 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2107 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2108 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2111 // If we can fold this based on the true/false value, do so.
2112 if (SimplifySelectOps(N, N2, N3))
2113 return SDOperand(N, 0); // Don't revisit N.
2115 // fold select_cc into other things, such as min/max/abs
2116 return SimplifySelectCC(N0, N1, N2, N3, CC);
2119 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2120 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2121 cast<CondCodeSDNode>(N->getOperand(2))->get());
2124 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2125 SDOperand N0 = N->getOperand(0);
2126 MVT::ValueType VT = N->getValueType(0);
2128 // fold (sext c1) -> c1
2129 if (isa<ConstantSDNode>(N0))
2130 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2132 // fold (sext (sext x)) -> (sext x)
2133 // fold (sext (aext x)) -> (sext x)
2134 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2135 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2137 // fold (sext (truncate x)) -> (sextinreg x).
2138 if (N0.getOpcode() == ISD::TRUNCATE &&
2139 (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2140 N0.getValueType()))) {
2141 SDOperand Op = N0.getOperand(0);
2142 if (Op.getValueType() < VT) {
2143 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2144 } else if (Op.getValueType() > VT) {
2145 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2147 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2148 DAG.getValueType(N0.getValueType()));
2151 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2152 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2153 (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
2154 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2155 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2156 LN0->getBasePtr(), LN0->getSrcValue(),
2157 LN0->getSrcValueOffset(),
2159 CombineTo(N, ExtLoad);
2160 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2161 ExtLoad.getValue(1));
2162 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2165 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2166 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2167 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) && N0.hasOneUse()) {
2168 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2169 MVT::ValueType EVT = LN0->getLoadedVT();
2170 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2171 LN0->getBasePtr(), LN0->getSrcValue(),
2172 LN0->getSrcValueOffset(), EVT);
2173 CombineTo(N, ExtLoad);
2174 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2175 ExtLoad.getValue(1));
2176 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2182 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2183 SDOperand N0 = N->getOperand(0);
2184 MVT::ValueType VT = N->getValueType(0);
2186 // fold (zext c1) -> c1
2187 if (isa<ConstantSDNode>(N0))
2188 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2189 // fold (zext (zext x)) -> (zext x)
2190 // fold (zext (aext x)) -> (zext x)
2191 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2192 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2194 // fold (zext (truncate x)) -> (and x, mask)
2195 if (N0.getOpcode() == ISD::TRUNCATE &&
2196 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2197 SDOperand Op = N0.getOperand(0);
2198 if (Op.getValueType() < VT) {
2199 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2200 } else if (Op.getValueType() > VT) {
2201 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2203 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2206 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2207 if (N0.getOpcode() == ISD::AND &&
2208 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2209 N0.getOperand(1).getOpcode() == ISD::Constant) {
2210 SDOperand X = N0.getOperand(0).getOperand(0);
2211 if (X.getValueType() < VT) {
2212 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2213 } else if (X.getValueType() > VT) {
2214 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2216 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2217 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2220 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2221 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2222 (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2223 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2224 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2225 LN0->getBasePtr(), LN0->getSrcValue(),
2226 LN0->getSrcValueOffset(),
2228 CombineTo(N, ExtLoad);
2229 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2230 ExtLoad.getValue(1));
2231 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2234 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2235 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2236 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) && N0.hasOneUse()) {
2237 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2238 MVT::ValueType EVT = LN0->getLoadedVT();
2239 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2240 LN0->getBasePtr(), LN0->getSrcValue(),
2241 LN0->getSrcValueOffset(), EVT);
2242 CombineTo(N, ExtLoad);
2243 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2244 ExtLoad.getValue(1));
2245 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2250 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
2251 SDOperand N0 = N->getOperand(0);
2252 MVT::ValueType VT = N->getValueType(0);
2254 // fold (aext c1) -> c1
2255 if (isa<ConstantSDNode>(N0))
2256 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
2257 // fold (aext (aext x)) -> (aext x)
2258 // fold (aext (zext x)) -> (zext x)
2259 // fold (aext (sext x)) -> (sext x)
2260 if (N0.getOpcode() == ISD::ANY_EXTEND ||
2261 N0.getOpcode() == ISD::ZERO_EXTEND ||
2262 N0.getOpcode() == ISD::SIGN_EXTEND)
2263 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2265 // fold (aext (truncate x))
2266 if (N0.getOpcode() == ISD::TRUNCATE) {
2267 SDOperand TruncOp = N0.getOperand(0);
2268 if (TruncOp.getValueType() == VT)
2269 return TruncOp; // x iff x size == zext size.
2270 if (TruncOp.getValueType() > VT)
2271 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
2272 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
2275 // fold (aext (and (trunc x), cst)) -> (and x, cst).
2276 if (N0.getOpcode() == ISD::AND &&
2277 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2278 N0.getOperand(1).getOpcode() == ISD::Constant) {
2279 SDOperand X = N0.getOperand(0).getOperand(0);
2280 if (X.getValueType() < VT) {
2281 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2282 } else if (X.getValueType() > VT) {
2283 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2285 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2286 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2289 // fold (aext (load x)) -> (aext (truncate (extload x)))
2290 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2291 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2292 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2293 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2294 LN0->getBasePtr(), LN0->getSrcValue(),
2295 LN0->getSrcValueOffset(),
2297 CombineTo(N, ExtLoad);
2298 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2299 ExtLoad.getValue(1));
2300 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2303 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
2304 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
2305 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
2306 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.Val) &&
2308 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2309 MVT::ValueType EVT = LN0->getLoadedVT();
2310 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
2311 LN0->getChain(), LN0->getBasePtr(),
2313 LN0->getSrcValueOffset(), EVT);
2314 CombineTo(N, ExtLoad);
2315 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2316 ExtLoad.getValue(1));
2317 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2323 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
2324 SDOperand N0 = N->getOperand(0);
2325 SDOperand N1 = N->getOperand(1);
2326 MVT::ValueType VT = N->getValueType(0);
2327 MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
2328 unsigned EVTBits = MVT::getSizeInBits(EVT);
2330 // fold (sext_in_reg c1) -> c1
2331 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
2332 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
2334 // If the input is already sign extended, just drop the extension.
2335 if (TLI.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
2338 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
2339 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2340 EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
2341 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
2344 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is zero
2345 if (TLI.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
2346 return DAG.getZeroExtendInReg(N0, EVT);
2348 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
2349 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
2350 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
2351 if (N0.getOpcode() == ISD::SRL) {
2352 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2353 if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
2354 // We can turn this into an SRA iff the input to the SRL is already sign
2356 unsigned InSignBits = TLI.ComputeNumSignBits(N0.getOperand(0));
2357 if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
2358 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
2362 // fold (sext_inreg (extload x)) -> (sextload x)
2363 if (ISD::isEXTLoad(N0.Val) &&
2364 EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2365 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2366 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2367 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2368 LN0->getBasePtr(), LN0->getSrcValue(),
2369 LN0->getSrcValueOffset(), EVT);
2370 CombineTo(N, ExtLoad);
2371 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2372 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2374 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
2375 if (ISD::isZEXTLoad(N0.Val) && N0.hasOneUse() &&
2376 EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2377 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2378 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2379 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2380 LN0->getBasePtr(), LN0->getSrcValue(),
2381 LN0->getSrcValueOffset(), EVT);
2382 CombineTo(N, ExtLoad);
2383 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2384 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2389 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
2390 SDOperand N0 = N->getOperand(0);
2391 MVT::ValueType VT = N->getValueType(0);
2394 if (N0.getValueType() == N->getValueType(0))
2396 // fold (truncate c1) -> c1
2397 if (isa<ConstantSDNode>(N0))
2398 return DAG.getNode(ISD::TRUNCATE, VT, N0);
2399 // fold (truncate (truncate x)) -> (truncate x)
2400 if (N0.getOpcode() == ISD::TRUNCATE)
2401 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
2402 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
2403 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
2404 N0.getOpcode() == ISD::ANY_EXTEND) {
2405 if (N0.getValueType() < VT)
2406 // if the source is smaller than the dest, we still need an extend
2407 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2408 else if (N0.getValueType() > VT)
2409 // if the source is larger than the dest, than we just need the truncate
2410 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
2412 // if the source and dest are the same type, we can drop both the extend
2414 return N0.getOperand(0);
2416 // fold (truncate (load x)) -> (smaller load x)
2417 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse()) {
2418 assert(MVT::getSizeInBits(N0.getValueType()) > MVT::getSizeInBits(VT) &&
2419 "Cannot truncate to larger type!");
2420 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2421 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
2422 // For big endian targets, we need to add an offset to the pointer to load
2423 // the correct bytes. For little endian systems, we merely need to read
2424 // fewer bytes from the same pointer.
2426 (MVT::getSizeInBits(N0.getValueType()) - MVT::getSizeInBits(VT)) / 8;
2427 SDOperand NewPtr = TLI.isLittleEndian() ? LN0->getBasePtr() :
2428 DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
2429 DAG.getConstant(PtrOff, PtrType));
2430 AddToWorkList(NewPtr.Val);
2431 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), NewPtr,
2432 LN0->getSrcValue(), LN0->getSrcValueOffset());
2434 CombineTo(N0.Val, Load, Load.getValue(1));
2435 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2440 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
2441 SDOperand N0 = N->getOperand(0);
2442 MVT::ValueType VT = N->getValueType(0);
2444 // If the input is a constant, let getNode() fold it.
2445 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
2446 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
2447 if (Res.Val != N) return Res;
2450 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
2451 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
2453 // fold (conv (load x)) -> (load (conv*)x)
2454 // FIXME: These xforms need to know that the resultant load doesn't need a
2455 // higher alignment than the original!
2456 if (0 && ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse()) {
2457 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2458 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
2459 LN0->getSrcValue(), LN0->getSrcValueOffset());
2461 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
2469 SDOperand DAGCombiner::visitVBIT_CONVERT(SDNode *N) {
2470 SDOperand N0 = N->getOperand(0);
2471 MVT::ValueType VT = N->getValueType(0);
2473 // If the input is a VBUILD_VECTOR with all constant elements, fold this now.
2474 // First check to see if this is all constant.
2475 if (N0.getOpcode() == ISD::VBUILD_VECTOR && N0.Val->hasOneUse() &&
2476 VT == MVT::Vector) {
2477 bool isSimple = true;
2478 for (unsigned i = 0, e = N0.getNumOperands()-2; i != e; ++i)
2479 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
2480 N0.getOperand(i).getOpcode() != ISD::Constant &&
2481 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
2486 MVT::ValueType DestEltVT = cast<VTSDNode>(N->getOperand(2))->getVT();
2487 if (isSimple && !MVT::isVector(DestEltVT)) {
2488 return ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(N0.Val, DestEltVT);
2495 /// ConstantFoldVBIT_CONVERTofVBUILD_VECTOR - We know that BV is a vbuild_vector
2496 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
2497 /// destination element value type.
2498 SDOperand DAGCombiner::
2499 ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
2500 MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
2502 // If this is already the right type, we're done.
2503 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
2505 unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
2506 unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
2508 // If this is a conversion of N elements of one type to N elements of another
2509 // type, convert each element. This handles FP<->INT cases.
2510 if (SrcBitSize == DstBitSize) {
2511 SmallVector<SDOperand, 8> Ops;
2512 for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) {
2513 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
2514 AddToWorkList(Ops.back().Val);
2516 Ops.push_back(*(BV->op_end()-2)); // Add num elements.
2517 Ops.push_back(DAG.getValueType(DstEltVT));
2518 return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2521 // Otherwise, we're growing or shrinking the elements. To avoid having to
2522 // handle annoying details of growing/shrinking FP values, we convert them to
2524 if (MVT::isFloatingPoint(SrcEltVT)) {
2525 // Convert the input float vector to a int vector where the elements are the
2527 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
2528 MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2529 BV = ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(BV, IntVT).Val;
2533 // Now we know the input is an integer vector. If the output is a FP type,
2534 // convert to integer first, then to FP of the right size.
2535 if (MVT::isFloatingPoint(DstEltVT)) {
2536 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
2537 MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2538 SDNode *Tmp = ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(BV, TmpVT).Val;
2540 // Next, convert to FP elements of the same size.
2541 return ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(Tmp, DstEltVT);
2544 // Okay, we know the src/dst types are both integers of differing types.
2545 // Handling growing first.
2546 assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
2547 if (SrcBitSize < DstBitSize) {
2548 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
2550 SmallVector<SDOperand, 8> Ops;
2551 for (unsigned i = 0, e = BV->getNumOperands()-2; i != e;
2552 i += NumInputsPerOutput) {
2553 bool isLE = TLI.isLittleEndian();
2554 uint64_t NewBits = 0;
2555 bool EltIsUndef = true;
2556 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
2557 // Shift the previously computed bits over.
2558 NewBits <<= SrcBitSize;
2559 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
2560 if (Op.getOpcode() == ISD::UNDEF) continue;
2563 NewBits |= cast<ConstantSDNode>(Op)->getValue();
2567 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2569 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
2572 Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements.
2573 Ops.push_back(DAG.getValueType(DstEltVT)); // Add element size.
2574 return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2577 // Finally, this must be the case where we are shrinking elements: each input
2578 // turns into multiple outputs.
2579 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
2580 SmallVector<SDOperand, 8> Ops;
2581 for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) {
2582 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
2583 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
2584 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2587 uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
2589 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
2590 unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
2591 OpVal >>= DstBitSize;
2592 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
2595 // For big endian targets, swap the order of the pieces of each element.
2596 if (!TLI.isLittleEndian())
2597 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
2599 Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements.
2600 Ops.push_back(DAG.getValueType(DstEltVT)); // Add element size.
2601 return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2606 SDOperand DAGCombiner::visitFADD(SDNode *N) {
2607 SDOperand N0 = N->getOperand(0);
2608 SDOperand N1 = N->getOperand(1);
2609 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2610 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2611 MVT::ValueType VT = N->getValueType(0);
2613 // fold (fadd c1, c2) -> c1+c2
2615 return DAG.getNode(ISD::FADD, VT, N0, N1);
2616 // canonicalize constant to RHS
2617 if (N0CFP && !N1CFP)
2618 return DAG.getNode(ISD::FADD, VT, N1, N0);
2619 // fold (A + (-B)) -> A-B
2620 if (N1.getOpcode() == ISD::FNEG)
2621 return DAG.getNode(ISD::FSUB, VT, N0, N1.getOperand(0));
2622 // fold ((-A) + B) -> B-A
2623 if (N0.getOpcode() == ISD::FNEG)
2624 return DAG.getNode(ISD::FSUB, VT, N1, N0.getOperand(0));
2628 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
2629 SDOperand N0 = N->getOperand(0);
2630 SDOperand N1 = N->getOperand(1);
2631 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2632 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2633 MVT::ValueType VT = N->getValueType(0);
2635 // fold (fsub c1, c2) -> c1-c2
2637 return DAG.getNode(ISD::FSUB, VT, N0, N1);
2638 // fold (A-(-B)) -> A+B
2639 if (N1.getOpcode() == ISD::FNEG)
2640 return DAG.getNode(ISD::FADD, VT, N0, N1.getOperand(0));
2644 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
2645 SDOperand N0 = N->getOperand(0);
2646 SDOperand N1 = N->getOperand(1);
2647 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2648 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2649 MVT::ValueType VT = N->getValueType(0);
2651 // fold (fmul c1, c2) -> c1*c2
2653 return DAG.getNode(ISD::FMUL, VT, N0, N1);
2654 // canonicalize constant to RHS
2655 if (N0CFP && !N1CFP)
2656 return DAG.getNode(ISD::FMUL, VT, N1, N0);
2657 // fold (fmul X, 2.0) -> (fadd X, X)
2658 if (N1CFP && N1CFP->isExactlyValue(+2.0))
2659 return DAG.getNode(ISD::FADD, VT, N0, N0);
2663 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
2664 SDOperand N0 = N->getOperand(0);
2665 SDOperand N1 = N->getOperand(1);
2666 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2667 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2668 MVT::ValueType VT = N->getValueType(0);
2670 // fold (fdiv c1, c2) -> c1/c2
2672 return DAG.getNode(ISD::FDIV, VT, N0, N1);
2676 SDOperand DAGCombiner::visitFREM(SDNode *N) {
2677 SDOperand N0 = N->getOperand(0);
2678 SDOperand N1 = N->getOperand(1);
2679 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2680 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2681 MVT::ValueType VT = N->getValueType(0);
2683 // fold (frem c1, c2) -> fmod(c1,c2)
2685 return DAG.getNode(ISD::FREM, VT, N0, N1);
2689 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
2690 SDOperand N0 = N->getOperand(0);
2691 SDOperand N1 = N->getOperand(1);
2692 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2693 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2694 MVT::ValueType VT = N->getValueType(0);
2696 if (N0CFP && N1CFP) // Constant fold
2697 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
2700 // copysign(x, c1) -> fabs(x) iff ispos(c1)
2701 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
2706 u.d = N1CFP->getValue();
2708 return DAG.getNode(ISD::FABS, VT, N0);
2710 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
2713 // copysign(fabs(x), y) -> copysign(x, y)
2714 // copysign(fneg(x), y) -> copysign(x, y)
2715 // copysign(copysign(x,z), y) -> copysign(x, y)
2716 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
2717 N0.getOpcode() == ISD::FCOPYSIGN)
2718 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
2720 // copysign(x, abs(y)) -> abs(x)
2721 if (N1.getOpcode() == ISD::FABS)
2722 return DAG.getNode(ISD::FABS, VT, N0);
2724 // copysign(x, copysign(y,z)) -> copysign(x, z)
2725 if (N1.getOpcode() == ISD::FCOPYSIGN)
2726 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
2728 // copysign(x, fp_extend(y)) -> copysign(x, y)
2729 // copysign(x, fp_round(y)) -> copysign(x, y)
2730 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
2731 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
2738 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
2739 SDOperand N0 = N->getOperand(0);
2740 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2741 MVT::ValueType VT = N->getValueType(0);
2743 // fold (sint_to_fp c1) -> c1fp
2745 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
2749 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
2750 SDOperand N0 = N->getOperand(0);
2751 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2752 MVT::ValueType VT = N->getValueType(0);
2754 // fold (uint_to_fp c1) -> c1fp
2756 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
2760 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
2761 SDOperand N0 = N->getOperand(0);
2762 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2763 MVT::ValueType VT = N->getValueType(0);
2765 // fold (fp_to_sint c1fp) -> c1
2767 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
2771 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
2772 SDOperand N0 = N->getOperand(0);
2773 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2774 MVT::ValueType VT = N->getValueType(0);
2776 // fold (fp_to_uint c1fp) -> c1
2778 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
2782 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
2783 SDOperand N0 = N->getOperand(0);
2784 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2785 MVT::ValueType VT = N->getValueType(0);
2787 // fold (fp_round c1fp) -> c1fp
2789 return DAG.getNode(ISD::FP_ROUND, VT, N0);
2791 // fold (fp_round (fp_extend x)) -> x
2792 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
2793 return N0.getOperand(0);
2795 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
2796 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
2797 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0));
2798 AddToWorkList(Tmp.Val);
2799 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
2805 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
2806 SDOperand N0 = N->getOperand(0);
2807 MVT::ValueType VT = N->getValueType(0);
2808 MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2809 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2811 // fold (fp_round_inreg c1fp) -> c1fp
2813 SDOperand Round = DAG.getConstantFP(N0CFP->getValue(), EVT);
2814 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
2819 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
2820 SDOperand N0 = N->getOperand(0);
2821 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2822 MVT::ValueType VT = N->getValueType(0);
2824 // fold (fp_extend c1fp) -> c1fp
2826 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
2828 // fold (fpext (load x)) -> (fpext (fpround (extload x)))
2829 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2830 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2831 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2832 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2833 LN0->getBasePtr(), LN0->getSrcValue(),
2834 LN0->getSrcValueOffset(),
2836 CombineTo(N, ExtLoad);
2837 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad),
2838 ExtLoad.getValue(1));
2839 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2846 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
2847 SDOperand N0 = N->getOperand(0);
2848 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2849 MVT::ValueType VT = N->getValueType(0);
2851 // fold (fneg c1) -> -c1
2853 return DAG.getNode(ISD::FNEG, VT, N0);
2854 // fold (fneg (sub x, y)) -> (sub y, x)
2855 if (N0.getOpcode() == ISD::SUB)
2856 return DAG.getNode(ISD::SUB, VT, N0.getOperand(1), N0.getOperand(0));
2857 // fold (fneg (fneg x)) -> x
2858 if (N0.getOpcode() == ISD::FNEG)
2859 return N0.getOperand(0);
2863 SDOperand DAGCombiner::visitFABS(SDNode *N) {
2864 SDOperand N0 = N->getOperand(0);
2865 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2866 MVT::ValueType VT = N->getValueType(0);
2868 // fold (fabs c1) -> fabs(c1)
2870 return DAG.getNode(ISD::FABS, VT, N0);
2871 // fold (fabs (fabs x)) -> (fabs x)
2872 if (N0.getOpcode() == ISD::FABS)
2873 return N->getOperand(0);
2874 // fold (fabs (fneg x)) -> (fabs x)
2875 // fold (fabs (fcopysign x, y)) -> (fabs x)
2876 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
2877 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
2882 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
2883 SDOperand Chain = N->getOperand(0);
2884 SDOperand N1 = N->getOperand(1);
2885 SDOperand N2 = N->getOperand(2);
2886 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2888 // never taken branch, fold to chain
2889 if (N1C && N1C->isNullValue())
2891 // unconditional branch
2892 if (N1C && N1C->getValue() == 1)
2893 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
2894 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
2896 if (N1.getOpcode() == ISD::SETCC &&
2897 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
2898 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
2899 N1.getOperand(0), N1.getOperand(1), N2);
2904 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
2906 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
2907 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
2908 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
2910 // Use SimplifySetCC to simplify SETCC's.
2911 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
2912 if (Simp.Val) AddToWorkList(Simp.Val);
2914 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
2916 // fold br_cc true, dest -> br dest (unconditional branch)
2917 if (SCCC && SCCC->getValue())
2918 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
2920 // fold br_cc false, dest -> unconditional fall through
2921 if (SCCC && SCCC->isNullValue())
2922 return N->getOperand(0);
2924 // fold to a simpler setcc
2925 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
2926 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
2927 Simp.getOperand(2), Simp.getOperand(0),
2928 Simp.getOperand(1), N->getOperand(4));
2932 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
2933 LoadSDNode *LD = cast<LoadSDNode>(N);
2934 SDOperand Chain = LD->getChain();
2935 SDOperand Ptr = LD->getBasePtr();
2937 // If there are no uses of the loaded value, change uses of the chain value
2938 // into uses of the chain input (i.e. delete the dead load).
2939 if (N->hasNUsesOfValue(0, 0))
2940 return CombineTo(N, DAG.getNode(ISD::UNDEF, N->getValueType(0)), Chain);
2942 // If this load is directly stored, replace the load value with the stored
2944 // TODO: Handle store large -> read small portion.
2945 // TODO: Handle TRUNCSTORE/LOADEXT
2946 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
2947 if (ISD::isNON_TRUNCStore(Chain.Val)) {
2948 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
2949 if (PrevST->getBasePtr() == Ptr &&
2950 PrevST->getValue().getValueType() == N->getValueType(0))
2951 return CombineTo(N, Chain.getOperand(1), Chain);
2956 // Walk up chain skipping non-aliasing memory nodes.
2957 SDOperand BetterChain = FindBetterChain(N, Chain);
2959 // If there is a better chain.
2960 if (Chain != BetterChain) {
2963 // Replace the chain to void dependency.
2964 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
2965 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
2966 LD->getSrcValue(), LD->getSrcValueOffset());
2968 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
2969 LD->getValueType(0),
2970 BetterChain, Ptr, LD->getSrcValue(),
2971 LD->getSrcValueOffset(),
2975 // Create token factor to keep old chain connected.
2976 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
2977 Chain, ReplLoad.getValue(1));
2979 // Replace uses with load result and token factor. Don't add users
2981 return CombineTo(N, ReplLoad.getValue(0), Token, false);
2985 // Try transforming N to an indexed load.
2986 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
2987 return SDOperand(N, 0);
2992 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
2993 StoreSDNode *ST = cast<StoreSDNode>(N);
2994 SDOperand Chain = ST->getChain();
2995 SDOperand Value = ST->getValue();
2996 SDOperand Ptr = ST->getBasePtr();
2998 // If this is a store of a bit convert, store the input value.
2999 // FIXME: This needs to know that the resultant store does not need a
3000 // higher alignment than the original.
3001 if (0 && Value.getOpcode() == ISD::BIT_CONVERT) {
3002 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
3003 ST->getSrcValueOffset());
3007 // Walk up chain skipping non-aliasing memory nodes.
3008 SDOperand BetterChain = FindBetterChain(N, Chain);
3010 // If there is a better chain.
3011 if (Chain != BetterChain) {
3012 // Replace the chain to avoid dependency.
3013 SDOperand ReplStore;
3014 if (ST->isTruncatingStore()) {
3015 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
3016 ST->getSrcValue(),ST->getSrcValueOffset(), ST->getStoredVT());
3018 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
3019 ST->getSrcValue(), ST->getSrcValueOffset());
3022 // Create token to keep both nodes around.
3024 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
3026 // Don't add users to work list.
3027 return CombineTo(N, Token, false);
3031 // Try transforming N to an indexed store.
3032 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
3033 return SDOperand(N, 0);
3038 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
3039 SDOperand InVec = N->getOperand(0);
3040 SDOperand InVal = N->getOperand(1);
3041 SDOperand EltNo = N->getOperand(2);
3043 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
3044 // vector with the inserted element.
3045 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
3046 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
3047 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
3048 if (Elt < Ops.size())
3050 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
3051 &Ops[0], Ops.size());
3057 SDOperand DAGCombiner::visitVINSERT_VECTOR_ELT(SDNode *N) {
3058 SDOperand InVec = N->getOperand(0);
3059 SDOperand InVal = N->getOperand(1);
3060 SDOperand EltNo = N->getOperand(2);
3061 SDOperand NumElts = N->getOperand(3);
3062 SDOperand EltType = N->getOperand(4);
3064 // If the invec is a VBUILD_VECTOR and if EltNo is a constant, build a new
3065 // vector with the inserted element.
3066 if (InVec.getOpcode() == ISD::VBUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
3067 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
3068 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
3069 if (Elt < Ops.size()-2)
3071 return DAG.getNode(ISD::VBUILD_VECTOR, InVec.getValueType(),
3072 &Ops[0], Ops.size());
3078 SDOperand DAGCombiner::visitVBUILD_VECTOR(SDNode *N) {
3079 unsigned NumInScalars = N->getNumOperands()-2;
3080 SDOperand NumElts = N->getOperand(NumInScalars);
3081 SDOperand EltType = N->getOperand(NumInScalars+1);
3083 // Check to see if this is a VBUILD_VECTOR of a bunch of VEXTRACT_VECTOR_ELT
3084 // operations. If so, and if the EXTRACT_ELT vector inputs come from at most
3085 // two distinct vectors, turn this into a shuffle node.
3086 SDOperand VecIn1, VecIn2;
3087 for (unsigned i = 0; i != NumInScalars; ++i) {
3088 // Ignore undef inputs.
3089 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
3091 // If this input is something other than a VEXTRACT_VECTOR_ELT with a
3092 // constant index, bail out.
3093 if (N->getOperand(i).getOpcode() != ISD::VEXTRACT_VECTOR_ELT ||
3094 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
3095 VecIn1 = VecIn2 = SDOperand(0, 0);
3099 // If the input vector type disagrees with the result of the vbuild_vector,
3100 // we can't make a shuffle.
3101 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
3102 if (*(ExtractedFromVec.Val->op_end()-2) != NumElts ||
3103 *(ExtractedFromVec.Val->op_end()-1) != EltType) {
3104 VecIn1 = VecIn2 = SDOperand(0, 0);
3108 // Otherwise, remember this. We allow up to two distinct input vectors.
3109 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
3112 if (VecIn1.Val == 0) {
3113 VecIn1 = ExtractedFromVec;
3114 } else if (VecIn2.Val == 0) {
3115 VecIn2 = ExtractedFromVec;
3118 VecIn1 = VecIn2 = SDOperand(0, 0);
3123 // If everything is good, we can make a shuffle operation.
3125 SmallVector<SDOperand, 8> BuildVecIndices;
3126 for (unsigned i = 0; i != NumInScalars; ++i) {
3127 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
3128 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3132 SDOperand Extract = N->getOperand(i);
3134 // If extracting from the first vector, just use the index directly.
3135 if (Extract.getOperand(0) == VecIn1) {
3136 BuildVecIndices.push_back(Extract.getOperand(1));
3140 // Otherwise, use InIdx + VecSize
3141 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
3142 BuildVecIndices.push_back(DAG.getConstant(Idx+NumInScalars, MVT::i32));
3145 // Add count and size info.
3146 BuildVecIndices.push_back(NumElts);
3147 BuildVecIndices.push_back(DAG.getValueType(MVT::i32));
3149 // Return the new VVECTOR_SHUFFLE node.
3155 // Use an undef vbuild_vector as input for the second operand.
3156 std::vector<SDOperand> UnOps(NumInScalars,
3157 DAG.getNode(ISD::UNDEF,
3158 cast<VTSDNode>(EltType)->getVT()));
3159 UnOps.push_back(NumElts);
3160 UnOps.push_back(EltType);
3161 Ops[1] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3162 &UnOps[0], UnOps.size());
3163 AddToWorkList(Ops[1].Val);
3165 Ops[2] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3166 &BuildVecIndices[0], BuildVecIndices.size());
3169 return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, Ops, 5);
3175 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
3176 SDOperand ShufMask = N->getOperand(2);
3177 unsigned NumElts = ShufMask.getNumOperands();
3179 // If the shuffle mask is an identity operation on the LHS, return the LHS.
3180 bool isIdentity = true;
3181 for (unsigned i = 0; i != NumElts; ++i) {
3182 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3183 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
3188 if (isIdentity) return N->getOperand(0);
3190 // If the shuffle mask is an identity operation on the RHS, return the RHS.
3192 for (unsigned i = 0; i != NumElts; ++i) {
3193 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3194 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
3199 if (isIdentity) return N->getOperand(1);
3201 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
3203 bool isUnary = true;
3204 bool isSplat = true;
3206 unsigned BaseIdx = 0;
3207 for (unsigned i = 0; i != NumElts; ++i)
3208 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
3209 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
3210 int V = (Idx < NumElts) ? 0 : 1;
3224 SDOperand N0 = N->getOperand(0);
3225 SDOperand N1 = N->getOperand(1);
3226 // Normalize unary shuffle so the RHS is undef.
3227 if (isUnary && VecNum == 1)
3230 // If it is a splat, check if the argument vector is a build_vector with
3231 // all scalar elements the same.
3234 if (V->getOpcode() == ISD::BIT_CONVERT)
3235 V = V->getOperand(0).Val;
3236 if (V->getOpcode() == ISD::BUILD_VECTOR) {
3237 unsigned NumElems = V->getNumOperands()-2;
3238 if (NumElems > BaseIdx) {
3240 bool AllSame = true;
3241 for (unsigned i = 0; i != NumElems; ++i) {
3242 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
3243 Base = V->getOperand(i);
3247 // Splat of <u, u, u, u>, return <u, u, u, u>
3250 for (unsigned i = 0; i != NumElems; ++i) {
3251 if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
3252 V->getOperand(i) != Base) {
3257 // Splat of <x, x, x, x>, return <x, x, x, x>
3264 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
3266 if (isUnary || N0 == N1) {
3267 if (N0.getOpcode() == ISD::UNDEF)
3268 return DAG.getNode(ISD::UNDEF, N->getValueType(0));
3269 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
3271 SmallVector<SDOperand, 8> MappedOps;
3272 for (unsigned i = 0, e = ShufMask.getNumOperands(); i != e; ++i) {
3273 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
3274 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
3275 MappedOps.push_back(ShufMask.getOperand(i));
3278 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
3279 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
3282 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
3283 &MappedOps[0], MappedOps.size());
3284 AddToWorkList(ShufMask.Val);
3285 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
3287 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
3294 SDOperand DAGCombiner::visitVVECTOR_SHUFFLE(SDNode *N) {
3295 SDOperand ShufMask = N->getOperand(2);
3296 unsigned NumElts = ShufMask.getNumOperands()-2;
3298 // If the shuffle mask is an identity operation on the LHS, return the LHS.
3299 bool isIdentity = true;
3300 for (unsigned i = 0; i != NumElts; ++i) {
3301 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3302 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
3307 if (isIdentity) return N->getOperand(0);
3309 // If the shuffle mask is an identity operation on the RHS, return the RHS.
3311 for (unsigned i = 0; i != NumElts; ++i) {
3312 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3313 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
3318 if (isIdentity) return N->getOperand(1);
3320 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
3322 bool isUnary = true;
3323 bool isSplat = true;
3325 unsigned BaseIdx = 0;
3326 for (unsigned i = 0; i != NumElts; ++i)
3327 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
3328 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
3329 int V = (Idx < NumElts) ? 0 : 1;
3343 SDOperand N0 = N->getOperand(0);
3344 SDOperand N1 = N->getOperand(1);
3345 // Normalize unary shuffle so the RHS is undef.
3346 if (isUnary && VecNum == 1)
3349 // If it is a splat, check if the argument vector is a build_vector with
3350 // all scalar elements the same.
3354 // If this is a vbit convert that changes the element type of the vector but
3355 // not the number of vector elements, look through it. Be careful not to
3356 // look though conversions that change things like v4f32 to v2f64.
3357 if (V->getOpcode() == ISD::VBIT_CONVERT) {
3358 SDOperand ConvInput = V->getOperand(0);
3359 if (ConvInput.getValueType() == MVT::Vector &&
3361 ConvInput.getConstantOperandVal(ConvInput.getNumOperands()-2))
3365 if (V->getOpcode() == ISD::VBUILD_VECTOR) {
3366 unsigned NumElems = V->getNumOperands()-2;
3367 if (NumElems > BaseIdx) {
3369 bool AllSame = true;
3370 for (unsigned i = 0; i != NumElems; ++i) {
3371 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
3372 Base = V->getOperand(i);
3376 // Splat of <u, u, u, u>, return <u, u, u, u>
3379 for (unsigned i = 0; i != NumElems; ++i) {
3380 if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
3381 V->getOperand(i) != Base) {
3386 // Splat of <x, x, x, x>, return <x, x, x, x>
3393 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
3395 if (isUnary || N0 == N1) {
3396 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
3398 SmallVector<SDOperand, 8> MappedOps;
3399 for (unsigned i = 0; i != NumElts; ++i) {
3400 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
3401 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
3402 MappedOps.push_back(ShufMask.getOperand(i));
3405 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
3406 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
3409 // Add the type/#elts values.
3410 MappedOps.push_back(ShufMask.getOperand(NumElts));
3411 MappedOps.push_back(ShufMask.getOperand(NumElts+1));
3413 ShufMask = DAG.getNode(ISD::VBUILD_VECTOR, ShufMask.getValueType(),
3414 &MappedOps[0], MappedOps.size());
3415 AddToWorkList(ShufMask.Val);
3417 // Build the undef vector.
3418 SDOperand UDVal = DAG.getNode(ISD::UNDEF, MappedOps[0].getValueType());
3419 for (unsigned i = 0; i != NumElts; ++i)
3420 MappedOps[i] = UDVal;
3421 MappedOps[NumElts ] = *(N0.Val->op_end()-2);
3422 MappedOps[NumElts+1] = *(N0.Val->op_end()-1);
3423 UDVal = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3424 &MappedOps[0], MappedOps.size());
3426 return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
3427 N0, UDVal, ShufMask,
3428 MappedOps[NumElts], MappedOps[NumElts+1]);
3434 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
3435 /// a VAND to a vector_shuffle with the destination vector and a zero vector.
3436 /// e.g. VAND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
3437 /// vector_shuffle V, Zero, <0, 4, 2, 4>
3438 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
3439 SDOperand LHS = N->getOperand(0);
3440 SDOperand RHS = N->getOperand(1);
3441 if (N->getOpcode() == ISD::VAND) {
3442 SDOperand DstVecSize = *(LHS.Val->op_end()-2);
3443 SDOperand DstVecEVT = *(LHS.Val->op_end()-1);
3444 if (RHS.getOpcode() == ISD::VBIT_CONVERT)
3445 RHS = RHS.getOperand(0);
3446 if (RHS.getOpcode() == ISD::VBUILD_VECTOR) {
3447 std::vector<SDOperand> IdxOps;
3448 unsigned NumOps = RHS.getNumOperands();
3449 unsigned NumElts = NumOps-2;
3450 MVT::ValueType EVT = cast<VTSDNode>(RHS.getOperand(NumOps-1))->getVT();
3451 for (unsigned i = 0; i != NumElts; ++i) {
3452 SDOperand Elt = RHS.getOperand(i);
3453 if (!isa<ConstantSDNode>(Elt))
3455 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
3456 IdxOps.push_back(DAG.getConstant(i, EVT));
3457 else if (cast<ConstantSDNode>(Elt)->isNullValue())
3458 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
3463 // Let's see if the target supports this vector_shuffle.
3464 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
3467 // Return the new VVECTOR_SHUFFLE node.
3468 SDOperand NumEltsNode = DAG.getConstant(NumElts, MVT::i32);
3469 SDOperand EVTNode = DAG.getValueType(EVT);
3470 std::vector<SDOperand> Ops;
3471 LHS = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, LHS, NumEltsNode,
3474 AddToWorkList(LHS.Val);
3475 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
3476 ZeroOps.push_back(NumEltsNode);
3477 ZeroOps.push_back(EVTNode);
3478 Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3479 &ZeroOps[0], ZeroOps.size()));
3480 IdxOps.push_back(NumEltsNode);
3481 IdxOps.push_back(EVTNode);
3482 Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3483 &IdxOps[0], IdxOps.size()));
3484 Ops.push_back(NumEltsNode);
3485 Ops.push_back(EVTNode);
3486 SDOperand Result = DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
3487 &Ops[0], Ops.size());
3488 if (NumEltsNode != DstVecSize || EVTNode != DstVecEVT) {
3489 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
3490 DstVecSize, DstVecEVT);
3498 /// visitVBinOp - Visit a binary vector operation, like VADD. IntOp indicates
3499 /// the scalar operation of the vop if it is operating on an integer vector
3500 /// (e.g. ADD) and FPOp indicates the FP version (e.g. FADD).
3501 SDOperand DAGCombiner::visitVBinOp(SDNode *N, ISD::NodeType IntOp,
3502 ISD::NodeType FPOp) {
3503 MVT::ValueType EltType = cast<VTSDNode>(*(N->op_end()-1))->getVT();
3504 ISD::NodeType ScalarOp = MVT::isInteger(EltType) ? IntOp : FPOp;
3505 SDOperand LHS = N->getOperand(0);
3506 SDOperand RHS = N->getOperand(1);
3507 SDOperand Shuffle = XformToShuffleWithZero(N);
3508 if (Shuffle.Val) return Shuffle;
3510 // If the LHS and RHS are VBUILD_VECTOR nodes, see if we can constant fold
3512 if (LHS.getOpcode() == ISD::VBUILD_VECTOR &&
3513 RHS.getOpcode() == ISD::VBUILD_VECTOR) {
3514 SmallVector<SDOperand, 8> Ops;
3515 for (unsigned i = 0, e = LHS.getNumOperands()-2; i != e; ++i) {
3516 SDOperand LHSOp = LHS.getOperand(i);
3517 SDOperand RHSOp = RHS.getOperand(i);
3518 // If these two elements can't be folded, bail out.
3519 if ((LHSOp.getOpcode() != ISD::UNDEF &&
3520 LHSOp.getOpcode() != ISD::Constant &&
3521 LHSOp.getOpcode() != ISD::ConstantFP) ||
3522 (RHSOp.getOpcode() != ISD::UNDEF &&
3523 RHSOp.getOpcode() != ISD::Constant &&
3524 RHSOp.getOpcode() != ISD::ConstantFP))
3526 // Can't fold divide by zero.
3527 if (N->getOpcode() == ISD::VSDIV || N->getOpcode() == ISD::VUDIV) {
3528 if ((RHSOp.getOpcode() == ISD::Constant &&
3529 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
3530 (RHSOp.getOpcode() == ISD::ConstantFP &&
3531 !cast<ConstantFPSDNode>(RHSOp.Val)->getValue()))
3534 Ops.push_back(DAG.getNode(ScalarOp, EltType, LHSOp, RHSOp));
3535 AddToWorkList(Ops.back().Val);
3536 assert((Ops.back().getOpcode() == ISD::UNDEF ||
3537 Ops.back().getOpcode() == ISD::Constant ||
3538 Ops.back().getOpcode() == ISD::ConstantFP) &&
3539 "Scalar binop didn't fold!");
3542 if (Ops.size() == LHS.getNumOperands()-2) {
3543 Ops.push_back(*(LHS.Val->op_end()-2));
3544 Ops.push_back(*(LHS.Val->op_end()-1));
3545 return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
3552 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
3553 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
3555 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
3556 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3557 // If we got a simplified select_cc node back from SimplifySelectCC, then
3558 // break it down into a new SETCC node, and a new SELECT node, and then return
3559 // the SELECT node, since we were called with a SELECT node.
3561 // Check to see if we got a select_cc back (to turn into setcc/select).
3562 // Otherwise, just return whatever node we got back, like fabs.
3563 if (SCC.getOpcode() == ISD::SELECT_CC) {
3564 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
3565 SCC.getOperand(0), SCC.getOperand(1),
3567 AddToWorkList(SETCC.Val);
3568 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
3569 SCC.getOperand(3), SETCC);
3576 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
3577 /// are the two values being selected between, see if we can simplify the
3578 /// select. Callers of this should assume that TheSelect is deleted if this
3579 /// returns true. As such, they should return the appropriate thing (e.g. the
3580 /// node) back to the top-level of the DAG combiner loop to avoid it being
3583 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
3586 // If this is a select from two identical things, try to pull the operation
3587 // through the select.
3588 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
3589 // If this is a load and the token chain is identical, replace the select
3590 // of two loads with a load through a select of the address to load from.
3591 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
3592 // constants have been dropped into the constant pool.
3593 if (LHS.getOpcode() == ISD::LOAD &&
3594 // Token chains must be identical.
3595 LHS.getOperand(0) == RHS.getOperand(0)) {
3596 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
3597 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
3599 // If this is an EXTLOAD, the VT's must match.
3600 if (LLD->getLoadedVT() == RLD->getLoadedVT()) {
3601 // FIXME: this conflates two src values, discarding one. This is not
3602 // the right thing to do, but nothing uses srcvalues now. When they do,
3603 // turn SrcValue into a list of locations.
3605 if (TheSelect->getOpcode() == ISD::SELECT)
3606 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
3607 TheSelect->getOperand(0), LLD->getBasePtr(),
3610 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
3611 TheSelect->getOperand(0),
3612 TheSelect->getOperand(1),
3613 LLD->getBasePtr(), RLD->getBasePtr(),
3614 TheSelect->getOperand(4));
3617 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
3618 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
3619 Addr,LLD->getSrcValue(), LLD->getSrcValueOffset());
3621 Load = DAG.getExtLoad(LLD->getExtensionType(),
3622 TheSelect->getValueType(0),
3623 LLD->getChain(), Addr, LLD->getSrcValue(),
3624 LLD->getSrcValueOffset(),
3625 LLD->getLoadedVT());
3627 // Users of the select now use the result of the load.
3628 CombineTo(TheSelect, Load);
3630 // Users of the old loads now use the new load's chain. We know the
3631 // old-load value is dead now.
3632 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
3633 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
3642 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
3643 SDOperand N2, SDOperand N3,
3646 MVT::ValueType VT = N2.getValueType();
3647 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
3648 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
3649 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
3651 // Determine if the condition we're dealing with is constant
3652 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
3653 if (SCC.Val) AddToWorkList(SCC.Val);
3654 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
3656 // fold select_cc true, x, y -> x
3657 if (SCCC && SCCC->getValue())
3659 // fold select_cc false, x, y -> y
3660 if (SCCC && SCCC->getValue() == 0)
3663 // Check to see if we can simplify the select into an fabs node
3664 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
3665 // Allow either -0.0 or 0.0
3666 if (CFP->getValue() == 0.0) {
3667 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
3668 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
3669 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
3670 N2 == N3.getOperand(0))
3671 return DAG.getNode(ISD::FABS, VT, N0);
3673 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
3674 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
3675 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
3676 N2.getOperand(0) == N3)
3677 return DAG.getNode(ISD::FABS, VT, N3);
3681 // Check to see if we can perform the "gzip trick", transforming
3682 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
3683 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
3684 MVT::isInteger(N0.getValueType()) &&
3685 MVT::isInteger(N2.getValueType()) &&
3686 (N1C->isNullValue() || // (a < 0) ? b : 0
3687 (N1C->getValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
3688 MVT::ValueType XType = N0.getValueType();
3689 MVT::ValueType AType = N2.getValueType();
3690 if (XType >= AType) {
3691 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
3692 // single-bit constant.
3693 if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
3694 unsigned ShCtV = Log2_64(N2C->getValue());
3695 ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
3696 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
3697 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
3698 AddToWorkList(Shift.Val);
3699 if (XType > AType) {
3700 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
3701 AddToWorkList(Shift.Val);
3703 return DAG.getNode(ISD::AND, AType, Shift, N2);
3705 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
3706 DAG.getConstant(MVT::getSizeInBits(XType)-1,
3707 TLI.getShiftAmountTy()));
3708 AddToWorkList(Shift.Val);
3709 if (XType > AType) {
3710 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
3711 AddToWorkList(Shift.Val);
3713 return DAG.getNode(ISD::AND, AType, Shift, N2);
3717 // fold select C, 16, 0 -> shl C, 4
3718 if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
3719 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
3720 // Get a SetCC of the condition
3721 // FIXME: Should probably make sure that setcc is legal if we ever have a
3722 // target where it isn't.
3723 SDOperand Temp, SCC;
3724 // cast from setcc result type to select result type
3725 if (AfterLegalize) {
3726 SCC = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
3727 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
3729 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
3730 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
3732 AddToWorkList(SCC.Val);
3733 AddToWorkList(Temp.Val);
3734 // shl setcc result by log2 n2c
3735 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
3736 DAG.getConstant(Log2_64(N2C->getValue()),
3737 TLI.getShiftAmountTy()));
3740 // Check to see if this is the equivalent of setcc
3741 // FIXME: Turn all of these into setcc if setcc if setcc is legal
3742 // otherwise, go ahead with the folds.
3743 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
3744 MVT::ValueType XType = N0.getValueType();
3745 if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
3746 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
3747 if (Res.getValueType() != VT)
3748 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
3752 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
3753 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
3754 TLI.isOperationLegal(ISD::CTLZ, XType)) {
3755 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
3756 return DAG.getNode(ISD::SRL, XType, Ctlz,
3757 DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
3758 TLI.getShiftAmountTy()));
3760 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
3761 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
3762 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
3764 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
3765 DAG.getConstant(~0ULL, XType));
3766 return DAG.getNode(ISD::SRL, XType,
3767 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
3768 DAG.getConstant(MVT::getSizeInBits(XType)-1,
3769 TLI.getShiftAmountTy()));
3771 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
3772 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
3773 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
3774 DAG.getConstant(MVT::getSizeInBits(XType)-1,
3775 TLI.getShiftAmountTy()));
3776 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
3780 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
3781 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
3782 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
3783 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) {
3784 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0))) {
3785 MVT::ValueType XType = N0.getValueType();
3786 if (SubC->isNullValue() && MVT::isInteger(XType)) {
3787 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
3788 DAG.getConstant(MVT::getSizeInBits(XType)-1,
3789 TLI.getShiftAmountTy()));
3790 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
3791 AddToWorkList(Shift.Val);
3792 AddToWorkList(Add.Val);
3793 return DAG.getNode(ISD::XOR, XType, Add, Shift);
3801 SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
3802 SDOperand N1, ISD::CondCode Cond,
3803 bool foldBooleans) {
3804 // These setcc operations always fold.
3808 case ISD::SETFALSE2: return DAG.getConstant(0, VT);
3810 case ISD::SETTRUE2: return DAG.getConstant(1, VT);
3813 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
3814 uint64_t C1 = N1C->getValue();
3815 if (isa<ConstantSDNode>(N0.Val)) {
3816 return DAG.FoldSetCC(VT, N0, N1, Cond);
3818 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3819 // equality comparison, then we're just comparing whether X itself is
3821 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
3822 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
3823 N0.getOperand(1).getOpcode() == ISD::Constant) {
3824 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
3825 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3826 ShAmt == Log2_32(MVT::getSizeInBits(N0.getValueType()))) {
3827 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
3828 // (srl (ctlz x), 5) == 0 -> X != 0
3829 // (srl (ctlz x), 5) != 1 -> X != 0
3832 // (srl (ctlz x), 5) != 0 -> X == 0
3833 // (srl (ctlz x), 5) == 1 -> X == 0
3836 SDOperand Zero = DAG.getConstant(0, N0.getValueType());
3837 return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0),
3842 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3843 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
3844 unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
3846 // If the comparison constant has bits in the upper part, the
3847 // zero-extended value could never match.
3848 if (C1 & (~0ULL << InSize)) {
3849 unsigned VSize = MVT::getSizeInBits(N0.getValueType());
3853 case ISD::SETEQ: return DAG.getConstant(0, VT);
3856 case ISD::SETNE: return DAG.getConstant(1, VT);
3859 // True if the sign bit of C1 is set.
3860 return DAG.getConstant((C1 & (1ULL << VSize)) != 0, VT);
3863 // True if the sign bit of C1 isn't set.
3864 return DAG.getConstant((C1 & (1ULL << VSize)) == 0, VT);
3870 // Otherwise, we can perform the comparison with the low bits.
3878 return DAG.getSetCC(VT, N0.getOperand(0),
3879 DAG.getConstant(C1, N0.getOperand(0).getValueType()),
3882 break; // todo, be more careful with signed comparisons
3884 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3885 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3886 MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
3887 unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
3888 MVT::ValueType ExtDstTy = N0.getValueType();
3889 unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
3891 // If the extended part has any inconsistent bits, it cannot ever
3892 // compare equal. In other words, they have to be all ones or all
3895 (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
3896 if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
3897 return DAG.getConstant(Cond == ISD::SETNE, VT);
3900 MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
3901 if (Op0Ty == ExtSrcTy) {
3902 ZextOp = N0.getOperand(0);
3904 int64_t Imm = ~0ULL >> (64-ExtSrcTyBits);
3905 ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
3906 DAG.getConstant(Imm, Op0Ty));
3908 AddToWorkList(ZextOp.Val);
3909 // Otherwise, make this a use of a zext.
3910 return DAG.getSetCC(VT, ZextOp,
3911 DAG.getConstant(C1 & (~0ULL>>(64-ExtSrcTyBits)),
3914 } else if ((N1C->getValue() == 0 || N1C->getValue() == 1) &&
3915 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3917 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
3918 if (N0.getOpcode() == ISD::SETCC) {
3919 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getValue() != 1);
3923 // Invert the condition.
3924 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
3925 CC = ISD::getSetCCInverse(CC,
3926 MVT::isInteger(N0.getOperand(0).getValueType()));
3927 return DAG.getSetCC(VT, N0.getOperand(0), N0.getOperand(1), CC);
3930 if ((N0.getOpcode() == ISD::XOR ||
3931 (N0.getOpcode() == ISD::AND &&
3932 N0.getOperand(0).getOpcode() == ISD::XOR &&
3933 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
3934 isa<ConstantSDNode>(N0.getOperand(1)) &&
3935 cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
3936 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
3937 // can only do this if the top bits are known zero.
3938 if (TLI.MaskedValueIsZero(N0,
3939 MVT::getIntVTBitMask(N0.getValueType())-1)){
3940 // Okay, get the un-inverted input value.
3942 if (N0.getOpcode() == ISD::XOR)
3943 Val = N0.getOperand(0);
3945 assert(N0.getOpcode() == ISD::AND &&
3946 N0.getOperand(0).getOpcode() == ISD::XOR);
3947 // ((X^1)&1)^1 -> X & 1
3948 Val = DAG.getNode(ISD::AND, N0.getValueType(),
3949 N0.getOperand(0).getOperand(0),
3952 return DAG.getSetCC(VT, Val, N1,
3953 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3958 uint64_t MinVal, MaxVal;
3959 unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
3960 if (ISD::isSignedIntSetCC(Cond)) {
3961 MinVal = 1ULL << (OperandBitSize-1);
3962 if (OperandBitSize != 1) // Avoid X >> 64, which is undefined.
3963 MaxVal = ~0ULL >> (65-OperandBitSize);
3968 MaxVal = ~0ULL >> (64-OperandBitSize);
3971 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
3972 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
3973 if (C1 == MinVal) return DAG.getConstant(1, VT); // X >= MIN --> true
3974 --C1; // X >= C0 --> X > (C0-1)
3975 return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
3976 (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
3979 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
3980 if (C1 == MaxVal) return DAG.getConstant(1, VT); // X <= MAX --> true
3981 ++C1; // X <= C0 --> X < (C0+1)
3982 return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
3983 (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
3986 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
3987 return DAG.getConstant(0, VT); // X < MIN --> false
3989 // Canonicalize setgt X, Min --> setne X, Min
3990 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
3991 return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
3992 // Canonicalize setlt X, Max --> setne X, Max
3993 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
3994 return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
3996 // If we have setult X, 1, turn it into seteq X, 0
3997 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
3998 return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
4000 // If we have setugt X, Max-1, turn it into seteq X, Max
4001 else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
4002 return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
4005 // If we have "setcc X, C0", check to see if we can shrink the immediate
4008 // SETUGT X, SINTMAX -> SETLT X, 0
4009 if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
4010 C1 == (~0ULL >> (65-OperandBitSize)))
4011 return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
4014 // FIXME: Implement the rest of these.
4016 // Fold bit comparisons when we can.
4017 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4018 VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
4019 if (ConstantSDNode *AndRHS =
4020 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4021 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
4022 // Perform the xform if the AND RHS is a single bit.
4023 if (isPowerOf2_64(AndRHS->getValue())) {
4024 return DAG.getNode(ISD::SRL, VT, N0,
4025 DAG.getConstant(Log2_64(AndRHS->getValue()),
4026 TLI.getShiftAmountTy()));
4028 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
4029 // (X & 8) == 8 --> (X & 8) >> 3
4030 // Perform the xform if C1 is a single bit.
4031 if (isPowerOf2_64(C1)) {
4032 return DAG.getNode(ISD::SRL, VT, N0,
4033 DAG.getConstant(Log2_64(C1),TLI.getShiftAmountTy()));
4038 } else if (isa<ConstantSDNode>(N0.Val)) {
4039 // Ensure that the constant occurs on the RHS.
4040 return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
4043 if (isa<ConstantFPSDNode>(N0.Val)) {
4044 // Constant fold or commute setcc.
4045 SDOperand O = DAG.FoldSetCC(VT, N0, N1, Cond);
4046 if (O.Val) return O;
4050 // We can always fold X == X for integer setcc's.
4051 if (MVT::isInteger(N0.getValueType()))
4052 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
4053 unsigned UOF = ISD::getUnorderedFlavor(Cond);
4054 if (UOF == 2) // FP operators that are undefined on NaNs.
4055 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
4056 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
4057 return DAG.getConstant(UOF, VT);
4058 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
4059 // if it is not already.
4060 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
4061 if (NewCond != Cond)
4062 return DAG.getSetCC(VT, N0, N1, NewCond);
4065 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4066 MVT::isInteger(N0.getValueType())) {
4067 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
4068 N0.getOpcode() == ISD::XOR) {
4069 // Simplify (X+Y) == (X+Z) --> Y == Z
4070 if (N0.getOpcode() == N1.getOpcode()) {
4071 if (N0.getOperand(0) == N1.getOperand(0))
4072 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
4073 if (N0.getOperand(1) == N1.getOperand(1))
4074 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
4075 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
4076 // If X op Y == Y op X, try other combinations.
4077 if (N0.getOperand(0) == N1.getOperand(1))
4078 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
4079 if (N0.getOperand(1) == N1.getOperand(0))
4080 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
4084 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
4085 if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4086 // Turn (X+C1) == C2 --> X == C2-C1
4087 if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
4088 return DAG.getSetCC(VT, N0.getOperand(0),
4089 DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
4090 N0.getValueType()), Cond);
4093 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
4094 if (N0.getOpcode() == ISD::XOR)
4095 // If we know that all of the inverted bits are zero, don't bother
4096 // performing the inversion.
4097 if (TLI.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getValue()))
4098 return DAG.getSetCC(VT, N0.getOperand(0),
4099 DAG.getConstant(LHSR->getValue()^RHSC->getValue(),
4100 N0.getValueType()), Cond);
4103 // Turn (C1-X) == C2 --> X == C1-C2
4104 if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
4105 if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
4106 return DAG.getSetCC(VT, N0.getOperand(1),
4107 DAG.getConstant(SUBC->getValue()-RHSC->getValue(),
4108 N0.getValueType()), Cond);
4113 // Simplify (X+Z) == X --> Z == 0
4114 if (N0.getOperand(0) == N1)
4115 return DAG.getSetCC(VT, N0.getOperand(1),
4116 DAG.getConstant(0, N0.getValueType()), Cond);
4117 if (N0.getOperand(1) == N1) {
4118 if (DAG.isCommutativeBinOp(N0.getOpcode()))
4119 return DAG.getSetCC(VT, N0.getOperand(0),
4120 DAG.getConstant(0, N0.getValueType()), Cond);
4122 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
4123 // (Z-X) == X --> Z == X<<1
4124 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
4126 DAG.getConstant(1,TLI.getShiftAmountTy()));
4127 AddToWorkList(SH.Val);
4128 return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
4133 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
4134 N1.getOpcode() == ISD::XOR) {
4135 // Simplify X == (X+Z) --> Z == 0
4136 if (N1.getOperand(0) == N0) {
4137 return DAG.getSetCC(VT, N1.getOperand(1),
4138 DAG.getConstant(0, N1.getValueType()), Cond);
4139 } else if (N1.getOperand(1) == N0) {
4140 if (DAG.isCommutativeBinOp(N1.getOpcode())) {
4141 return DAG.getSetCC(VT, N1.getOperand(0),
4142 DAG.getConstant(0, N1.getValueType()), Cond);
4144 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
4145 // X == (Z-X) --> X<<1 == Z
4146 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0,
4147 DAG.getConstant(1,TLI.getShiftAmountTy()));
4148 AddToWorkList(SH.Val);
4149 return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
4155 // Fold away ALL boolean setcc's.
4157 if (N0.getValueType() == MVT::i1 && foldBooleans) {
4159 default: assert(0 && "Unknown integer setcc!");
4160 case ISD::SETEQ: // X == Y -> (X^Y)^1
4161 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
4162 N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
4163 AddToWorkList(Temp.Val);
4165 case ISD::SETNE: // X != Y --> (X^Y)
4166 N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
4168 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> X^1 & Y
4169 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> X^1 & Y
4170 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
4171 N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
4172 AddToWorkList(Temp.Val);
4174 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> Y^1 & X
4175 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> Y^1 & X
4176 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
4177 N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
4178 AddToWorkList(Temp.Val);
4180 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> X^1 | Y
4181 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> X^1 | Y
4182 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
4183 N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
4184 AddToWorkList(Temp.Val);
4186 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> Y^1 | X
4187 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> Y^1 | X
4188 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
4189 N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
4192 if (VT != MVT::i1) {
4193 AddToWorkList(N0.Val);
4194 // FIXME: If running after legalize, we probably can't do this.
4195 N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
4200 // Could not fold it.
4204 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
4205 /// return a DAG expression to select that will generate the same value by
4206 /// multiplying by a magic number. See:
4207 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4208 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
4209 std::vector<SDNode*> Built;
4210 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
4212 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4218 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
4219 /// return a DAG expression to select that will generate the same value by
4220 /// multiplying by a magic number. See:
4221 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4222 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
4223 std::vector<SDNode*> Built;
4224 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
4226 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4232 /// FindBaseOffset - Return true if base is known not to alias with anything
4233 /// but itself. Provides base object and offset as results.
4234 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
4235 // Assume it is a primitive operation.
4236 Base = Ptr; Offset = 0;
4238 // If it's an adding a simple constant then integrate the offset.
4239 if (Base.getOpcode() == ISD::ADD) {
4240 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
4241 Base = Base.getOperand(0);
4242 Offset += C->getValue();
4246 // If it's any of the following then it can't alias with anything but itself.
4247 return isa<FrameIndexSDNode>(Base) ||
4248 isa<ConstantPoolSDNode>(Base) ||
4249 isa<GlobalAddressSDNode>(Base);
4252 /// isAlias - Return true if there is any possibility that the two addresses
4254 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
4255 const Value *SrcValue1, int SrcValueOffset1,
4256 SDOperand Ptr2, int64_t Size2,
4257 const Value *SrcValue2, int SrcValueOffset2)
4259 // If they are the same then they must be aliases.
4260 if (Ptr1 == Ptr2) return true;
4262 // Gather base node and offset information.
4263 SDOperand Base1, Base2;
4264 int64_t Offset1, Offset2;
4265 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
4266 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
4268 // If they have a same base address then...
4269 if (Base1 == Base2) {
4270 // Check to see if the addresses overlap.
4271 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
4274 // If we know both bases then they can't alias.
4275 if (KnownBase1 && KnownBase2) return false;
4277 if (CombinerGlobalAA) {
4278 // Use alias analysis information.
4279 int Overlap1 = Size1 + SrcValueOffset1 + Offset1;
4280 int Overlap2 = Size2 + SrcValueOffset2 + Offset2;
4281 AliasAnalysis::AliasResult AAResult =
4282 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
4283 if (AAResult == AliasAnalysis::NoAlias)
4287 // Otherwise we have to assume they alias.
4291 /// FindAliasInfo - Extracts the relevant alias information from the memory
4292 /// node. Returns true if the operand was a load.
4293 bool DAGCombiner::FindAliasInfo(SDNode *N,
4294 SDOperand &Ptr, int64_t &Size,
4295 const Value *&SrcValue, int &SrcValueOffset) {
4296 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4297 Ptr = LD->getBasePtr();
4298 Size = MVT::getSizeInBits(LD->getLoadedVT()) >> 3;
4299 SrcValue = LD->getSrcValue();
4300 SrcValueOffset = LD->getSrcValueOffset();
4302 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4303 Ptr = ST->getBasePtr();
4304 Size = MVT::getSizeInBits(ST->getStoredVT()) >> 3;
4305 SrcValue = ST->getSrcValue();
4306 SrcValueOffset = ST->getSrcValueOffset();
4308 assert(0 && "FindAliasInfo expected a memory operand");
4314 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
4315 /// looking for aliasing nodes and adding them to the Aliases vector.
4316 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
4317 SmallVector<SDOperand, 8> &Aliases) {
4318 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
4319 std::set<SDNode *> Visited; // Visited node set.
4321 // Get alias information for node.
4324 const Value *SrcValue;
4326 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
4329 Chains.push_back(OriginalChain);
4331 // Look at each chain and determine if it is an alias. If so, add it to the
4332 // aliases list. If not, then continue up the chain looking for the next
4334 while (!Chains.empty()) {
4335 SDOperand Chain = Chains.back();
4338 // Don't bother if we've been before.
4339 if (Visited.find(Chain.Val) != Visited.end()) continue;
4340 Visited.insert(Chain.Val);
4342 switch (Chain.getOpcode()) {
4343 case ISD::EntryToken:
4344 // Entry token is ideal chain operand, but handled in FindBetterChain.
4349 // Get alias information for Chain.
4352 const Value *OpSrcValue;
4353 int OpSrcValueOffset;
4354 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
4355 OpSrcValue, OpSrcValueOffset);
4357 // If chain is alias then stop here.
4358 if (!(IsLoad && IsOpLoad) &&
4359 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
4360 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
4361 Aliases.push_back(Chain);
4363 // Look further up the chain.
4364 Chains.push_back(Chain.getOperand(0));
4365 // Clean up old chain.
4366 AddToWorkList(Chain.Val);
4371 case ISD::TokenFactor:
4372 // We have to check each of the operands of the token factor, so we queue
4373 // then up. Adding the operands to the queue (stack) in reverse order
4374 // maintains the original order and increases the likelihood that getNode
4375 // will find a matching token factor (CSE.)
4376 for (unsigned n = Chain.getNumOperands(); n;)
4377 Chains.push_back(Chain.getOperand(--n));
4378 // Eliminate the token factor if we can.
4379 AddToWorkList(Chain.Val);
4383 // For all other instructions we will just have to take what we can get.
4384 Aliases.push_back(Chain);
4390 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
4391 /// for a better chain (aliasing node.)
4392 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
4393 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
4395 // Accumulate all the aliases to this node.
4396 GatherAllAliases(N, OldChain, Aliases);
4398 if (Aliases.size() == 0) {
4399 // If no operands then chain to entry token.
4400 return DAG.getEntryNode();
4401 } else if (Aliases.size() == 1) {
4402 // If a single operand then chain to it. We don't need to revisit it.
4406 // Construct a custom tailored token factor.
4407 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4408 &Aliases[0], Aliases.size());
4410 // Make sure the old chain gets cleaned up.
4411 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
4416 // SelectionDAG::Combine - This is the entry point for the file.
4418 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
4419 /// run - This is the main entry point to this class.
4421 DAGCombiner(*this, AA).Run(RunningAfterLegalize);