Move isCommutativeBinOp from SelectionDAG.cpp and DAGCombiner.cpp out. Make it a...
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
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.
18 //
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: make truncate see through SIGN_EXTEND and AND
26 // FIXME: divide by zero is currently left unfolded.  do we want to turn this
27 //        into an undef?
28 // FIXME: select ne (select cc, 1, 0), 0, true, false -> select cc, true, false
29 // 
30 //===----------------------------------------------------------------------===//
31
32 #define DEBUG_TYPE "dagcombine"
33 #include "llvm/ADT/Statistic.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 <algorithm>
40 #include <cmath>
41 #include <iostream>
42 using namespace llvm;
43
44 namespace {
45   static Statistic<> NodesCombined ("dagcombiner", 
46                                     "Number of dag nodes combined");
47
48   class VISIBILITY_HIDDEN DAGCombiner {
49     SelectionDAG &DAG;
50     TargetLowering &TLI;
51     bool AfterLegalize;
52
53     // Worklist of all of the nodes that need to be simplified.
54     std::vector<SDNode*> WorkList;
55
56     /// AddUsersToWorkList - When an instruction is simplified, add all users of
57     /// the instruction to the work lists because they might get more simplified
58     /// now.
59     ///
60     void AddUsersToWorkList(SDNode *N) {
61       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
62            UI != UE; ++UI)
63         WorkList.push_back(*UI);
64     }
65
66     /// removeFromWorkList - remove all instances of N from the worklist.
67     ///
68     void removeFromWorkList(SDNode *N) {
69       WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
70                      WorkList.end());
71     }
72     
73   public:
74     void AddToWorkList(SDNode *N) {
75       WorkList.push_back(N);
76     }
77     
78     SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo) {
79       assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
80       ++NodesCombined;
81       DEBUG(std::cerr << "\nReplacing "; N->dump();
82             std::cerr << "\nWith: "; To[0].Val->dump(&DAG);
83             std::cerr << " and " << NumTo-1 << " other values\n");
84       std::vector<SDNode*> NowDead;
85       DAG.ReplaceAllUsesWith(N, To, &NowDead);
86       
87       // Push the new nodes and any users onto the worklist
88       for (unsigned i = 0, e = NumTo; i != e; ++i) {
89         WorkList.push_back(To[i].Val);
90         AddUsersToWorkList(To[i].Val);
91       }
92       
93       // Nodes can end up on the worklist more than once.  Make sure we do
94       // not process a node that has been replaced.
95       removeFromWorkList(N);
96       for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
97         removeFromWorkList(NowDead[i]);
98       
99       // Finally, since the node is now dead, remove it from the graph.
100       DAG.DeleteNode(N);
101       return SDOperand(N, 0);
102     }
103     
104     SDOperand CombineTo(SDNode *N, SDOperand Res) {
105       return CombineTo(N, &Res, 1);
106     }
107     
108     SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
109       SDOperand To[] = { Res0, Res1 };
110       return CombineTo(N, To, 2);
111     }
112   private:    
113     
114     /// SimplifyDemandedBits - Check the specified integer node value to see if
115     /// it can be simplified or if things it uses can be simplified by bit
116     /// propagation.  If so, return true.
117     bool SimplifyDemandedBits(SDOperand Op) {
118       TargetLowering::TargetLoweringOpt TLO(DAG);
119       uint64_t KnownZero, KnownOne;
120       uint64_t Demanded = MVT::getIntVTBitMask(Op.getValueType());
121       if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
122         return false;
123
124       // Revisit the node.
125       WorkList.push_back(Op.Val);
126       
127       // Replace the old value with the new one.
128       ++NodesCombined;
129       DEBUG(std::cerr << "\nReplacing "; TLO.Old.Val->dump();
130             std::cerr << "\nWith: "; TLO.New.Val->dump(&DAG));
131
132       std::vector<SDNode*> NowDead;
133       DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, NowDead);
134       
135       // Push the new node and any (possibly new) users onto the worklist.
136       WorkList.push_back(TLO.New.Val);
137       AddUsersToWorkList(TLO.New.Val);
138       
139       // Nodes can end up on the worklist more than once.  Make sure we do
140       // not process a node that has been replaced.
141       for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
142         removeFromWorkList(NowDead[i]);
143       
144       // Finally, if the node is now dead, remove it from the graph.  The node
145       // may not be dead if the replacement process recursively simplified to
146       // something else needing this node.
147       if (TLO.Old.Val->use_empty()) {
148         removeFromWorkList(TLO.Old.Val);
149         DAG.DeleteNode(TLO.Old.Val);
150       }
151       return true;
152     }
153
154     /// visit - call the node-specific routine that knows how to fold each
155     /// particular type of node.
156     SDOperand visit(SDNode *N);
157
158     // Visitation implementation - Implement dag node combining for different
159     // node types.  The semantics are as follows:
160     // Return Value:
161     //   SDOperand.Val == 0   - No change was made
162     //   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
163     //   otherwise            - N should be replaced by the returned Operand.
164     //
165     SDOperand visitTokenFactor(SDNode *N);
166     SDOperand visitADD(SDNode *N);
167     SDOperand visitSUB(SDNode *N);
168     SDOperand visitMUL(SDNode *N);
169     SDOperand visitSDIV(SDNode *N);
170     SDOperand visitUDIV(SDNode *N);
171     SDOperand visitSREM(SDNode *N);
172     SDOperand visitUREM(SDNode *N);
173     SDOperand visitMULHU(SDNode *N);
174     SDOperand visitMULHS(SDNode *N);
175     SDOperand visitAND(SDNode *N);
176     SDOperand visitOR(SDNode *N);
177     SDOperand visitXOR(SDNode *N);
178     SDOperand visitVBinOp(SDNode *N, ISD::NodeType IntOp, ISD::NodeType FPOp);
179     SDOperand visitSHL(SDNode *N);
180     SDOperand visitSRA(SDNode *N);
181     SDOperand visitSRL(SDNode *N);
182     SDOperand visitCTLZ(SDNode *N);
183     SDOperand visitCTTZ(SDNode *N);
184     SDOperand visitCTPOP(SDNode *N);
185     SDOperand visitSELECT(SDNode *N);
186     SDOperand visitSELECT_CC(SDNode *N);
187     SDOperand visitSETCC(SDNode *N);
188     SDOperand visitSIGN_EXTEND(SDNode *N);
189     SDOperand visitZERO_EXTEND(SDNode *N);
190     SDOperand visitANY_EXTEND(SDNode *N);
191     SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
192     SDOperand visitTRUNCATE(SDNode *N);
193     SDOperand visitBIT_CONVERT(SDNode *N);
194     SDOperand visitVBIT_CONVERT(SDNode *N);
195     SDOperand visitFADD(SDNode *N);
196     SDOperand visitFSUB(SDNode *N);
197     SDOperand visitFMUL(SDNode *N);
198     SDOperand visitFDIV(SDNode *N);
199     SDOperand visitFREM(SDNode *N);
200     SDOperand visitFCOPYSIGN(SDNode *N);
201     SDOperand visitSINT_TO_FP(SDNode *N);
202     SDOperand visitUINT_TO_FP(SDNode *N);
203     SDOperand visitFP_TO_SINT(SDNode *N);
204     SDOperand visitFP_TO_UINT(SDNode *N);
205     SDOperand visitFP_ROUND(SDNode *N);
206     SDOperand visitFP_ROUND_INREG(SDNode *N);
207     SDOperand visitFP_EXTEND(SDNode *N);
208     SDOperand visitFNEG(SDNode *N);
209     SDOperand visitFABS(SDNode *N);
210     SDOperand visitBRCOND(SDNode *N);
211     SDOperand visitBR_CC(SDNode *N);
212     SDOperand visitLOAD(SDNode *N);
213     SDOperand visitXEXTLOAD(SDNode *N);
214     SDOperand visitSTORE(SDNode *N);
215     SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
216     SDOperand visitVINSERT_VECTOR_ELT(SDNode *N);
217     SDOperand visitVBUILD_VECTOR(SDNode *N);
218     SDOperand visitVECTOR_SHUFFLE(SDNode *N);
219     SDOperand visitVVECTOR_SHUFFLE(SDNode *N);
220
221     SDOperand XformToShuffleWithZero(SDNode *N);
222     SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
223     
224     bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
225     SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
226     SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
227     SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2, 
228                                SDOperand N3, ISD::CondCode CC);
229     SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
230                             ISD::CondCode Cond, bool foldBooleans = true);
231     SDOperand ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(SDNode *, MVT::ValueType);
232     SDOperand BuildSDIV(SDNode *N);
233     SDOperand BuildUDIV(SDNode *N);    
234 public:
235     DAGCombiner(SelectionDAG &D)
236       : DAG(D), TLI(D.getTargetLoweringInfo()), AfterLegalize(false) {}
237     
238     /// Run - runs the dag combiner on all nodes in the work list
239     void Run(bool RunningAfterLegalize); 
240   };
241 }
242
243 //===----------------------------------------------------------------------===//
244 //  TargetLowering::DAGCombinerInfo implementation
245 //===----------------------------------------------------------------------===//
246
247 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
248   ((DAGCombiner*)DC)->AddToWorkList(N);
249 }
250
251 SDOperand TargetLowering::DAGCombinerInfo::
252 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
253   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
254 }
255
256 SDOperand TargetLowering::DAGCombinerInfo::
257 CombineTo(SDNode *N, SDOperand Res) {
258   return ((DAGCombiner*)DC)->CombineTo(N, Res);
259 }
260
261
262 SDOperand TargetLowering::DAGCombinerInfo::
263 CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
264   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
265 }
266
267
268
269
270 //===----------------------------------------------------------------------===//
271
272
273 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
274 // that selects between the values 1 and 0, making it equivalent to a setcc.
275 // Also, set the incoming LHS, RHS, and CC references to the appropriate 
276 // nodes based on the type of node we are checking.  This simplifies life a
277 // bit for the callers.
278 static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
279                               SDOperand &CC) {
280   if (N.getOpcode() == ISD::SETCC) {
281     LHS = N.getOperand(0);
282     RHS = N.getOperand(1);
283     CC  = N.getOperand(2);
284     return true;
285   }
286   if (N.getOpcode() == ISD::SELECT_CC && 
287       N.getOperand(2).getOpcode() == ISD::Constant &&
288       N.getOperand(3).getOpcode() == ISD::Constant &&
289       cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
290       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
291     LHS = N.getOperand(0);
292     RHS = N.getOperand(1);
293     CC  = N.getOperand(4);
294     return true;
295   }
296   return false;
297 }
298
299 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
300 // one use.  If this is true, it allows the users to invert the operation for
301 // free when it is profitable to do so.
302 static bool isOneUseSetCC(SDOperand N) {
303   SDOperand N0, N1, N2;
304   if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
305     return true;
306   return false;
307 }
308
309 SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
310   MVT::ValueType VT = N0.getValueType();
311   // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
312   // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
313   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
314     if (isa<ConstantSDNode>(N1)) {
315       SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
316       AddToWorkList(OpNode.Val);
317       return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
318     } else if (N0.hasOneUse()) {
319       SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
320       AddToWorkList(OpNode.Val);
321       return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
322     }
323   }
324   // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
325   // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
326   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
327     if (isa<ConstantSDNode>(N0)) {
328       SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
329       AddToWorkList(OpNode.Val);
330       return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
331     } else if (N1.hasOneUse()) {
332       SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
333       AddToWorkList(OpNode.Val);
334       return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
335     }
336   }
337   return SDOperand();
338 }
339
340 void DAGCombiner::Run(bool RunningAfterLegalize) {
341   // set the instance variable, so that the various visit routines may use it.
342   AfterLegalize = RunningAfterLegalize;
343
344   // Add all the dag nodes to the worklist.
345   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
346        E = DAG.allnodes_end(); I != E; ++I)
347     WorkList.push_back(I);
348   
349   // Create a dummy node (which is not added to allnodes), that adds a reference
350   // to the root node, preventing it from being deleted, and tracking any
351   // changes of the root.
352   HandleSDNode Dummy(DAG.getRoot());
353   
354   
355   /// DagCombineInfo - Expose the DAG combiner to the target combiner impls.
356   TargetLowering::DAGCombinerInfo 
357     DagCombineInfo(DAG, !RunningAfterLegalize, this);
358   
359   // while the worklist isn't empty, inspect the node on the end of it and
360   // try and combine it.
361   while (!WorkList.empty()) {
362     SDNode *N = WorkList.back();
363     WorkList.pop_back();
364     
365     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
366     // N is deleted from the DAG, since they too may now be dead or may have a
367     // reduced number of uses, allowing other xforms.
368     if (N->use_empty() && N != &Dummy) {
369       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
370         WorkList.push_back(N->getOperand(i).Val);
371       
372       removeFromWorkList(N);
373       DAG.DeleteNode(N);
374       continue;
375     }
376     
377     SDOperand RV = visit(N);
378     
379     // If nothing happened, try a target-specific DAG combine.
380     if (RV.Val == 0) {
381       assert(N->getOpcode() != ISD::DELETED_NODE &&
382              "Node was deleted but visit returned NULL!");
383       if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
384           TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode()))
385         RV = TLI.PerformDAGCombine(N, DagCombineInfo);
386     }
387     
388     if (RV.Val) {
389       ++NodesCombined;
390       // If we get back the same node we passed in, rather than a new node or
391       // zero, we know that the node must have defined multiple values and
392       // CombineTo was used.  Since CombineTo takes care of the worklist 
393       // mechanics for us, we have no work to do in this case.
394       if (RV.Val != N) {
395         assert(N->getOpcode() != ISD::DELETED_NODE &&
396                RV.Val->getOpcode() != ISD::DELETED_NODE &&
397                "Node was deleted but visit returned new node!");
398
399         DEBUG(std::cerr << "\nReplacing "; N->dump();
400               std::cerr << "\nWith: "; RV.Val->dump(&DAG);
401               std::cerr << '\n');
402         std::vector<SDNode*> NowDead;
403         SDOperand OpV = RV;
404         DAG.ReplaceAllUsesWith(N, &OpV, &NowDead);
405           
406         // Push the new node and any users onto the worklist
407         WorkList.push_back(RV.Val);
408         AddUsersToWorkList(RV.Val);
409           
410         // Nodes can end up on the worklist more than once.  Make sure we do
411         // not process a node that has been replaced.
412         removeFromWorkList(N);
413         for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
414           removeFromWorkList(NowDead[i]);
415         
416         // Finally, since the node is now dead, remove it from the graph.
417         DAG.DeleteNode(N);
418       }
419     }
420   }
421   
422   // If the root changed (e.g. it was a dead load, update the root).
423   DAG.setRoot(Dummy.getValue());
424 }
425
426 SDOperand DAGCombiner::visit(SDNode *N) {
427   switch(N->getOpcode()) {
428   default: break;
429   case ISD::TokenFactor:        return visitTokenFactor(N);
430   case ISD::ADD:                return visitADD(N);
431   case ISD::SUB:                return visitSUB(N);
432   case ISD::MUL:                return visitMUL(N);
433   case ISD::SDIV:               return visitSDIV(N);
434   case ISD::UDIV:               return visitUDIV(N);
435   case ISD::SREM:               return visitSREM(N);
436   case ISD::UREM:               return visitUREM(N);
437   case ISD::MULHU:              return visitMULHU(N);
438   case ISD::MULHS:              return visitMULHS(N);
439   case ISD::AND:                return visitAND(N);
440   case ISD::OR:                 return visitOR(N);
441   case ISD::XOR:                return visitXOR(N);
442   case ISD::SHL:                return visitSHL(N);
443   case ISD::SRA:                return visitSRA(N);
444   case ISD::SRL:                return visitSRL(N);
445   case ISD::CTLZ:               return visitCTLZ(N);
446   case ISD::CTTZ:               return visitCTTZ(N);
447   case ISD::CTPOP:              return visitCTPOP(N);
448   case ISD::SELECT:             return visitSELECT(N);
449   case ISD::SELECT_CC:          return visitSELECT_CC(N);
450   case ISD::SETCC:              return visitSETCC(N);
451   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
452   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
453   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
454   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
455   case ISD::TRUNCATE:           return visitTRUNCATE(N);
456   case ISD::BIT_CONVERT:        return visitBIT_CONVERT(N);
457   case ISD::VBIT_CONVERT:       return visitVBIT_CONVERT(N);
458   case ISD::FADD:               return visitFADD(N);
459   case ISD::FSUB:               return visitFSUB(N);
460   case ISD::FMUL:               return visitFMUL(N);
461   case ISD::FDIV:               return visitFDIV(N);
462   case ISD::FREM:               return visitFREM(N);
463   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
464   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
465   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
466   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
467   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
468   case ISD::FP_ROUND:           return visitFP_ROUND(N);
469   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
470   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
471   case ISD::FNEG:               return visitFNEG(N);
472   case ISD::FABS:               return visitFABS(N);
473   case ISD::BRCOND:             return visitBRCOND(N);
474   case ISD::BR_CC:              return visitBR_CC(N);
475   case ISD::LOAD:               return visitLOAD(N);
476   case ISD::EXTLOAD:
477   case ISD::SEXTLOAD:
478   case ISD::ZEXTLOAD:           return visitXEXTLOAD(N);
479   case ISD::STORE:              return visitSTORE(N);
480   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
481   case ISD::VINSERT_VECTOR_ELT: return visitVINSERT_VECTOR_ELT(N);
482   case ISD::VBUILD_VECTOR:      return visitVBUILD_VECTOR(N);
483   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
484   case ISD::VVECTOR_SHUFFLE:    return visitVVECTOR_SHUFFLE(N);
485   case ISD::VADD:               return visitVBinOp(N, ISD::ADD , ISD::FADD);
486   case ISD::VSUB:               return visitVBinOp(N, ISD::SUB , ISD::FSUB);
487   case ISD::VMUL:               return visitVBinOp(N, ISD::MUL , ISD::FMUL);
488   case ISD::VSDIV:              return visitVBinOp(N, ISD::SDIV, ISD::FDIV);
489   case ISD::VUDIV:              return visitVBinOp(N, ISD::UDIV, ISD::UDIV);
490   case ISD::VAND:               return visitVBinOp(N, ISD::AND , ISD::AND);
491   case ISD::VOR:                return visitVBinOp(N, ISD::OR  , ISD::OR);
492   case ISD::VXOR:               return visitVBinOp(N, ISD::XOR , ISD::XOR);
493   }
494   return SDOperand();
495 }
496
497 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
498   SmallVector<SDOperand, 8> Ops;
499   bool Changed = false;
500
501   // If the token factor has two operands and one is the entry token, replace
502   // the token factor with the other operand.
503   if (N->getNumOperands() == 2) {
504     if (N->getOperand(0).getOpcode() == ISD::EntryToken ||
505         N->getOperand(0) == N->getOperand(1))
506       return N->getOperand(1);
507     if (N->getOperand(1).getOpcode() == ISD::EntryToken)
508       return N->getOperand(0);
509   }
510   
511   // fold (tokenfactor (tokenfactor)) -> tokenfactor
512   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
513     SDOperand Op = N->getOperand(i);
514     if (Op.getOpcode() == ISD::TokenFactor && Op.hasOneUse()) {
515       AddToWorkList(Op.Val);  // Remove dead node.
516       Changed = true;
517       for (unsigned j = 0, e = Op.getNumOperands(); j != e; ++j)
518         Ops.push_back(Op.getOperand(j));
519     } else if (i == 0 || N->getOperand(i) != N->getOperand(i-1)) {
520       Ops.push_back(Op);
521     } else {
522       // Deleted an operand that was the same as the last one.
523       Changed = true;
524     }
525   }
526   if (Changed)
527     return DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
528   return SDOperand();
529 }
530
531 SDOperand DAGCombiner::visitADD(SDNode *N) {
532   SDOperand N0 = N->getOperand(0);
533   SDOperand N1 = N->getOperand(1);
534   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
535   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
536   MVT::ValueType VT = N0.getValueType();
537   
538   // fold (add c1, c2) -> c1+c2
539   if (N0C && N1C)
540     return DAG.getNode(ISD::ADD, VT, N0, N1);
541   // canonicalize constant to RHS
542   if (N0C && !N1C)
543     return DAG.getNode(ISD::ADD, VT, N1, N0);
544   // fold (add x, 0) -> x
545   if (N1C && N1C->isNullValue())
546     return N0;
547   // fold ((c1-A)+c2) -> (c1+c2)-A
548   if (N1C && N0.getOpcode() == ISD::SUB)
549     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
550       return DAG.getNode(ISD::SUB, VT,
551                          DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
552                          N0.getOperand(1));
553   // reassociate add
554   SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
555   if (RADD.Val != 0)
556     return RADD;
557   // fold ((0-A) + B) -> B-A
558   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
559       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
560     return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
561   // fold (A + (0-B)) -> A-B
562   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
563       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
564     return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
565   // fold (A+(B-A)) -> B
566   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
567     return N1.getOperand(0);
568
569   if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
570     return SDOperand(N, 0);
571   
572   // fold (a+b) -> (a|b) iff a and b share no bits.
573   if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
574     uint64_t LHSZero, LHSOne;
575     uint64_t RHSZero, RHSOne;
576     uint64_t Mask = MVT::getIntVTBitMask(VT);
577     TLI.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
578     if (LHSZero) {
579       TLI.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
580       
581       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
582       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
583       if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
584           (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
585         return DAG.getNode(ISD::OR, VT, N0, N1);
586     }
587   }
588   
589   return SDOperand();
590 }
591
592 SDOperand DAGCombiner::visitSUB(SDNode *N) {
593   SDOperand N0 = N->getOperand(0);
594   SDOperand N1 = N->getOperand(1);
595   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
596   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
597   MVT::ValueType VT = N0.getValueType();
598   
599   // fold (sub x, x) -> 0
600   if (N0 == N1)
601     return DAG.getConstant(0, N->getValueType(0));
602   // fold (sub c1, c2) -> c1-c2
603   if (N0C && N1C)
604     return DAG.getNode(ISD::SUB, VT, N0, N1);
605   // fold (sub x, c) -> (add x, -c)
606   if (N1C)
607     return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
608   // fold (A+B)-A -> B
609   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
610     return N0.getOperand(1);
611   // fold (A+B)-B -> A
612   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
613     return N0.getOperand(0);
614   return SDOperand();
615 }
616
617 SDOperand DAGCombiner::visitMUL(SDNode *N) {
618   SDOperand N0 = N->getOperand(0);
619   SDOperand N1 = N->getOperand(1);
620   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
621   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
622   MVT::ValueType VT = N0.getValueType();
623   
624   // fold (mul c1, c2) -> c1*c2
625   if (N0C && N1C)
626     return DAG.getNode(ISD::MUL, VT, N0, N1);
627   // canonicalize constant to RHS
628   if (N0C && !N1C)
629     return DAG.getNode(ISD::MUL, VT, N1, N0);
630   // fold (mul x, 0) -> 0
631   if (N1C && N1C->isNullValue())
632     return N1;
633   // fold (mul x, -1) -> 0-x
634   if (N1C && N1C->isAllOnesValue())
635     return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
636   // fold (mul x, (1 << c)) -> x << c
637   if (N1C && isPowerOf2_64(N1C->getValue()))
638     return DAG.getNode(ISD::SHL, VT, N0,
639                        DAG.getConstant(Log2_64(N1C->getValue()),
640                                        TLI.getShiftAmountTy()));
641   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
642   if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
643     // FIXME: If the input is something that is easily negated (e.g. a 
644     // single-use add), we should put the negate there.
645     return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
646                        DAG.getNode(ISD::SHL, VT, N0,
647                             DAG.getConstant(Log2_64(-N1C->getSignExtended()),
648                                             TLI.getShiftAmountTy())));
649   }
650
651   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
652   if (N1C && N0.getOpcode() == ISD::SHL && 
653       isa<ConstantSDNode>(N0.getOperand(1))) {
654     SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
655     AddToWorkList(C3.Val);
656     return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
657   }
658   
659   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
660   // use.
661   {
662     SDOperand Sh(0,0), Y(0,0);
663     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
664     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
665         N0.Val->hasOneUse()) {
666       Sh = N0; Y = N1;
667     } else if (N1.getOpcode() == ISD::SHL && 
668                isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
669       Sh = N1; Y = N0;
670     }
671     if (Sh.Val) {
672       SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
673       return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
674     }
675   }
676   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
677   if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() && 
678       isa<ConstantSDNode>(N0.getOperand(1))) {
679     return DAG.getNode(ISD::ADD, VT, 
680                        DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
681                        DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
682   }
683   
684   // reassociate mul
685   SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
686   if (RMUL.Val != 0)
687     return RMUL;
688   return SDOperand();
689 }
690
691 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
692   SDOperand N0 = N->getOperand(0);
693   SDOperand N1 = N->getOperand(1);
694   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
695   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
696   MVT::ValueType VT = N->getValueType(0);
697
698   // fold (sdiv c1, c2) -> c1/c2
699   if (N0C && N1C && !N1C->isNullValue())
700     return DAG.getNode(ISD::SDIV, VT, N0, N1);
701   // fold (sdiv X, 1) -> X
702   if (N1C && N1C->getSignExtended() == 1LL)
703     return N0;
704   // fold (sdiv X, -1) -> 0-X
705   if (N1C && N1C->isAllOnesValue())
706     return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
707   // If we know the sign bits of both operands are zero, strength reduce to a
708   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
709   uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
710   if (TLI.MaskedValueIsZero(N1, SignBit) &&
711       TLI.MaskedValueIsZero(N0, SignBit))
712     return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
713   // fold (sdiv X, pow2) -> simple ops after legalize
714   if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
715       (isPowerOf2_64(N1C->getSignExtended()) || 
716        isPowerOf2_64(-N1C->getSignExtended()))) {
717     // If dividing by powers of two is cheap, then don't perform the following
718     // fold.
719     if (TLI.isPow2DivCheap())
720       return SDOperand();
721     int64_t pow2 = N1C->getSignExtended();
722     int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
723     unsigned lg2 = Log2_64(abs2);
724     // Splat the sign bit into the register
725     SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
726                                 DAG.getConstant(MVT::getSizeInBits(VT)-1,
727                                                 TLI.getShiftAmountTy()));
728     AddToWorkList(SGN.Val);
729     // Add (N0 < 0) ? abs2 - 1 : 0;
730     SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
731                                 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
732                                                 TLI.getShiftAmountTy()));
733     SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
734     AddToWorkList(SRL.Val);
735     AddToWorkList(ADD.Val);    // Divide by pow2
736     SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
737                                 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
738     // If we're dividing by a positive value, we're done.  Otherwise, we must
739     // negate the result.
740     if (pow2 > 0)
741       return SRA;
742     AddToWorkList(SRA.Val);
743     return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
744   }
745   // if integer divide is expensive and we satisfy the requirements, emit an
746   // alternate sequence.
747   if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) && 
748       !TLI.isIntDivCheap()) {
749     SDOperand Op = BuildSDIV(N);
750     if (Op.Val) return Op;
751   }
752   return SDOperand();
753 }
754
755 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
756   SDOperand N0 = N->getOperand(0);
757   SDOperand N1 = N->getOperand(1);
758   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
759   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
760   MVT::ValueType VT = N->getValueType(0);
761   
762   // fold (udiv c1, c2) -> c1/c2
763   if (N0C && N1C && !N1C->isNullValue())
764     return DAG.getNode(ISD::UDIV, VT, N0, N1);
765   // fold (udiv x, (1 << c)) -> x >>u c
766   if (N1C && isPowerOf2_64(N1C->getValue()))
767     return DAG.getNode(ISD::SRL, VT, N0, 
768                        DAG.getConstant(Log2_64(N1C->getValue()),
769                                        TLI.getShiftAmountTy()));
770   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
771   if (N1.getOpcode() == ISD::SHL) {
772     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
773       if (isPowerOf2_64(SHC->getValue())) {
774         MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
775         SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
776                                     DAG.getConstant(Log2_64(SHC->getValue()),
777                                                     ADDVT));
778         AddToWorkList(Add.Val);
779         return DAG.getNode(ISD::SRL, VT, N0, Add);
780       }
781     }
782   }
783   // fold (udiv x, c) -> alternate
784   if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
785     SDOperand Op = BuildUDIV(N);
786     if (Op.Val) return Op;
787   }
788   return SDOperand();
789 }
790
791 SDOperand DAGCombiner::visitSREM(SDNode *N) {
792   SDOperand N0 = N->getOperand(0);
793   SDOperand N1 = N->getOperand(1);
794   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
795   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
796   MVT::ValueType VT = N->getValueType(0);
797   
798   // fold (srem c1, c2) -> c1%c2
799   if (N0C && N1C && !N1C->isNullValue())
800     return DAG.getNode(ISD::SREM, VT, N0, N1);
801   // If we know the sign bits of both operands are zero, strength reduce to a
802   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
803   uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
804   if (TLI.MaskedValueIsZero(N1, SignBit) &&
805       TLI.MaskedValueIsZero(N0, SignBit))
806     return DAG.getNode(ISD::UREM, VT, N0, N1);
807   return SDOperand();
808 }
809
810 SDOperand DAGCombiner::visitUREM(SDNode *N) {
811   SDOperand N0 = N->getOperand(0);
812   SDOperand N1 = N->getOperand(1);
813   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
814   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
815   MVT::ValueType VT = N->getValueType(0);
816   
817   // fold (urem c1, c2) -> c1%c2
818   if (N0C && N1C && !N1C->isNullValue())
819     return DAG.getNode(ISD::UREM, VT, N0, N1);
820   // fold (urem x, pow2) -> (and x, pow2-1)
821   if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
822     return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
823   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
824   if (N1.getOpcode() == ISD::SHL) {
825     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
826       if (isPowerOf2_64(SHC->getValue())) {
827         SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
828         AddToWorkList(Add.Val);
829         return DAG.getNode(ISD::AND, VT, N0, Add);
830       }
831     }
832   }
833   return SDOperand();
834 }
835
836 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
837   SDOperand N0 = N->getOperand(0);
838   SDOperand N1 = N->getOperand(1);
839   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
840   
841   // fold (mulhs x, 0) -> 0
842   if (N1C && N1C->isNullValue())
843     return N1;
844   // fold (mulhs x, 1) -> (sra x, size(x)-1)
845   if (N1C && N1C->getValue() == 1)
846     return DAG.getNode(ISD::SRA, N0.getValueType(), N0, 
847                        DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
848                                        TLI.getShiftAmountTy()));
849   return SDOperand();
850 }
851
852 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
853   SDOperand N0 = N->getOperand(0);
854   SDOperand N1 = N->getOperand(1);
855   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
856   
857   // fold (mulhu x, 0) -> 0
858   if (N1C && N1C->isNullValue())
859     return N1;
860   // fold (mulhu x, 1) -> 0
861   if (N1C && N1C->getValue() == 1)
862     return DAG.getConstant(0, N0.getValueType());
863   return SDOperand();
864 }
865
866 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
867 /// two operands of the same opcode, try to simplify it.
868 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
869   SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
870   MVT::ValueType VT = N0.getValueType();
871   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
872   
873   // For each of OP in AND/OR/XOR:
874   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
875   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
876   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
877   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
878   if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
879        N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
880       N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
881     SDOperand ORNode = DAG.getNode(N->getOpcode(), 
882                                    N0.getOperand(0).getValueType(),
883                                    N0.getOperand(0), N1.getOperand(0));
884     AddToWorkList(ORNode.Val);
885     return DAG.getNode(N0.getOpcode(), VT, ORNode);
886   }
887   
888   // For each of OP in SHL/SRL/SRA/AND...
889   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
890   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
891   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
892   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
893        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
894       N0.getOperand(1) == N1.getOperand(1)) {
895     SDOperand ORNode = DAG.getNode(N->getOpcode(),
896                                    N0.getOperand(0).getValueType(),
897                                    N0.getOperand(0), N1.getOperand(0));
898     AddToWorkList(ORNode.Val);
899     return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
900   }
901   
902   return SDOperand();
903 }
904
905 SDOperand DAGCombiner::visitAND(SDNode *N) {
906   SDOperand N0 = N->getOperand(0);
907   SDOperand N1 = N->getOperand(1);
908   SDOperand LL, LR, RL, RR, CC0, CC1;
909   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
910   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
911   MVT::ValueType VT = N1.getValueType();
912   unsigned OpSizeInBits = MVT::getSizeInBits(VT);
913   
914   // fold (and c1, c2) -> c1&c2
915   if (N0C && N1C)
916     return DAG.getNode(ISD::AND, VT, N0, N1);
917   // canonicalize constant to RHS
918   if (N0C && !N1C)
919     return DAG.getNode(ISD::AND, VT, N1, N0);
920   // fold (and x, -1) -> x
921   if (N1C && N1C->isAllOnesValue())
922     return N0;
923   // if (and x, c) is known to be zero, return 0
924   if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
925     return DAG.getConstant(0, VT);
926   // reassociate and
927   SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
928   if (RAND.Val != 0)
929     return RAND;
930   // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
931   if (N1C && N0.getOpcode() == ISD::OR)
932     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
933       if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
934         return N1;
935   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
936   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
937     unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
938     if (TLI.MaskedValueIsZero(N0.getOperand(0),
939                               ~N1C->getValue() & InMask)) {
940       SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
941                                    N0.getOperand(0));
942       
943       // Replace uses of the AND with uses of the Zero extend node.
944       CombineTo(N, Zext);
945       
946       // We actually want to replace all uses of the any_extend with the
947       // zero_extend, to avoid duplicating things.  This will later cause this
948       // AND to be folded.
949       CombineTo(N0.Val, Zext);
950       return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
951     }
952   }
953   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
954   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
955     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
956     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
957     
958     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
959         MVT::isInteger(LL.getValueType())) {
960       // fold (X == 0) & (Y == 0) -> (X|Y == 0)
961       if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
962         SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
963         AddToWorkList(ORNode.Val);
964         return DAG.getSetCC(VT, ORNode, LR, Op1);
965       }
966       // fold (X == -1) & (Y == -1) -> (X&Y == -1)
967       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
968         SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
969         AddToWorkList(ANDNode.Val);
970         return DAG.getSetCC(VT, ANDNode, LR, Op1);
971       }
972       // fold (X >  -1) & (Y >  -1) -> (X|Y > -1)
973       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
974         SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
975         AddToWorkList(ORNode.Val);
976         return DAG.getSetCC(VT, ORNode, LR, Op1);
977       }
978     }
979     // canonicalize equivalent to ll == rl
980     if (LL == RR && LR == RL) {
981       Op1 = ISD::getSetCCSwappedOperands(Op1);
982       std::swap(RL, RR);
983     }
984     if (LL == RL && LR == RR) {
985       bool isInteger = MVT::isInteger(LL.getValueType());
986       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
987       if (Result != ISD::SETCC_INVALID)
988         return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
989     }
990   }
991
992   // Simplify: and (op x...), (op y...)  -> (op (and x, y))
993   if (N0.getOpcode() == N1.getOpcode()) {
994     SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
995     if (Tmp.Val) return Tmp;
996   }
997   
998   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
999   // fold (and (sra)) -> (and (srl)) when possible.
1000   if (!MVT::isVector(VT) &&
1001       SimplifyDemandedBits(SDOperand(N, 0)))
1002     return SDOperand(N, 0);
1003   // fold (zext_inreg (extload x)) -> (zextload x)
1004   if (N0.getOpcode() == ISD::EXTLOAD) {
1005     MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1006     // If we zero all the possible extended bits, then we can turn this into
1007     // a zextload if we are running before legalize or the operation is legal.
1008     if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1009         (!AfterLegalize || TLI.isOperationLegal(ISD::ZEXTLOAD, EVT))) {
1010       SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1011                                          N0.getOperand(1), N0.getOperand(2),
1012                                          EVT);
1013       AddToWorkList(N);
1014       CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1015       return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1016     }
1017   }
1018   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1019   if (N0.getOpcode() == ISD::SEXTLOAD && N0.hasOneUse()) {
1020     MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1021     // If we zero all the possible extended bits, then we can turn this into
1022     // a zextload if we are running before legalize or the operation is legal.
1023     if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1024         (!AfterLegalize || TLI.isOperationLegal(ISD::ZEXTLOAD, EVT))) {
1025       SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1026                                          N0.getOperand(1), N0.getOperand(2),
1027                                          EVT);
1028       AddToWorkList(N);
1029       CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1030       return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1031     }
1032   }
1033   
1034   // fold (and (load x), 255) -> (zextload x, i8)
1035   // fold (and (extload x, i16), 255) -> (zextload x, i8)
1036   if (N1C &&
1037       (N0.getOpcode() == ISD::LOAD || N0.getOpcode() == ISD::EXTLOAD ||
1038        N0.getOpcode() == ISD::ZEXTLOAD) &&
1039       N0.hasOneUse()) {
1040     MVT::ValueType EVT, LoadedVT;
1041     if (N1C->getValue() == 255)
1042       EVT = MVT::i8;
1043     else if (N1C->getValue() == 65535)
1044       EVT = MVT::i16;
1045     else if (N1C->getValue() == ~0U)
1046       EVT = MVT::i32;
1047     else
1048       EVT = MVT::Other;
1049     
1050     LoadedVT = N0.getOpcode() == ISD::LOAD ? VT :
1051                            cast<VTSDNode>(N0.getOperand(3))->getVT();
1052     if (EVT != MVT::Other && LoadedVT > EVT &&
1053         (!AfterLegalize || TLI.isOperationLegal(ISD::ZEXTLOAD, EVT))) {
1054       MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1055       // For big endian targets, we need to add an offset to the pointer to load
1056       // the correct bytes.  For little endian systems, we merely need to read
1057       // fewer bytes from the same pointer.
1058       unsigned PtrOff =
1059         (MVT::getSizeInBits(LoadedVT) - MVT::getSizeInBits(EVT)) / 8;
1060       SDOperand NewPtr = N0.getOperand(1);
1061       if (!TLI.isLittleEndian())
1062         NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1063                              DAG.getConstant(PtrOff, PtrType));
1064       AddToWorkList(NewPtr.Val);
1065       SDOperand Load =
1066         DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0), NewPtr,
1067                        N0.getOperand(2), EVT);
1068       AddToWorkList(N);
1069       CombineTo(N0.Val, Load, Load.getValue(1));
1070       return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1071     }
1072   }
1073   
1074   return SDOperand();
1075 }
1076
1077 SDOperand DAGCombiner::visitOR(SDNode *N) {
1078   SDOperand N0 = N->getOperand(0);
1079   SDOperand N1 = N->getOperand(1);
1080   SDOperand LL, LR, RL, RR, CC0, CC1;
1081   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1082   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1083   MVT::ValueType VT = N1.getValueType();
1084   unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1085   
1086   // fold (or c1, c2) -> c1|c2
1087   if (N0C && N1C)
1088     return DAG.getNode(ISD::OR, VT, N0, N1);
1089   // canonicalize constant to RHS
1090   if (N0C && !N1C)
1091     return DAG.getNode(ISD::OR, VT, N1, N0);
1092   // fold (or x, 0) -> x
1093   if (N1C && N1C->isNullValue())
1094     return N0;
1095   // fold (or x, -1) -> -1
1096   if (N1C && N1C->isAllOnesValue())
1097     return N1;
1098   // fold (or x, c) -> c iff (x & ~c) == 0
1099   if (N1C && 
1100       TLI.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
1101     return N1;
1102   // reassociate or
1103   SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1104   if (ROR.Val != 0)
1105     return ROR;
1106   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1107   if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1108              isa<ConstantSDNode>(N0.getOperand(1))) {
1109     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1110     return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1111                                                  N1),
1112                        DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1113   }
1114   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1115   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1116     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1117     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1118     
1119     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1120         MVT::isInteger(LL.getValueType())) {
1121       // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1122       // fold (X <  0) | (Y <  0) -> (X|Y < 0)
1123       if (cast<ConstantSDNode>(LR)->getValue() == 0 && 
1124           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1125         SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1126         AddToWorkList(ORNode.Val);
1127         return DAG.getSetCC(VT, ORNode, LR, Op1);
1128       }
1129       // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1130       // fold (X >  -1) | (Y >  -1) -> (X&Y >  -1)
1131       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 
1132           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1133         SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1134         AddToWorkList(ANDNode.Val);
1135         return DAG.getSetCC(VT, ANDNode, LR, Op1);
1136       }
1137     }
1138     // canonicalize equivalent to ll == rl
1139     if (LL == RR && LR == RL) {
1140       Op1 = ISD::getSetCCSwappedOperands(Op1);
1141       std::swap(RL, RR);
1142     }
1143     if (LL == RL && LR == RR) {
1144       bool isInteger = MVT::isInteger(LL.getValueType());
1145       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1146       if (Result != ISD::SETCC_INVALID)
1147         return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1148     }
1149   }
1150   
1151   // Simplify: or (op x...), (op y...)  -> (op (or x, y))
1152   if (N0.getOpcode() == N1.getOpcode()) {
1153     SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1154     if (Tmp.Val) return Tmp;
1155   }
1156
1157   // canonicalize shl to left side in a shl/srl pair, to match rotate
1158   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
1159     std::swap(N0, N1);
1160   // check for rotl, rotr
1161   if (N0.getOpcode() == ISD::SHL && N1.getOpcode() == ISD::SRL &&
1162       N0.getOperand(0) == N1.getOperand(0) &&
1163       TLI.isOperationLegal(ISD::ROTL, VT) && TLI.isTypeLegal(VT)) {
1164     // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1165     if (N0.getOperand(1).getOpcode() == ISD::Constant &&
1166         N1.getOperand(1).getOpcode() == ISD::Constant) {
1167       uint64_t c1val = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1168       uint64_t c2val = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
1169       if ((c1val + c2val) == OpSizeInBits)
1170         return DAG.getNode(ISD::ROTL, VT, N0.getOperand(0), N0.getOperand(1));
1171     }
1172     // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
1173     if (N1.getOperand(1).getOpcode() == ISD::SUB &&
1174         N0.getOperand(1) == N1.getOperand(1).getOperand(1))
1175       if (ConstantSDNode *SUBC = 
1176           dyn_cast<ConstantSDNode>(N1.getOperand(1).getOperand(0)))
1177         if (SUBC->getValue() == OpSizeInBits)
1178           return DAG.getNode(ISD::ROTL, VT, N0.getOperand(0), N0.getOperand(1));
1179     // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
1180     if (N0.getOperand(1).getOpcode() == ISD::SUB &&
1181         N1.getOperand(1) == N0.getOperand(1).getOperand(1))
1182       if (ConstantSDNode *SUBC = 
1183           dyn_cast<ConstantSDNode>(N0.getOperand(1).getOperand(0)))
1184         if (SUBC->getValue() == OpSizeInBits) {
1185           if (TLI.isOperationLegal(ISD::ROTR, VT) && TLI.isTypeLegal(VT))
1186             return DAG.getNode(ISD::ROTR, VT, N0.getOperand(0), 
1187                                N1.getOperand(1));
1188           else
1189             return DAG.getNode(ISD::ROTL, VT, N0.getOperand(0),
1190                                N0.getOperand(1));
1191         }
1192   }
1193   return SDOperand();
1194 }
1195
1196 SDOperand DAGCombiner::visitXOR(SDNode *N) {
1197   SDOperand N0 = N->getOperand(0);
1198   SDOperand N1 = N->getOperand(1);
1199   SDOperand LHS, RHS, CC;
1200   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1201   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1202   MVT::ValueType VT = N0.getValueType();
1203   
1204   // fold (xor c1, c2) -> c1^c2
1205   if (N0C && N1C)
1206     return DAG.getNode(ISD::XOR, VT, N0, N1);
1207   // canonicalize constant to RHS
1208   if (N0C && !N1C)
1209     return DAG.getNode(ISD::XOR, VT, N1, N0);
1210   // fold (xor x, 0) -> x
1211   if (N1C && N1C->isNullValue())
1212     return N0;
1213   // reassociate xor
1214   SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
1215   if (RXOR.Val != 0)
1216     return RXOR;
1217   // fold !(x cc y) -> (x !cc y)
1218   if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
1219     bool isInt = MVT::isInteger(LHS.getValueType());
1220     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
1221                                                isInt);
1222     if (N0.getOpcode() == ISD::SETCC)
1223       return DAG.getSetCC(VT, LHS, RHS, NotCC);
1224     if (N0.getOpcode() == ISD::SELECT_CC)
1225       return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
1226     assert(0 && "Unhandled SetCC Equivalent!");
1227     abort();
1228   }
1229   // fold !(x or y) -> (!x and !y) iff x or y are setcc
1230   if (N1C && N1C->getValue() == 1 && 
1231       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1232     SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1233     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
1234       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1235       LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
1236       RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
1237       AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1238       return DAG.getNode(NewOpcode, VT, LHS, RHS);
1239     }
1240   }
1241   // fold !(x or y) -> (!x and !y) iff x or y are constants
1242   if (N1C && N1C->isAllOnesValue() && 
1243       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1244     SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1245     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
1246       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1247       LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
1248       RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
1249       AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1250       return DAG.getNode(NewOpcode, VT, LHS, RHS);
1251     }
1252   }
1253   // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
1254   if (N1C && N0.getOpcode() == ISD::XOR) {
1255     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
1256     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1257     if (N00C)
1258       return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
1259                          DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
1260     if (N01C)
1261       return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
1262                          DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
1263   }
1264   // fold (xor x, x) -> 0
1265   if (N0 == N1) {
1266     if (!MVT::isVector(VT)) {
1267       return DAG.getConstant(0, VT);
1268     } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1269       // Produce a vector of zeros.
1270       SDOperand El = DAG.getConstant(0, MVT::getVectorBaseType(VT));
1271       std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
1272       return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1273     }
1274   }
1275   
1276   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
1277   if (N0.getOpcode() == N1.getOpcode()) {
1278     SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1279     if (Tmp.Val) return Tmp;
1280   }
1281   
1282   // Simplify the expression using non-local knowledge.
1283   if (!MVT::isVector(VT) &&
1284       SimplifyDemandedBits(SDOperand(N, 0)))
1285     return SDOperand(N, 0);
1286   
1287   return SDOperand();
1288 }
1289
1290 SDOperand DAGCombiner::visitSHL(SDNode *N) {
1291   SDOperand N0 = N->getOperand(0);
1292   SDOperand N1 = N->getOperand(1);
1293   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1294   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1295   MVT::ValueType VT = N0.getValueType();
1296   unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1297   
1298   // fold (shl c1, c2) -> c1<<c2
1299   if (N0C && N1C)
1300     return DAG.getNode(ISD::SHL, VT, N0, N1);
1301   // fold (shl 0, x) -> 0
1302   if (N0C && N0C->isNullValue())
1303     return N0;
1304   // fold (shl x, c >= size(x)) -> undef
1305   if (N1C && N1C->getValue() >= OpSizeInBits)
1306     return DAG.getNode(ISD::UNDEF, VT);
1307   // fold (shl x, 0) -> x
1308   if (N1C && N1C->isNullValue())
1309     return N0;
1310   // if (shl x, c) is known to be zero, return 0
1311   if (TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1312     return DAG.getConstant(0, VT);
1313   if (SimplifyDemandedBits(SDOperand(N, 0)))
1314     return SDOperand(N, 0);
1315   // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
1316   if (N1C && N0.getOpcode() == ISD::SHL && 
1317       N0.getOperand(1).getOpcode() == ISD::Constant) {
1318     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1319     uint64_t c2 = N1C->getValue();
1320     if (c1 + c2 > OpSizeInBits)
1321       return DAG.getConstant(0, VT);
1322     return DAG.getNode(ISD::SHL, VT, N0.getOperand(0), 
1323                        DAG.getConstant(c1 + c2, N1.getValueType()));
1324   }
1325   // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
1326   //                               (srl (and x, -1 << c1), c1-c2)
1327   if (N1C && N0.getOpcode() == ISD::SRL && 
1328       N0.getOperand(1).getOpcode() == ISD::Constant) {
1329     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1330     uint64_t c2 = N1C->getValue();
1331     SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1332                                  DAG.getConstant(~0ULL << c1, VT));
1333     if (c2 > c1)
1334       return DAG.getNode(ISD::SHL, VT, Mask, 
1335                          DAG.getConstant(c2-c1, N1.getValueType()));
1336     else
1337       return DAG.getNode(ISD::SRL, VT, Mask, 
1338                          DAG.getConstant(c1-c2, N1.getValueType()));
1339   }
1340   // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
1341   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
1342     return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1343                        DAG.getConstant(~0ULL << N1C->getValue(), VT));
1344   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1<<c2)
1345   if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() && 
1346       isa<ConstantSDNode>(N0.getOperand(1))) {
1347     return DAG.getNode(ISD::ADD, VT, 
1348                        DAG.getNode(ISD::SHL, VT, N0.getOperand(0), N1),
1349                        DAG.getNode(ISD::SHL, VT, N0.getOperand(1), N1));
1350   }
1351   return SDOperand();
1352 }
1353
1354 SDOperand DAGCombiner::visitSRA(SDNode *N) {
1355   SDOperand N0 = N->getOperand(0);
1356   SDOperand N1 = N->getOperand(1);
1357   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1358   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1359   MVT::ValueType VT = N0.getValueType();
1360   
1361   // fold (sra c1, c2) -> c1>>c2
1362   if (N0C && N1C)
1363     return DAG.getNode(ISD::SRA, VT, N0, N1);
1364   // fold (sra 0, x) -> 0
1365   if (N0C && N0C->isNullValue())
1366     return N0;
1367   // fold (sra -1, x) -> -1
1368   if (N0C && N0C->isAllOnesValue())
1369     return N0;
1370   // fold (sra x, c >= size(x)) -> undef
1371   if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
1372     return DAG.getNode(ISD::UNDEF, VT);
1373   // fold (sra x, 0) -> x
1374   if (N1C && N1C->isNullValue())
1375     return N0;
1376   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
1377   // sext_inreg.
1378   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
1379     unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
1380     MVT::ValueType EVT;
1381     switch (LowBits) {
1382     default: EVT = MVT::Other; break;
1383     case  1: EVT = MVT::i1;    break;
1384     case  8: EVT = MVT::i8;    break;
1385     case 16: EVT = MVT::i16;   break;
1386     case 32: EVT = MVT::i32;   break;
1387     }
1388     if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
1389       return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
1390                          DAG.getValueType(EVT));
1391   }
1392   
1393   // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
1394   if (N1C && N0.getOpcode() == ISD::SRA) {
1395     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1396       unsigned Sum = N1C->getValue() + C1->getValue();
1397       if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
1398       return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
1399                          DAG.getConstant(Sum, N1C->getValueType(0)));
1400     }
1401   }
1402   
1403   // Simplify, based on bits shifted out of the LHS. 
1404   if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
1405     return SDOperand(N, 0);
1406   
1407   
1408   // If the sign bit is known to be zero, switch this to a SRL.
1409   if (TLI.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
1410     return DAG.getNode(ISD::SRL, VT, N0, N1);
1411   return SDOperand();
1412 }
1413
1414 SDOperand DAGCombiner::visitSRL(SDNode *N) {
1415   SDOperand N0 = N->getOperand(0);
1416   SDOperand N1 = N->getOperand(1);
1417   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1418   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1419   MVT::ValueType VT = N0.getValueType();
1420   unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1421   
1422   // fold (srl c1, c2) -> c1 >>u c2
1423   if (N0C && N1C)
1424     return DAG.getNode(ISD::SRL, VT, N0, N1);
1425   // fold (srl 0, x) -> 0
1426   if (N0C && N0C->isNullValue())
1427     return N0;
1428   // fold (srl x, c >= size(x)) -> undef
1429   if (N1C && N1C->getValue() >= OpSizeInBits)
1430     return DAG.getNode(ISD::UNDEF, VT);
1431   // fold (srl x, 0) -> x
1432   if (N1C && N1C->isNullValue())
1433     return N0;
1434   // if (srl x, c) is known to be zero, return 0
1435   if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
1436     return DAG.getConstant(0, VT);
1437   // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
1438   if (N1C && N0.getOpcode() == ISD::SRL && 
1439       N0.getOperand(1).getOpcode() == ISD::Constant) {
1440     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1441     uint64_t c2 = N1C->getValue();
1442     if (c1 + c2 > OpSizeInBits)
1443       return DAG.getConstant(0, VT);
1444     return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), 
1445                        DAG.getConstant(c1 + c2, N1.getValueType()));
1446   }
1447   
1448   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
1449   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1450     // Shifting in all undef bits?
1451     MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
1452     if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
1453       return DAG.getNode(ISD::UNDEF, VT);
1454
1455     SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
1456     AddToWorkList(SmallShift.Val);
1457     return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
1458   }
1459   
1460   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
1461   if (N1C && N0.getOpcode() == ISD::CTLZ && 
1462       N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
1463     uint64_t KnownZero, KnownOne, Mask = MVT::getIntVTBitMask(VT);
1464     TLI.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
1465     
1466     // If any of the input bits are KnownOne, then the input couldn't be all
1467     // zeros, thus the result of the srl will always be zero.
1468     if (KnownOne) return DAG.getConstant(0, VT);
1469     
1470     // If all of the bits input the to ctlz node are known to be zero, then
1471     // the result of the ctlz is "32" and the result of the shift is one.
1472     uint64_t UnknownBits = ~KnownZero & Mask;
1473     if (UnknownBits == 0) return DAG.getConstant(1, VT);
1474     
1475     // Otherwise, check to see if there is exactly one bit input to the ctlz.
1476     if ((UnknownBits & (UnknownBits-1)) == 0) {
1477       // Okay, we know that only that the single bit specified by UnknownBits
1478       // could be set on input to the CTLZ node.  If this bit is set, the SRL
1479       // will return 0, if it is clear, it returns 1.  Change the CTLZ/SRL pair
1480       // to an SRL,XOR pair, which is likely to simplify more.
1481       unsigned ShAmt = CountTrailingZeros_64(UnknownBits);
1482       SDOperand Op = N0.getOperand(0);
1483       if (ShAmt) {
1484         Op = DAG.getNode(ISD::SRL, VT, Op,
1485                          DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
1486         AddToWorkList(Op.Val);
1487       }
1488       return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
1489     }
1490   }
1491   
1492   return SDOperand();
1493 }
1494
1495 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
1496   SDOperand N0 = N->getOperand(0);
1497   MVT::ValueType VT = N->getValueType(0);
1498
1499   // fold (ctlz c1) -> c2
1500   if (isa<ConstantSDNode>(N0))
1501     return DAG.getNode(ISD::CTLZ, VT, N0);
1502   return SDOperand();
1503 }
1504
1505 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
1506   SDOperand N0 = N->getOperand(0);
1507   MVT::ValueType VT = N->getValueType(0);
1508   
1509   // fold (cttz c1) -> c2
1510   if (isa<ConstantSDNode>(N0))
1511     return DAG.getNode(ISD::CTTZ, VT, N0);
1512   return SDOperand();
1513 }
1514
1515 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
1516   SDOperand N0 = N->getOperand(0);
1517   MVT::ValueType VT = N->getValueType(0);
1518   
1519   // fold (ctpop c1) -> c2
1520   if (isa<ConstantSDNode>(N0))
1521     return DAG.getNode(ISD::CTPOP, VT, N0);
1522   return SDOperand();
1523 }
1524
1525 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
1526   SDOperand N0 = N->getOperand(0);
1527   SDOperand N1 = N->getOperand(1);
1528   SDOperand N2 = N->getOperand(2);
1529   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1530   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1531   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
1532   MVT::ValueType VT = N->getValueType(0);
1533
1534   // fold select C, X, X -> X
1535   if (N1 == N2)
1536     return N1;
1537   // fold select true, X, Y -> X
1538   if (N0C && !N0C->isNullValue())
1539     return N1;
1540   // fold select false, X, Y -> Y
1541   if (N0C && N0C->isNullValue())
1542     return N2;
1543   // fold select C, 1, X -> C | X
1544   if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
1545     return DAG.getNode(ISD::OR, VT, N0, N2);
1546   // fold select C, 0, X -> ~C & X
1547   // FIXME: this should check for C type == X type, not i1?
1548   if (MVT::i1 == VT && N1C && N1C->isNullValue()) {
1549     SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
1550     AddToWorkList(XORNode.Val);
1551     return DAG.getNode(ISD::AND, VT, XORNode, N2);
1552   }
1553   // fold select C, X, 1 -> ~C | X
1554   if (MVT::i1 == VT && N2C && N2C->getValue() == 1) {
1555     SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
1556     AddToWorkList(XORNode.Val);
1557     return DAG.getNode(ISD::OR, VT, XORNode, N1);
1558   }
1559   // fold select C, X, 0 -> C & X
1560   // FIXME: this should check for C type == X type, not i1?
1561   if (MVT::i1 == VT && N2C && N2C->isNullValue())
1562     return DAG.getNode(ISD::AND, VT, N0, N1);
1563   // fold  X ? X : Y --> X ? 1 : Y --> X | Y
1564   if (MVT::i1 == VT && N0 == N1)
1565     return DAG.getNode(ISD::OR, VT, N0, N2);
1566   // fold X ? Y : X --> X ? Y : 0 --> X & Y
1567   if (MVT::i1 == VT && N0 == N2)
1568     return DAG.getNode(ISD::AND, VT, N0, N1);
1569   
1570   // If we can fold this based on the true/false value, do so.
1571   if (SimplifySelectOps(N, N1, N2))
1572     return SDOperand(N, 0);  // Don't revisit N.
1573   
1574   // fold selects based on a setcc into other things, such as min/max/abs
1575   if (N0.getOpcode() == ISD::SETCC)
1576     // FIXME:
1577     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
1578     // having to say they don't support SELECT_CC on every type the DAG knows
1579     // about, since there is no way to mark an opcode illegal at all value types
1580     if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
1581       return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
1582                          N1, N2, N0.getOperand(2));
1583     else
1584       return SimplifySelect(N0, N1, N2);
1585   return SDOperand();
1586 }
1587
1588 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
1589   SDOperand N0 = N->getOperand(0);
1590   SDOperand N1 = N->getOperand(1);
1591   SDOperand N2 = N->getOperand(2);
1592   SDOperand N3 = N->getOperand(3);
1593   SDOperand N4 = N->getOperand(4);
1594   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1595   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1596   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
1597   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
1598   
1599   // Determine if the condition we're dealing with is constant
1600   SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
1601   //ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
1602   
1603   // fold select_cc lhs, rhs, x, x, cc -> x
1604   if (N2 == N3)
1605     return N2;
1606   
1607   // If we can fold this based on the true/false value, do so.
1608   if (SimplifySelectOps(N, N2, N3))
1609     return SDOperand(N, 0);  // Don't revisit N.
1610   
1611   // fold select_cc into other things, such as min/max/abs
1612   return SimplifySelectCC(N0, N1, N2, N3, CC);
1613 }
1614
1615 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
1616   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
1617                        cast<CondCodeSDNode>(N->getOperand(2))->get());
1618 }
1619
1620 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
1621   SDOperand N0 = N->getOperand(0);
1622   MVT::ValueType VT = N->getValueType(0);
1623
1624   // fold (sext c1) -> c1
1625   if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0))
1626     return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
1627   
1628   // fold (sext (sext x)) -> (sext x)
1629   // fold (sext (aext x)) -> (sext x)
1630   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
1631     return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
1632   
1633   // fold (sext (truncate x)) -> (sextinreg x) iff x size == sext size.
1634   if (N0.getOpcode() == ISD::TRUNCATE && N0.getOperand(0).getValueType() == VT&&
1635       (!AfterLegalize || 
1636        TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, N0.getValueType())))
1637     return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
1638                        DAG.getValueType(N0.getValueType()));
1639   
1640   // fold (sext (load x)) -> (sext (truncate (sextload x)))
1641   if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse() &&
1642       (!AfterLegalize||TLI.isOperationLegal(ISD::SEXTLOAD, N0.getValueType()))){
1643     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1644                                        N0.getOperand(1), N0.getOperand(2),
1645                                        N0.getValueType());
1646     CombineTo(N, ExtLoad);
1647     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1648               ExtLoad.getValue(1));
1649     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1650   }
1651
1652   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
1653   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
1654   if ((N0.getOpcode() == ISD::SEXTLOAD || N0.getOpcode() == ISD::EXTLOAD) &&
1655       N0.hasOneUse()) {
1656     MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1657     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1658                                        N0.getOperand(1), N0.getOperand(2), EVT);
1659     CombineTo(N, ExtLoad);
1660     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1661               ExtLoad.getValue(1));
1662     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1663   }
1664   
1665   return SDOperand();
1666 }
1667
1668 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
1669   SDOperand N0 = N->getOperand(0);
1670   MVT::ValueType VT = N->getValueType(0);
1671
1672   // fold (zext c1) -> c1
1673   if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0))
1674     return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
1675   // fold (zext (zext x)) -> (zext x)
1676   // fold (zext (aext x)) -> (zext x)
1677   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
1678     return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
1679   // fold (zext (truncate x)) -> (zextinreg x) iff x size == zext size.
1680   if (N0.getOpcode() == ISD::TRUNCATE && N0.getOperand(0).getValueType() == VT&&
1681       (!AfterLegalize || TLI.isOperationLegal(ISD::AND, N0.getValueType())))
1682     return DAG.getZeroExtendInReg(N0.getOperand(0), N0.getValueType());
1683   // fold (zext (load x)) -> (zext (truncate (zextload x)))
1684   if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse() &&
1685       (!AfterLegalize||TLI.isOperationLegal(ISD::ZEXTLOAD, N0.getValueType()))){
1686     SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1687                                        N0.getOperand(1), N0.getOperand(2),
1688                                        N0.getValueType());
1689     CombineTo(N, ExtLoad);
1690     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1691               ExtLoad.getValue(1));
1692     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1693   }
1694
1695   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
1696   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
1697   if ((N0.getOpcode() == ISD::ZEXTLOAD || N0.getOpcode() == ISD::EXTLOAD) &&
1698       N0.hasOneUse()) {
1699     MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1700     SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1701                                        N0.getOperand(1), N0.getOperand(2), EVT);
1702     CombineTo(N, ExtLoad);
1703     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1704               ExtLoad.getValue(1));
1705     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1706   }
1707   return SDOperand();
1708 }
1709
1710 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
1711   SDOperand N0 = N->getOperand(0);
1712   MVT::ValueType VT = N->getValueType(0);
1713   
1714   // fold (aext c1) -> c1
1715   if (isa<ConstantSDNode>(N0))
1716     return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
1717   // fold (aext (aext x)) -> (aext x)
1718   // fold (aext (zext x)) -> (zext x)
1719   // fold (aext (sext x)) -> (sext x)
1720   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
1721       N0.getOpcode() == ISD::ZERO_EXTEND ||
1722       N0.getOpcode() == ISD::SIGN_EXTEND)
1723     return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
1724   
1725   // fold (aext (truncate x)) -> x iff x size == zext size.
1726   if (N0.getOpcode() == ISD::TRUNCATE && N0.getOperand(0).getValueType() == VT)
1727     return N0.getOperand(0);
1728   // fold (aext (load x)) -> (aext (truncate (extload x)))
1729   if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse() &&
1730       (!AfterLegalize||TLI.isOperationLegal(ISD::EXTLOAD, N0.getValueType()))) {
1731     SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N0.getOperand(0),
1732                                        N0.getOperand(1), N0.getOperand(2),
1733                                        N0.getValueType());
1734     CombineTo(N, ExtLoad);
1735     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1736               ExtLoad.getValue(1));
1737     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1738   }
1739   
1740   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
1741   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
1742   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
1743   if ((N0.getOpcode() == ISD::ZEXTLOAD || N0.getOpcode() == ISD::EXTLOAD ||
1744        N0.getOpcode() == ISD::SEXTLOAD) &&
1745       N0.hasOneUse()) {
1746     MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1747     SDOperand ExtLoad = DAG.getExtLoad(N0.getOpcode(), VT, N0.getOperand(0),
1748                                        N0.getOperand(1), N0.getOperand(2), EVT);
1749     CombineTo(N, ExtLoad);
1750     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1751               ExtLoad.getValue(1));
1752     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1753   }
1754   return SDOperand();
1755 }
1756
1757
1758 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
1759   SDOperand N0 = N->getOperand(0);
1760   SDOperand N1 = N->getOperand(1);
1761   MVT::ValueType VT = N->getValueType(0);
1762   MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
1763   unsigned EVTBits = MVT::getSizeInBits(EVT);
1764   
1765   // fold (sext_in_reg c1) -> c1
1766   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
1767     return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
1768   
1769   // If the input is already sign extended, just drop the extension.
1770   if (TLI.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
1771     return N0;
1772   
1773   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
1774   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1775       EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
1776     return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
1777   }
1778
1779   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is zero
1780   if (TLI.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
1781     return DAG.getZeroExtendInReg(N0, EVT);
1782   
1783   // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
1784   // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
1785   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
1786   if (N0.getOpcode() == ISD::SRL) {
1787     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1788       if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
1789         // We can turn this into an SRA iff the input to the SRL is already sign
1790         // extended enough.
1791         unsigned InSignBits = TLI.ComputeNumSignBits(N0.getOperand(0));
1792         if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
1793           return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
1794       }
1795   }
1796   
1797   // fold (sext_inreg (extload x)) -> (sextload x)
1798   if (N0.getOpcode() == ISD::EXTLOAD && 
1799       EVT == cast<VTSDNode>(N0.getOperand(3))->getVT() &&
1800       (!AfterLegalize || TLI.isOperationLegal(ISD::SEXTLOAD, EVT))) {
1801     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1802                                        N0.getOperand(1), N0.getOperand(2),
1803                                        EVT);
1804     CombineTo(N, ExtLoad);
1805     CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1806     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1807   }
1808   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
1809   if (N0.getOpcode() == ISD::ZEXTLOAD && N0.hasOneUse() &&
1810       EVT == cast<VTSDNode>(N0.getOperand(3))->getVT() &&
1811       (!AfterLegalize || TLI.isOperationLegal(ISD::SEXTLOAD, EVT))) {
1812     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1813                                        N0.getOperand(1), N0.getOperand(2),
1814                                        EVT);
1815     CombineTo(N, ExtLoad);
1816     CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1817     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1818   }
1819   return SDOperand();
1820 }
1821
1822 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
1823   SDOperand N0 = N->getOperand(0);
1824   MVT::ValueType VT = N->getValueType(0);
1825
1826   // noop truncate
1827   if (N0.getValueType() == N->getValueType(0))
1828     return N0;
1829   // fold (truncate c1) -> c1
1830   if (isa<ConstantSDNode>(N0))
1831     return DAG.getNode(ISD::TRUNCATE, VT, N0);
1832   // fold (truncate (truncate x)) -> (truncate x)
1833   if (N0.getOpcode() == ISD::TRUNCATE)
1834     return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
1835   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
1836   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
1837       N0.getOpcode() == ISD::ANY_EXTEND) {
1838     if (N0.getValueType() < VT)
1839       // if the source is smaller than the dest, we still need an extend
1840       return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
1841     else if (N0.getValueType() > VT)
1842       // if the source is larger than the dest, than we just need the truncate
1843       return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
1844     else
1845       // if the source and dest are the same type, we can drop both the extend
1846       // and the truncate
1847       return N0.getOperand(0);
1848   }
1849   // fold (truncate (load x)) -> (smaller load x)
1850   if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse()) {
1851     assert(MVT::getSizeInBits(N0.getValueType()) > MVT::getSizeInBits(VT) &&
1852            "Cannot truncate to larger type!");
1853     MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1854     // For big endian targets, we need to add an offset to the pointer to load
1855     // the correct bytes.  For little endian systems, we merely need to read
1856     // fewer bytes from the same pointer.
1857     uint64_t PtrOff = 
1858       (MVT::getSizeInBits(N0.getValueType()) - MVT::getSizeInBits(VT)) / 8;
1859     SDOperand NewPtr = TLI.isLittleEndian() ? N0.getOperand(1) : 
1860       DAG.getNode(ISD::ADD, PtrType, N0.getOperand(1),
1861                   DAG.getConstant(PtrOff, PtrType));
1862     AddToWorkList(NewPtr.Val);
1863     SDOperand Load = DAG.getLoad(VT, N0.getOperand(0), NewPtr,N0.getOperand(2));
1864     AddToWorkList(N);
1865     CombineTo(N0.Val, Load, Load.getValue(1));
1866     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1867   }
1868   return SDOperand();
1869 }
1870
1871 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
1872   SDOperand N0 = N->getOperand(0);
1873   MVT::ValueType VT = N->getValueType(0);
1874
1875   // If the input is a constant, let getNode() fold it.
1876   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
1877     SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
1878     if (Res.Val != N) return Res;
1879   }
1880   
1881   if (N0.getOpcode() == ISD::BIT_CONVERT)  // conv(conv(x,t1),t2) -> conv(x,t2)
1882     return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
1883
1884   // fold (conv (load x)) -> (load (conv*)x)
1885   // FIXME: These xforms need to know that the resultant load doesn't need a 
1886   // higher alignment than the original!
1887   if (0 && N0.getOpcode() == ISD::LOAD && N0.hasOneUse()) {
1888     SDOperand Load = DAG.getLoad(VT, N0.getOperand(0), N0.getOperand(1),
1889                                  N0.getOperand(2));
1890     AddToWorkList(N);
1891     CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
1892               Load.getValue(1));
1893     return Load;
1894   }
1895   
1896   return SDOperand();
1897 }
1898
1899 SDOperand DAGCombiner::visitVBIT_CONVERT(SDNode *N) {
1900   SDOperand N0 = N->getOperand(0);
1901   MVT::ValueType VT = N->getValueType(0);
1902
1903   // If the input is a VBUILD_VECTOR with all constant elements, fold this now.
1904   // First check to see if this is all constant.
1905   if (N0.getOpcode() == ISD::VBUILD_VECTOR && N0.Val->hasOneUse() &&
1906       VT == MVT::Vector) {
1907     bool isSimple = true;
1908     for (unsigned i = 0, e = N0.getNumOperands()-2; i != e; ++i)
1909       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
1910           N0.getOperand(i).getOpcode() != ISD::Constant &&
1911           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
1912         isSimple = false; 
1913         break;
1914       }
1915         
1916     MVT::ValueType DestEltVT = cast<VTSDNode>(N->getOperand(2))->getVT();
1917     if (isSimple && !MVT::isVector(DestEltVT)) {
1918       return ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(N0.Val, DestEltVT);
1919     }
1920   }
1921   
1922   return SDOperand();
1923 }
1924
1925 /// ConstantFoldVBIT_CONVERTofVBUILD_VECTOR - We know that BV is a vbuild_vector
1926 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the 
1927 /// destination element value type.
1928 SDOperand DAGCombiner::
1929 ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
1930   MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
1931   
1932   // If this is already the right type, we're done.
1933   if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
1934   
1935   unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
1936   unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
1937   
1938   // If this is a conversion of N elements of one type to N elements of another
1939   // type, convert each element.  This handles FP<->INT cases.
1940   if (SrcBitSize == DstBitSize) {
1941     SmallVector<SDOperand, 8> Ops;
1942     for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) {
1943       Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
1944       AddToWorkList(Ops.back().Val);
1945     }
1946     Ops.push_back(*(BV->op_end()-2)); // Add num elements.
1947     Ops.push_back(DAG.getValueType(DstEltVT));
1948     return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
1949   }
1950   
1951   // Otherwise, we're growing or shrinking the elements.  To avoid having to
1952   // handle annoying details of growing/shrinking FP values, we convert them to
1953   // int first.
1954   if (MVT::isFloatingPoint(SrcEltVT)) {
1955     // Convert the input float vector to a int vector where the elements are the
1956     // same sizes.
1957     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
1958     MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
1959     BV = ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(BV, IntVT).Val;
1960     SrcEltVT = IntVT;
1961   }
1962   
1963   // Now we know the input is an integer vector.  If the output is a FP type,
1964   // convert to integer first, then to FP of the right size.
1965   if (MVT::isFloatingPoint(DstEltVT)) {
1966     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
1967     MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
1968     SDNode *Tmp = ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(BV, TmpVT).Val;
1969     
1970     // Next, convert to FP elements of the same size.
1971     return ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(Tmp, DstEltVT);
1972   }
1973   
1974   // Okay, we know the src/dst types are both integers of differing types.
1975   // Handling growing first.
1976   assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
1977   if (SrcBitSize < DstBitSize) {
1978     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
1979     
1980     SmallVector<SDOperand, 8> Ops;
1981     for (unsigned i = 0, e = BV->getNumOperands()-2; i != e;
1982          i += NumInputsPerOutput) {
1983       bool isLE = TLI.isLittleEndian();
1984       uint64_t NewBits = 0;
1985       bool EltIsUndef = true;
1986       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
1987         // Shift the previously computed bits over.
1988         NewBits <<= SrcBitSize;
1989         SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
1990         if (Op.getOpcode() == ISD::UNDEF) continue;
1991         EltIsUndef = false;
1992         
1993         NewBits |= cast<ConstantSDNode>(Op)->getValue();
1994       }
1995       
1996       if (EltIsUndef)
1997         Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
1998       else
1999         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
2000     }
2001
2002     Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements.
2003     Ops.push_back(DAG.getValueType(DstEltVT));            // Add element size.
2004     return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2005   }
2006   
2007   // Finally, this must be the case where we are shrinking elements: each input
2008   // turns into multiple outputs.
2009   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
2010   SmallVector<SDOperand, 8> Ops;
2011   for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) {
2012     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
2013       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
2014         Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2015       continue;
2016     }
2017     uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
2018
2019     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
2020       unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
2021       OpVal >>= DstBitSize;
2022       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
2023     }
2024
2025     // For big endian targets, swap the order of the pieces of each element.
2026     if (!TLI.isLittleEndian())
2027       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
2028   }
2029   Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements.
2030   Ops.push_back(DAG.getValueType(DstEltVT));            // Add element size.
2031   return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2032 }
2033
2034
2035
2036 SDOperand DAGCombiner::visitFADD(SDNode *N) {
2037   SDOperand N0 = N->getOperand(0);
2038   SDOperand N1 = N->getOperand(1);
2039   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2040   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2041   MVT::ValueType VT = N->getValueType(0);
2042   
2043   // fold (fadd c1, c2) -> c1+c2
2044   if (N0CFP && N1CFP)
2045     return DAG.getNode(ISD::FADD, VT, N0, N1);
2046   // canonicalize constant to RHS
2047   if (N0CFP && !N1CFP)
2048     return DAG.getNode(ISD::FADD, VT, N1, N0);
2049   // fold (A + (-B)) -> A-B
2050   if (N1.getOpcode() == ISD::FNEG)
2051     return DAG.getNode(ISD::FSUB, VT, N0, N1.getOperand(0));
2052   // fold ((-A) + B) -> B-A
2053   if (N0.getOpcode() == ISD::FNEG)
2054     return DAG.getNode(ISD::FSUB, VT, N1, N0.getOperand(0));
2055   return SDOperand();
2056 }
2057
2058 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
2059   SDOperand N0 = N->getOperand(0);
2060   SDOperand N1 = N->getOperand(1);
2061   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2062   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2063   MVT::ValueType VT = N->getValueType(0);
2064   
2065   // fold (fsub c1, c2) -> c1-c2
2066   if (N0CFP && N1CFP)
2067     return DAG.getNode(ISD::FSUB, VT, N0, N1);
2068   // fold (A-(-B)) -> A+B
2069   if (N1.getOpcode() == ISD::FNEG)
2070     return DAG.getNode(ISD::FADD, VT, N0, N1.getOperand(0));
2071   return SDOperand();
2072 }
2073
2074 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
2075   SDOperand N0 = N->getOperand(0);
2076   SDOperand N1 = N->getOperand(1);
2077   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2078   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2079   MVT::ValueType VT = N->getValueType(0);
2080
2081   // fold (fmul c1, c2) -> c1*c2
2082   if (N0CFP && N1CFP)
2083     return DAG.getNode(ISD::FMUL, VT, N0, N1);
2084   // canonicalize constant to RHS
2085   if (N0CFP && !N1CFP)
2086     return DAG.getNode(ISD::FMUL, VT, N1, N0);
2087   // fold (fmul X, 2.0) -> (fadd X, X)
2088   if (N1CFP && N1CFP->isExactlyValue(+2.0))
2089     return DAG.getNode(ISD::FADD, VT, N0, N0);
2090   return SDOperand();
2091 }
2092
2093 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
2094   SDOperand N0 = N->getOperand(0);
2095   SDOperand N1 = N->getOperand(1);
2096   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2097   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2098   MVT::ValueType VT = N->getValueType(0);
2099
2100   // fold (fdiv c1, c2) -> c1/c2
2101   if (N0CFP && N1CFP)
2102     return DAG.getNode(ISD::FDIV, VT, N0, N1);
2103   return SDOperand();
2104 }
2105
2106 SDOperand DAGCombiner::visitFREM(SDNode *N) {
2107   SDOperand N0 = N->getOperand(0);
2108   SDOperand N1 = N->getOperand(1);
2109   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2110   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2111   MVT::ValueType VT = N->getValueType(0);
2112
2113   // fold (frem c1, c2) -> fmod(c1,c2)
2114   if (N0CFP && N1CFP)
2115     return DAG.getNode(ISD::FREM, VT, N0, N1);
2116   return SDOperand();
2117 }
2118
2119 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
2120   SDOperand N0 = N->getOperand(0);
2121   SDOperand N1 = N->getOperand(1);
2122   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2123   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2124   MVT::ValueType VT = N->getValueType(0);
2125
2126   if (N0CFP && N1CFP)  // Constant fold
2127     return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
2128   
2129   if (N1CFP) {
2130     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
2131     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
2132     union {
2133       double d;
2134       int64_t i;
2135     } u;
2136     u.d = N1CFP->getValue();
2137     if (u.i >= 0)
2138       return DAG.getNode(ISD::FABS, VT, N0);
2139     else
2140       return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
2141   }
2142   
2143   // copysign(fabs(x), y) -> copysign(x, y)
2144   // copysign(fneg(x), y) -> copysign(x, y)
2145   // copysign(copysign(x,z), y) -> copysign(x, y)
2146   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
2147       N0.getOpcode() == ISD::FCOPYSIGN)
2148     return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
2149
2150   // copysign(x, abs(y)) -> abs(x)
2151   if (N1.getOpcode() == ISD::FABS)
2152     return DAG.getNode(ISD::FABS, VT, N0);
2153   
2154   // copysign(x, copysign(y,z)) -> copysign(x, z)
2155   if (N1.getOpcode() == ISD::FCOPYSIGN)
2156     return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
2157   
2158   // copysign(x, fp_extend(y)) -> copysign(x, y)
2159   // copysign(x, fp_round(y)) -> copysign(x, y)
2160   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
2161     return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
2162   
2163   return SDOperand();
2164 }
2165
2166
2167
2168 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
2169   SDOperand N0 = N->getOperand(0);
2170   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2171   MVT::ValueType VT = N->getValueType(0);
2172   
2173   // fold (sint_to_fp c1) -> c1fp
2174   if (N0C)
2175     return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
2176   return SDOperand();
2177 }
2178
2179 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
2180   SDOperand N0 = N->getOperand(0);
2181   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2182   MVT::ValueType VT = N->getValueType(0);
2183
2184   // fold (uint_to_fp c1) -> c1fp
2185   if (N0C)
2186     return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
2187   return SDOperand();
2188 }
2189
2190 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
2191   SDOperand N0 = N->getOperand(0);
2192   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2193   MVT::ValueType VT = N->getValueType(0);
2194   
2195   // fold (fp_to_sint c1fp) -> c1
2196   if (N0CFP)
2197     return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
2198   return SDOperand();
2199 }
2200
2201 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
2202   SDOperand N0 = N->getOperand(0);
2203   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2204   MVT::ValueType VT = N->getValueType(0);
2205   
2206   // fold (fp_to_uint c1fp) -> c1
2207   if (N0CFP)
2208     return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
2209   return SDOperand();
2210 }
2211
2212 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
2213   SDOperand N0 = N->getOperand(0);
2214   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2215   MVT::ValueType VT = N->getValueType(0);
2216   
2217   // fold (fp_round c1fp) -> c1fp
2218   if (N0CFP)
2219     return DAG.getNode(ISD::FP_ROUND, VT, N0);
2220   
2221   // fold (fp_round (fp_extend x)) -> x
2222   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
2223     return N0.getOperand(0);
2224   
2225   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
2226   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
2227     SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0));
2228     AddToWorkList(Tmp.Val);
2229     return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
2230   }
2231   
2232   return SDOperand();
2233 }
2234
2235 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
2236   SDOperand N0 = N->getOperand(0);
2237   MVT::ValueType VT = N->getValueType(0);
2238   MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2239   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2240   
2241   // fold (fp_round_inreg c1fp) -> c1fp
2242   if (N0CFP) {
2243     SDOperand Round = DAG.getConstantFP(N0CFP->getValue(), EVT);
2244     return DAG.getNode(ISD::FP_EXTEND, VT, Round);
2245   }
2246   return SDOperand();
2247 }
2248
2249 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
2250   SDOperand N0 = N->getOperand(0);
2251   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2252   MVT::ValueType VT = N->getValueType(0);
2253   
2254   // fold (fp_extend c1fp) -> c1fp
2255   if (N0CFP)
2256     return DAG.getNode(ISD::FP_EXTEND, VT, N0);
2257   
2258   // fold (fpext (load x)) -> (fpext (fpround (extload x)))
2259   if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse() &&
2260       (!AfterLegalize||TLI.isOperationLegal(ISD::EXTLOAD, N0.getValueType()))) {
2261     SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N0.getOperand(0),
2262                                        N0.getOperand(1), N0.getOperand(2),
2263                                        N0.getValueType());
2264     CombineTo(N, ExtLoad);
2265     CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad),
2266               ExtLoad.getValue(1));
2267     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2268   }
2269   
2270   
2271   return SDOperand();
2272 }
2273
2274 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
2275   SDOperand N0 = N->getOperand(0);
2276   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2277   MVT::ValueType VT = N->getValueType(0);
2278
2279   // fold (fneg c1) -> -c1
2280   if (N0CFP)
2281     return DAG.getNode(ISD::FNEG, VT, N0);
2282   // fold (fneg (sub x, y)) -> (sub y, x)
2283   if (N0.getOpcode() == ISD::SUB)
2284     return DAG.getNode(ISD::SUB, VT, N0.getOperand(1), N0.getOperand(0));
2285   // fold (fneg (fneg x)) -> x
2286   if (N0.getOpcode() == ISD::FNEG)
2287     return N0.getOperand(0);
2288   return SDOperand();
2289 }
2290
2291 SDOperand DAGCombiner::visitFABS(SDNode *N) {
2292   SDOperand N0 = N->getOperand(0);
2293   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2294   MVT::ValueType VT = N->getValueType(0);
2295   
2296   // fold (fabs c1) -> fabs(c1)
2297   if (N0CFP)
2298     return DAG.getNode(ISD::FABS, VT, N0);
2299   // fold (fabs (fabs x)) -> (fabs x)
2300   if (N0.getOpcode() == ISD::FABS)
2301     return N->getOperand(0);
2302   // fold (fabs (fneg x)) -> (fabs x)
2303   // fold (fabs (fcopysign x, y)) -> (fabs x)
2304   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
2305     return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
2306   
2307   return SDOperand();
2308 }
2309
2310 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
2311   SDOperand Chain = N->getOperand(0);
2312   SDOperand N1 = N->getOperand(1);
2313   SDOperand N2 = N->getOperand(2);
2314   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2315   
2316   // never taken branch, fold to chain
2317   if (N1C && N1C->isNullValue())
2318     return Chain;
2319   // unconditional branch
2320   if (N1C && N1C->getValue() == 1)
2321     return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
2322   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
2323   // on the target.
2324   if (N1.getOpcode() == ISD::SETCC && 
2325       TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
2326     return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
2327                        N1.getOperand(0), N1.getOperand(1), N2);
2328   }
2329   return SDOperand();
2330 }
2331
2332 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
2333 //
2334 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
2335   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
2336   SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
2337   
2338   // Use SimplifySetCC  to simplify SETCC's.
2339   SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
2340   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
2341
2342   // fold br_cc true, dest -> br dest (unconditional branch)
2343   if (SCCC && SCCC->getValue())
2344     return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
2345                        N->getOperand(4));
2346   // fold br_cc false, dest -> unconditional fall through
2347   if (SCCC && SCCC->isNullValue())
2348     return N->getOperand(0);
2349   // fold to a simpler setcc
2350   if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
2351     return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0), 
2352                        Simp.getOperand(2), Simp.getOperand(0),
2353                        Simp.getOperand(1), N->getOperand(4));
2354   return SDOperand();
2355 }
2356
2357 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
2358   SDOperand Chain    = N->getOperand(0);
2359   SDOperand Ptr      = N->getOperand(1);
2360   SDOperand SrcValue = N->getOperand(2);
2361
2362   // If there are no uses of the loaded value, change uses of the chain value
2363   // into uses of the chain input (i.e. delete the dead load).
2364   if (N->hasNUsesOfValue(0, 0))
2365     return CombineTo(N, DAG.getNode(ISD::UNDEF, N->getValueType(0)), Chain);
2366   
2367   // If this load is directly stored, replace the load value with the stored
2368   // value.
2369   // TODO: Handle store large -> read small portion.
2370   // TODO: Handle TRUNCSTORE/EXTLOAD
2371   if (Chain.getOpcode() == ISD::STORE && Chain.getOperand(2) == Ptr &&
2372       Chain.getOperand(1).getValueType() == N->getValueType(0))
2373     return CombineTo(N, Chain.getOperand(1), Chain);
2374   
2375   return SDOperand();
2376 }
2377
2378 /// visitXEXTLOAD - Handle EXTLOAD/ZEXTLOAD/SEXTLOAD.
2379 SDOperand DAGCombiner::visitXEXTLOAD(SDNode *N) {
2380   SDOperand Chain    = N->getOperand(0);
2381   SDOperand Ptr      = N->getOperand(1);
2382   SDOperand SrcValue = N->getOperand(2);
2383   SDOperand EVT      = N->getOperand(3);
2384   
2385   // If there are no uses of the loaded value, change uses of the chain value
2386   // into uses of the chain input (i.e. delete the dead load).
2387   if (N->hasNUsesOfValue(0, 0))
2388     return CombineTo(N, DAG.getNode(ISD::UNDEF, N->getValueType(0)), Chain);
2389   
2390   return SDOperand();
2391 }
2392
2393 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
2394   SDOperand Chain    = N->getOperand(0);
2395   SDOperand Value    = N->getOperand(1);
2396   SDOperand Ptr      = N->getOperand(2);
2397   SDOperand SrcValue = N->getOperand(3);
2398  
2399   // If this is a store that kills a previous store, remove the previous store.
2400   if (Chain.getOpcode() == ISD::STORE && Chain.getOperand(2) == Ptr &&
2401       Chain.Val->hasOneUse() /* Avoid introducing DAG cycles */ &&
2402       // Make sure that these stores are the same value type:
2403       // FIXME: we really care that the second store is >= size of the first.
2404       Value.getValueType() == Chain.getOperand(1).getValueType()) {
2405     // Create a new store of Value that replaces both stores.
2406     SDNode *PrevStore = Chain.Val;
2407     if (PrevStore->getOperand(1) == Value) // Same value multiply stored.
2408       return Chain;
2409     SDOperand NewStore = DAG.getNode(ISD::STORE, MVT::Other,
2410                                      PrevStore->getOperand(0), Value, Ptr,
2411                                      SrcValue);
2412     CombineTo(N, NewStore);                 // Nuke this store.
2413     CombineTo(PrevStore, NewStore);  // Nuke the previous store.
2414     return SDOperand(N, 0);
2415   }
2416   
2417   // If this is a store of a bit convert, store the input value.
2418   // FIXME: This needs to know that the resultant store does not need a 
2419   // higher alignment than the original.
2420   if (0 && Value.getOpcode() == ISD::BIT_CONVERT)
2421     return DAG.getNode(ISD::STORE, MVT::Other, Chain, Value.getOperand(0),
2422                        Ptr, SrcValue);
2423   
2424   return SDOperand();
2425 }
2426
2427 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
2428   SDOperand InVec = N->getOperand(0);
2429   SDOperand InVal = N->getOperand(1);
2430   SDOperand EltNo = N->getOperand(2);
2431   
2432   // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
2433   // vector with the inserted element.
2434   if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
2435     unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
2436     SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
2437     if (Elt < Ops.size())
2438       Ops[Elt] = InVal;
2439     return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
2440                        &Ops[0], Ops.size());
2441   }
2442   
2443   return SDOperand();
2444 }
2445
2446 SDOperand DAGCombiner::visitVINSERT_VECTOR_ELT(SDNode *N) {
2447   SDOperand InVec = N->getOperand(0);
2448   SDOperand InVal = N->getOperand(1);
2449   SDOperand EltNo = N->getOperand(2);
2450   SDOperand NumElts = N->getOperand(3);
2451   SDOperand EltType = N->getOperand(4);
2452   
2453   // If the invec is a VBUILD_VECTOR and if EltNo is a constant, build a new
2454   // vector with the inserted element.
2455   if (InVec.getOpcode() == ISD::VBUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
2456     unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
2457     SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
2458     if (Elt < Ops.size()-2)
2459       Ops[Elt] = InVal;
2460     return DAG.getNode(ISD::VBUILD_VECTOR, InVec.getValueType(),
2461                        &Ops[0], Ops.size());
2462   }
2463   
2464   return SDOperand();
2465 }
2466
2467 SDOperand DAGCombiner::visitVBUILD_VECTOR(SDNode *N) {
2468   unsigned NumInScalars = N->getNumOperands()-2;
2469   SDOperand NumElts = N->getOperand(NumInScalars);
2470   SDOperand EltType = N->getOperand(NumInScalars+1);
2471
2472   // Check to see if this is a VBUILD_VECTOR of a bunch of VEXTRACT_VECTOR_ELT
2473   // operations.  If so, and if the EXTRACT_ELT vector inputs come from at most
2474   // two distinct vectors, turn this into a shuffle node.
2475   SDOperand VecIn1, VecIn2;
2476   for (unsigned i = 0; i != NumInScalars; ++i) {
2477     // Ignore undef inputs.
2478     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
2479     
2480     // If this input is something other than a VEXTRACT_VECTOR_ELT with a
2481     // constant index, bail out.
2482     if (N->getOperand(i).getOpcode() != ISD::VEXTRACT_VECTOR_ELT ||
2483         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
2484       VecIn1 = VecIn2 = SDOperand(0, 0);
2485       break;
2486     }
2487     
2488     // If the input vector type disagrees with the result of the vbuild_vector,
2489     // we can't make a shuffle.
2490     SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
2491     if (*(ExtractedFromVec.Val->op_end()-2) != NumElts ||
2492         *(ExtractedFromVec.Val->op_end()-1) != EltType) {
2493       VecIn1 = VecIn2 = SDOperand(0, 0);
2494       break;
2495     }
2496     
2497     // Otherwise, remember this.  We allow up to two distinct input vectors.
2498     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
2499       continue;
2500     
2501     if (VecIn1.Val == 0) {
2502       VecIn1 = ExtractedFromVec;
2503     } else if (VecIn2.Val == 0) {
2504       VecIn2 = ExtractedFromVec;
2505     } else {
2506       // Too many inputs.
2507       VecIn1 = VecIn2 = SDOperand(0, 0);
2508       break;
2509     }
2510   }
2511   
2512   // If everything is good, we can make a shuffle operation.
2513   if (VecIn1.Val) {
2514     SmallVector<SDOperand, 8> BuildVecIndices;
2515     for (unsigned i = 0; i != NumInScalars; ++i) {
2516       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
2517         BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
2518         continue;
2519       }
2520       
2521       SDOperand Extract = N->getOperand(i);
2522       
2523       // If extracting from the first vector, just use the index directly.
2524       if (Extract.getOperand(0) == VecIn1) {
2525         BuildVecIndices.push_back(Extract.getOperand(1));
2526         continue;
2527       }
2528
2529       // Otherwise, use InIdx + VecSize
2530       unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
2531       BuildVecIndices.push_back(DAG.getConstant(Idx+NumInScalars, MVT::i32));
2532     }
2533     
2534     // Add count and size info.
2535     BuildVecIndices.push_back(NumElts);
2536     BuildVecIndices.push_back(DAG.getValueType(MVT::i32));
2537     
2538     // Return the new VVECTOR_SHUFFLE node.
2539     SDOperand Ops[5];
2540     Ops[0] = VecIn1;
2541     if (VecIn2.Val) {
2542       Ops[1] = VecIn2;
2543     } else {
2544        // Use an undef vbuild_vector as input for the second operand.
2545       std::vector<SDOperand> UnOps(NumInScalars,
2546                                    DAG.getNode(ISD::UNDEF, 
2547                                            cast<VTSDNode>(EltType)->getVT()));
2548       UnOps.push_back(NumElts);
2549       UnOps.push_back(EltType);
2550       Ops[1] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
2551                            &UnOps[0], UnOps.size());
2552       AddToWorkList(Ops[1].Val);
2553     }
2554     Ops[2] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
2555                          &BuildVecIndices[0], BuildVecIndices.size());
2556     Ops[3] = NumElts;
2557     Ops[4] = EltType;
2558     return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, Ops, 5);
2559   }
2560   
2561   return SDOperand();
2562 }
2563
2564 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
2565   SDOperand ShufMask = N->getOperand(2);
2566   unsigned NumElts = ShufMask.getNumOperands();
2567
2568   // If the shuffle mask is an identity operation on the LHS, return the LHS.
2569   bool isIdentity = true;
2570   for (unsigned i = 0; i != NumElts; ++i) {
2571     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
2572         cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
2573       isIdentity = false;
2574       break;
2575     }
2576   }
2577   if (isIdentity) return N->getOperand(0);
2578
2579   // If the shuffle mask is an identity operation on the RHS, return the RHS.
2580   isIdentity = true;
2581   for (unsigned i = 0; i != NumElts; ++i) {
2582     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
2583         cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
2584       isIdentity = false;
2585       break;
2586     }
2587   }
2588   if (isIdentity) return N->getOperand(1);
2589
2590   // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
2591   // needed at all.
2592   bool isUnary = true;
2593   bool isSplat = true;
2594   int VecNum = -1;
2595   unsigned BaseIdx = 0;
2596   for (unsigned i = 0; i != NumElts; ++i)
2597     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
2598       unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
2599       int V = (Idx < NumElts) ? 0 : 1;
2600       if (VecNum == -1) {
2601         VecNum = V;
2602         BaseIdx = Idx;
2603       } else {
2604         if (BaseIdx != Idx)
2605           isSplat = false;
2606         if (VecNum != V) {
2607           isUnary = false;
2608           break;
2609         }
2610       }
2611     }
2612
2613   SDOperand N0 = N->getOperand(0);
2614   SDOperand N1 = N->getOperand(1);
2615   // Normalize unary shuffle so the RHS is undef.
2616   if (isUnary && VecNum == 1)
2617     std::swap(N0, N1);
2618
2619   // If it is a splat, check if the argument vector is a build_vector with
2620   // all scalar elements the same.
2621   if (isSplat) {
2622     SDNode *V = N0.Val;
2623     if (V->getOpcode() == ISD::BIT_CONVERT)
2624       V = V->getOperand(0).Val;
2625     if (V->getOpcode() == ISD::BUILD_VECTOR) {
2626       unsigned NumElems = V->getNumOperands()-2;
2627       if (NumElems > BaseIdx) {
2628         SDOperand Base;
2629         bool AllSame = true;
2630         for (unsigned i = 0; i != NumElems; ++i) {
2631           if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
2632             Base = V->getOperand(i);
2633             break;
2634           }
2635         }
2636         // Splat of <u, u, u, u>, return <u, u, u, u>
2637         if (!Base.Val)
2638           return N0;
2639         for (unsigned i = 0; i != NumElems; ++i) {
2640           if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
2641               V->getOperand(i) != Base) {
2642             AllSame = false;
2643             break;
2644           }
2645         }
2646         // Splat of <x, x, x, x>, return <x, x, x, x>
2647         if (AllSame)
2648           return N0;
2649       }
2650     }
2651   }
2652
2653   // If it is a unary or the LHS and the RHS are the same node, turn the RHS
2654   // into an undef.
2655   if (isUnary || N0 == N1) {
2656     if (N0.getOpcode() == ISD::UNDEF)
2657       return DAG.getNode(ISD::UNDEF, N->getValueType(0));
2658     // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
2659     // first operand.
2660     SmallVector<SDOperand, 8> MappedOps;
2661     for (unsigned i = 0, e = ShufMask.getNumOperands(); i != e; ++i) {
2662       if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
2663           cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
2664         MappedOps.push_back(ShufMask.getOperand(i));
2665       } else {
2666         unsigned NewIdx = 
2667            cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
2668         MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
2669       }
2670     }
2671     ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
2672                            &MappedOps[0], MappedOps.size());
2673     AddToWorkList(ShufMask.Val);
2674     return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
2675                        N0, 
2676                        DAG.getNode(ISD::UNDEF, N->getValueType(0)),
2677                        ShufMask);
2678   }
2679  
2680   return SDOperand();
2681 }
2682
2683 SDOperand DAGCombiner::visitVVECTOR_SHUFFLE(SDNode *N) {
2684   SDOperand ShufMask = N->getOperand(2);
2685   unsigned NumElts = ShufMask.getNumOperands()-2;
2686   
2687   // If the shuffle mask is an identity operation on the LHS, return the LHS.
2688   bool isIdentity = true;
2689   for (unsigned i = 0; i != NumElts; ++i) {
2690     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
2691         cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
2692       isIdentity = false;
2693       break;
2694     }
2695   }
2696   if (isIdentity) return N->getOperand(0);
2697   
2698   // If the shuffle mask is an identity operation on the RHS, return the RHS.
2699   isIdentity = true;
2700   for (unsigned i = 0; i != NumElts; ++i) {
2701     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
2702         cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
2703       isIdentity = false;
2704       break;
2705     }
2706   }
2707   if (isIdentity) return N->getOperand(1);
2708
2709   // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
2710   // needed at all.
2711   bool isUnary = true;
2712   bool isSplat = true;
2713   int VecNum = -1;
2714   unsigned BaseIdx = 0;
2715   for (unsigned i = 0; i != NumElts; ++i)
2716     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
2717       unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
2718       int V = (Idx < NumElts) ? 0 : 1;
2719       if (VecNum == -1) {
2720         VecNum = V;
2721         BaseIdx = Idx;
2722       } else {
2723         if (BaseIdx != Idx)
2724           isSplat = false;
2725         if (VecNum != V) {
2726           isUnary = false;
2727           break;
2728         }
2729       }
2730     }
2731
2732   SDOperand N0 = N->getOperand(0);
2733   SDOperand N1 = N->getOperand(1);
2734   // Normalize unary shuffle so the RHS is undef.
2735   if (isUnary && VecNum == 1)
2736     std::swap(N0, N1);
2737
2738   // If it is a splat, check if the argument vector is a build_vector with
2739   // all scalar elements the same.
2740   if (isSplat) {
2741     SDNode *V = N0.Val;
2742     if (V->getOpcode() == ISD::VBIT_CONVERT)
2743       V = V->getOperand(0).Val;
2744     if (V->getOpcode() == ISD::VBUILD_VECTOR) {
2745       unsigned NumElems = V->getNumOperands()-2;
2746       if (NumElems > BaseIdx) {
2747         SDOperand Base;
2748         bool AllSame = true;
2749         for (unsigned i = 0; i != NumElems; ++i) {
2750           if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
2751             Base = V->getOperand(i);
2752             break;
2753           }
2754         }
2755         // Splat of <u, u, u, u>, return <u, u, u, u>
2756         if (!Base.Val)
2757           return N0;
2758         for (unsigned i = 0; i != NumElems; ++i) {
2759           if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
2760               V->getOperand(i) != Base) {
2761             AllSame = false;
2762             break;
2763           }
2764         }
2765         // Splat of <x, x, x, x>, return <x, x, x, x>
2766         if (AllSame)
2767           return N0;
2768       }
2769     }
2770   }
2771
2772   // If it is a unary or the LHS and the RHS are the same node, turn the RHS
2773   // into an undef.
2774   if (isUnary || N0 == N1) {
2775     // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
2776     // first operand.
2777     SmallVector<SDOperand, 8> MappedOps;
2778     for (unsigned i = 0; i != NumElts; ++i) {
2779       if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
2780           cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
2781         MappedOps.push_back(ShufMask.getOperand(i));
2782       } else {
2783         unsigned NewIdx = 
2784           cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
2785         MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
2786       }
2787     }
2788     // Add the type/#elts values.
2789     MappedOps.push_back(ShufMask.getOperand(NumElts));
2790     MappedOps.push_back(ShufMask.getOperand(NumElts+1));
2791
2792     ShufMask = DAG.getNode(ISD::VBUILD_VECTOR, ShufMask.getValueType(),
2793                            &MappedOps[0], MappedOps.size());
2794     AddToWorkList(ShufMask.Val);
2795     
2796     // Build the undef vector.
2797     SDOperand UDVal = DAG.getNode(ISD::UNDEF, MappedOps[0].getValueType());
2798     for (unsigned i = 0; i != NumElts; ++i)
2799       MappedOps[i] = UDVal;
2800     MappedOps[NumElts  ] = *(N0.Val->op_end()-2);
2801     MappedOps[NumElts+1] = *(N0.Val->op_end()-1);
2802     UDVal = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
2803                         &MappedOps[0], MappedOps.size());
2804     
2805     return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, 
2806                        N0, UDVal, ShufMask,
2807                        MappedOps[NumElts], MappedOps[NumElts+1]);
2808   }
2809   
2810   return SDOperand();
2811 }
2812
2813 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
2814 /// a VAND to a vector_shuffle with the destination vector and a zero vector.
2815 /// e.g. VAND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
2816 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
2817 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
2818   SDOperand LHS = N->getOperand(0);
2819   SDOperand RHS = N->getOperand(1);
2820   if (N->getOpcode() == ISD::VAND) {
2821     SDOperand DstVecSize = *(LHS.Val->op_end()-2);
2822     SDOperand DstVecEVT  = *(LHS.Val->op_end()-1);
2823     if (RHS.getOpcode() == ISD::VBIT_CONVERT)
2824       RHS = RHS.getOperand(0);
2825     if (RHS.getOpcode() == ISD::VBUILD_VECTOR) {
2826       std::vector<SDOperand> IdxOps;
2827       unsigned NumOps = RHS.getNumOperands();
2828       unsigned NumElts = NumOps-2;
2829       MVT::ValueType EVT = cast<VTSDNode>(RHS.getOperand(NumOps-1))->getVT();
2830       for (unsigned i = 0; i != NumElts; ++i) {
2831         SDOperand Elt = RHS.getOperand(i);
2832         if (!isa<ConstantSDNode>(Elt))
2833           return SDOperand();
2834         else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
2835           IdxOps.push_back(DAG.getConstant(i, EVT));
2836         else if (cast<ConstantSDNode>(Elt)->isNullValue())
2837           IdxOps.push_back(DAG.getConstant(NumElts, EVT));
2838         else
2839           return SDOperand();
2840       }
2841
2842       // Let's see if the target supports this vector_shuffle.
2843       if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
2844         return SDOperand();
2845
2846       // Return the new VVECTOR_SHUFFLE node.
2847       SDOperand NumEltsNode = DAG.getConstant(NumElts, MVT::i32);
2848       SDOperand EVTNode = DAG.getValueType(EVT);
2849       std::vector<SDOperand> Ops;
2850       LHS = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, LHS, NumEltsNode, EVTNode);
2851       Ops.push_back(LHS);
2852       AddToWorkList(LHS.Val);
2853       std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
2854       ZeroOps.push_back(NumEltsNode);
2855       ZeroOps.push_back(EVTNode);
2856       Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
2857                                 &ZeroOps[0], ZeroOps.size()));
2858       IdxOps.push_back(NumEltsNode);
2859       IdxOps.push_back(EVTNode);
2860       Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
2861                                 &IdxOps[0], IdxOps.size()));
2862       Ops.push_back(NumEltsNode);
2863       Ops.push_back(EVTNode);
2864       SDOperand Result = DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2865                                      &Ops[0], Ops.size());
2866       if (NumEltsNode != DstVecSize || EVTNode != DstVecEVT) {
2867         Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2868                              DstVecSize, DstVecEVT);
2869       }
2870       return Result;
2871     }
2872   }
2873   return SDOperand();
2874 }
2875
2876 /// visitVBinOp - Visit a binary vector operation, like VADD.  IntOp indicates
2877 /// the scalar operation of the vop if it is operating on an integer vector
2878 /// (e.g. ADD) and FPOp indicates the FP version (e.g. FADD).
2879 SDOperand DAGCombiner::visitVBinOp(SDNode *N, ISD::NodeType IntOp, 
2880                                    ISD::NodeType FPOp) {
2881   MVT::ValueType EltType = cast<VTSDNode>(*(N->op_end()-1))->getVT();
2882   ISD::NodeType ScalarOp = MVT::isInteger(EltType) ? IntOp : FPOp;
2883   SDOperand LHS = N->getOperand(0);
2884   SDOperand RHS = N->getOperand(1);
2885   SDOperand Shuffle = XformToShuffleWithZero(N);
2886   if (Shuffle.Val) return Shuffle;
2887
2888   // If the LHS and RHS are VBUILD_VECTOR nodes, see if we can constant fold
2889   // this operation.
2890   if (LHS.getOpcode() == ISD::VBUILD_VECTOR && 
2891       RHS.getOpcode() == ISD::VBUILD_VECTOR) {
2892     SmallVector<SDOperand, 8> Ops;
2893     for (unsigned i = 0, e = LHS.getNumOperands()-2; i != e; ++i) {
2894       SDOperand LHSOp = LHS.getOperand(i);
2895       SDOperand RHSOp = RHS.getOperand(i);
2896       // If these two elements can't be folded, bail out.
2897       if ((LHSOp.getOpcode() != ISD::UNDEF &&
2898            LHSOp.getOpcode() != ISD::Constant &&
2899            LHSOp.getOpcode() != ISD::ConstantFP) ||
2900           (RHSOp.getOpcode() != ISD::UNDEF &&
2901            RHSOp.getOpcode() != ISD::Constant &&
2902            RHSOp.getOpcode() != ISD::ConstantFP))
2903         break;
2904       // Can't fold divide by zero.
2905       if (N->getOpcode() == ISD::VSDIV || N->getOpcode() == ISD::VUDIV) {
2906         if ((RHSOp.getOpcode() == ISD::Constant &&
2907              cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
2908             (RHSOp.getOpcode() == ISD::ConstantFP &&
2909              !cast<ConstantFPSDNode>(RHSOp.Val)->getValue()))
2910           break;
2911       }
2912       Ops.push_back(DAG.getNode(ScalarOp, EltType, LHSOp, RHSOp));
2913       AddToWorkList(Ops.back().Val);
2914       assert((Ops.back().getOpcode() == ISD::UNDEF ||
2915               Ops.back().getOpcode() == ISD::Constant ||
2916               Ops.back().getOpcode() == ISD::ConstantFP) &&
2917              "Scalar binop didn't fold!");
2918     }
2919     
2920     if (Ops.size() == LHS.getNumOperands()-2) {
2921       Ops.push_back(*(LHS.Val->op_end()-2));
2922       Ops.push_back(*(LHS.Val->op_end()-1));
2923       return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2924     }
2925   }
2926   
2927   return SDOperand();
2928 }
2929
2930 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
2931   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
2932   
2933   SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
2934                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
2935   // If we got a simplified select_cc node back from SimplifySelectCC, then
2936   // break it down into a new SETCC node, and a new SELECT node, and then return
2937   // the SELECT node, since we were called with a SELECT node.
2938   if (SCC.Val) {
2939     // Check to see if we got a select_cc back (to turn into setcc/select).
2940     // Otherwise, just return whatever node we got back, like fabs.
2941     if (SCC.getOpcode() == ISD::SELECT_CC) {
2942       SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
2943                                     SCC.getOperand(0), SCC.getOperand(1), 
2944                                     SCC.getOperand(4));
2945       AddToWorkList(SETCC.Val);
2946       return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
2947                          SCC.getOperand(3), SETCC);
2948     }
2949     return SCC;
2950   }
2951   return SDOperand();
2952 }
2953
2954 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
2955 /// are the two values being selected between, see if we can simplify the
2956 /// select.  Callers of this should assume that TheSelect is deleted if this
2957 /// returns true.  As such, they should return the appropriate thing (e.g. the
2958 /// node) back to the top-level of the DAG combiner loop to avoid it being
2959 /// looked at.
2960 ///
2961 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS, 
2962                                     SDOperand RHS) {
2963   
2964   // If this is a select from two identical things, try to pull the operation
2965   // through the select.
2966   if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
2967 #if 0
2968     std::cerr << "SELECT: ["; LHS.Val->dump();
2969     std::cerr << "] ["; RHS.Val->dump();
2970     std::cerr << "]\n";
2971 #endif
2972     
2973     // If this is a load and the token chain is identical, replace the select
2974     // of two loads with a load through a select of the address to load from.
2975     // This triggers in things like "select bool X, 10.0, 123.0" after the FP
2976     // constants have been dropped into the constant pool.
2977     if ((LHS.getOpcode() == ISD::LOAD ||
2978          LHS.getOpcode() == ISD::EXTLOAD ||
2979          LHS.getOpcode() == ISD::ZEXTLOAD ||
2980          LHS.getOpcode() == ISD::SEXTLOAD) &&
2981         // Token chains must be identical.
2982         LHS.getOperand(0) == RHS.getOperand(0) &&
2983         // If this is an EXTLOAD, the VT's must match.
2984         (LHS.getOpcode() == ISD::LOAD ||
2985          LHS.getOperand(3) == RHS.getOperand(3))) {
2986       // FIXME: this conflates two src values, discarding one.  This is not
2987       // the right thing to do, but nothing uses srcvalues now.  When they do,
2988       // turn SrcValue into a list of locations.
2989       SDOperand Addr;
2990       if (TheSelect->getOpcode() == ISD::SELECT)
2991         Addr = DAG.getNode(ISD::SELECT, LHS.getOperand(1).getValueType(),
2992                            TheSelect->getOperand(0), LHS.getOperand(1),
2993                            RHS.getOperand(1));
2994       else
2995         Addr = DAG.getNode(ISD::SELECT_CC, LHS.getOperand(1).getValueType(),
2996                            TheSelect->getOperand(0),
2997                            TheSelect->getOperand(1), 
2998                            LHS.getOperand(1), RHS.getOperand(1),
2999                            TheSelect->getOperand(4));
3000       
3001       SDOperand Load;
3002       if (LHS.getOpcode() == ISD::LOAD)
3003         Load = DAG.getLoad(TheSelect->getValueType(0), LHS.getOperand(0),
3004                            Addr, LHS.getOperand(2));
3005       else
3006         Load = DAG.getExtLoad(LHS.getOpcode(), TheSelect->getValueType(0),
3007                               LHS.getOperand(0), Addr, LHS.getOperand(2),
3008                               cast<VTSDNode>(LHS.getOperand(3))->getVT());
3009       // Users of the select now use the result of the load.
3010       CombineTo(TheSelect, Load);
3011       
3012       // Users of the old loads now use the new load's chain.  We know the
3013       // old-load value is dead now.
3014       CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
3015       CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
3016       return true;
3017     }
3018   }
3019   
3020   return false;
3021 }
3022
3023 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1, 
3024                                         SDOperand N2, SDOperand N3,
3025                                         ISD::CondCode CC) {
3026   
3027   MVT::ValueType VT = N2.getValueType();
3028   //ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
3029   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
3030   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
3031   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
3032
3033   // Determine if the condition we're dealing with is constant
3034   SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
3035   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
3036
3037   // fold select_cc true, x, y -> x
3038   if (SCCC && SCCC->getValue())
3039     return N2;
3040   // fold select_cc false, x, y -> y
3041   if (SCCC && SCCC->getValue() == 0)
3042     return N3;
3043   
3044   // Check to see if we can simplify the select into an fabs node
3045   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
3046     // Allow either -0.0 or 0.0
3047     if (CFP->getValue() == 0.0) {
3048       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
3049       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
3050           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
3051           N2 == N3.getOperand(0))
3052         return DAG.getNode(ISD::FABS, VT, N0);
3053       
3054       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
3055       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
3056           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
3057           N2.getOperand(0) == N3)
3058         return DAG.getNode(ISD::FABS, VT, N3);
3059     }
3060   }
3061   
3062   // Check to see if we can perform the "gzip trick", transforming
3063   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
3064   if (N1C && N1C->isNullValue() && N3C && N3C->isNullValue() &&
3065       MVT::isInteger(N0.getValueType()) && 
3066       MVT::isInteger(N2.getValueType()) && CC == ISD::SETLT) {
3067     MVT::ValueType XType = N0.getValueType();
3068     MVT::ValueType AType = N2.getValueType();
3069     if (XType >= AType) {
3070       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
3071       // single-bit constant.
3072       if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
3073         unsigned ShCtV = Log2_64(N2C->getValue());
3074         ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
3075         SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
3076         SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
3077         AddToWorkList(Shift.Val);
3078         if (XType > AType) {
3079           Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
3080           AddToWorkList(Shift.Val);
3081         }
3082         return DAG.getNode(ISD::AND, AType, Shift, N2);
3083       }
3084       SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
3085                                     DAG.getConstant(MVT::getSizeInBits(XType)-1,
3086                                                     TLI.getShiftAmountTy()));
3087       AddToWorkList(Shift.Val);
3088       if (XType > AType) {
3089         Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
3090         AddToWorkList(Shift.Val);
3091       }
3092       return DAG.getNode(ISD::AND, AType, Shift, N2);
3093     }
3094   }
3095   
3096   // fold select C, 16, 0 -> shl C, 4
3097   if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
3098       TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
3099     // Get a SetCC of the condition
3100     // FIXME: Should probably make sure that setcc is legal if we ever have a
3101     // target where it isn't.
3102     SDOperand Temp, SCC;
3103     // cast from setcc result type to select result type
3104     if (AfterLegalize) {
3105       SCC  = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
3106       Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
3107     } else {
3108       SCC  = DAG.getSetCC(MVT::i1, N0, N1, CC);
3109       Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
3110     }
3111     AddToWorkList(SCC.Val);
3112     AddToWorkList(Temp.Val);
3113     // shl setcc result by log2 n2c
3114     return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
3115                        DAG.getConstant(Log2_64(N2C->getValue()),
3116                                        TLI.getShiftAmountTy()));
3117   }
3118     
3119   // Check to see if this is the equivalent of setcc
3120   // FIXME: Turn all of these into setcc if setcc if setcc is legal
3121   // otherwise, go ahead with the folds.
3122   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
3123     MVT::ValueType XType = N0.getValueType();
3124     if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
3125       SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
3126       if (Res.getValueType() != VT)
3127         Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
3128       return Res;
3129     }
3130     
3131     // seteq X, 0 -> srl (ctlz X, log2(size(X)))
3132     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 
3133         TLI.isOperationLegal(ISD::CTLZ, XType)) {
3134       SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
3135       return DAG.getNode(ISD::SRL, XType, Ctlz, 
3136                          DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
3137                                          TLI.getShiftAmountTy()));
3138     }
3139     // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
3140     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 
3141       SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
3142                                     N0);
3143       SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0, 
3144                                     DAG.getConstant(~0ULL, XType));
3145       return DAG.getNode(ISD::SRL, XType, 
3146                          DAG.getNode(ISD::AND, XType, NegN0, NotN0),
3147                          DAG.getConstant(MVT::getSizeInBits(XType)-1,
3148                                          TLI.getShiftAmountTy()));
3149     }
3150     // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
3151     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
3152       SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
3153                                    DAG.getConstant(MVT::getSizeInBits(XType)-1,
3154                                                    TLI.getShiftAmountTy()));
3155       return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
3156     }
3157   }
3158   
3159   // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
3160   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
3161   if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
3162       N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) {
3163     if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0))) {
3164       MVT::ValueType XType = N0.getValueType();
3165       if (SubC->isNullValue() && MVT::isInteger(XType)) {
3166         SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
3167                                     DAG.getConstant(MVT::getSizeInBits(XType)-1,
3168                                                     TLI.getShiftAmountTy()));
3169         SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
3170         AddToWorkList(Shift.Val);
3171         AddToWorkList(Add.Val);
3172         return DAG.getNode(ISD::XOR, XType, Add, Shift);
3173       }
3174     }
3175   }
3176
3177   return SDOperand();
3178 }
3179
3180 SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
3181                                      SDOperand N1, ISD::CondCode Cond,
3182                                      bool foldBooleans) {
3183   // These setcc operations always fold.
3184   switch (Cond) {
3185   default: break;
3186   case ISD::SETFALSE:
3187   case ISD::SETFALSE2: return DAG.getConstant(0, VT);
3188   case ISD::SETTRUE:
3189   case ISD::SETTRUE2:  return DAG.getConstant(1, VT);
3190   }
3191
3192   if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
3193     uint64_t C1 = N1C->getValue();
3194     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val)) {
3195       uint64_t C0 = N0C->getValue();
3196
3197       // Sign extend the operands if required
3198       if (ISD::isSignedIntSetCC(Cond)) {
3199         C0 = N0C->getSignExtended();
3200         C1 = N1C->getSignExtended();
3201       }
3202
3203       switch (Cond) {
3204       default: assert(0 && "Unknown integer setcc!");
3205       case ISD::SETEQ:  return DAG.getConstant(C0 == C1, VT);
3206       case ISD::SETNE:  return DAG.getConstant(C0 != C1, VT);
3207       case ISD::SETULT: return DAG.getConstant(C0 <  C1, VT);
3208       case ISD::SETUGT: return DAG.getConstant(C0 >  C1, VT);
3209       case ISD::SETULE: return DAG.getConstant(C0 <= C1, VT);
3210       case ISD::SETUGE: return DAG.getConstant(C0 >= C1, VT);
3211       case ISD::SETLT:  return DAG.getConstant((int64_t)C0 <  (int64_t)C1, VT);
3212       case ISD::SETGT:  return DAG.getConstant((int64_t)C0 >  (int64_t)C1, VT);
3213       case ISD::SETLE:  return DAG.getConstant((int64_t)C0 <= (int64_t)C1, VT);
3214       case ISD::SETGE:  return DAG.getConstant((int64_t)C0 >= (int64_t)C1, VT);
3215       }
3216     } else {
3217       // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3218       if (N0.getOpcode() == ISD::ZERO_EXTEND) {
3219         unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
3220
3221         // If the comparison constant has bits in the upper part, the
3222         // zero-extended value could never match.
3223         if (C1 & (~0ULL << InSize)) {
3224           unsigned VSize = MVT::getSizeInBits(N0.getValueType());
3225           switch (Cond) {
3226           case ISD::SETUGT:
3227           case ISD::SETUGE:
3228           case ISD::SETEQ: return DAG.getConstant(0, VT);
3229           case ISD::SETULT:
3230           case ISD::SETULE:
3231           case ISD::SETNE: return DAG.getConstant(1, VT);
3232           case ISD::SETGT:
3233           case ISD::SETGE:
3234             // True if the sign bit of C1 is set.
3235             return DAG.getConstant((C1 & (1ULL << VSize)) != 0, VT);
3236           case ISD::SETLT:
3237           case ISD::SETLE:
3238             // True if the sign bit of C1 isn't set.
3239             return DAG.getConstant((C1 & (1ULL << VSize)) == 0, VT);
3240           default:
3241             break;
3242           }
3243         }
3244
3245         // Otherwise, we can perform the comparison with the low bits.
3246         switch (Cond) {
3247         case ISD::SETEQ:
3248         case ISD::SETNE:
3249         case ISD::SETUGT:
3250         case ISD::SETUGE:
3251         case ISD::SETULT:
3252         case ISD::SETULE:
3253           return DAG.getSetCC(VT, N0.getOperand(0),
3254                           DAG.getConstant(C1, N0.getOperand(0).getValueType()),
3255                           Cond);
3256         default:
3257           break;   // todo, be more careful with signed comparisons
3258         }
3259       } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3260                  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3261         MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
3262         unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
3263         MVT::ValueType ExtDstTy = N0.getValueType();
3264         unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
3265
3266         // If the extended part has any inconsistent bits, it cannot ever
3267         // compare equal.  In other words, they have to be all ones or all
3268         // zeros.
3269         uint64_t ExtBits =
3270           (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
3271         if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
3272           return DAG.getConstant(Cond == ISD::SETNE, VT);
3273         
3274         SDOperand ZextOp;
3275         MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
3276         if (Op0Ty == ExtSrcTy) {
3277           ZextOp = N0.getOperand(0);
3278         } else {
3279           int64_t Imm = ~0ULL >> (64-ExtSrcTyBits);
3280           ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
3281                                DAG.getConstant(Imm, Op0Ty));
3282         }
3283         AddToWorkList(ZextOp.Val);
3284         // Otherwise, make this a use of a zext.
3285         return DAG.getSetCC(VT, ZextOp, 
3286                             DAG.getConstant(C1 & (~0ULL>>(64-ExtSrcTyBits)), 
3287                                             ExtDstTy),
3288                             Cond);
3289       } else if ((N1C->getValue() == 0 || N1C->getValue() == 1) &&
3290                  (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3291                  (N0.getOpcode() == ISD::XOR ||
3292                   (N0.getOpcode() == ISD::AND && 
3293                    N0.getOperand(0).getOpcode() == ISD::XOR &&
3294                    N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
3295                  isa<ConstantSDNode>(N0.getOperand(1)) &&
3296                  cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
3297         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We can
3298         // only do this if the top bits are known zero.
3299         if (TLI.MaskedValueIsZero(N1, 
3300                                   MVT::getIntVTBitMask(N0.getValueType())-1)) {
3301           // Okay, get the un-inverted input value.
3302           SDOperand Val;
3303           if (N0.getOpcode() == ISD::XOR)
3304             Val = N0.getOperand(0);
3305           else {
3306             assert(N0.getOpcode() == ISD::AND && 
3307                    N0.getOperand(0).getOpcode() == ISD::XOR);
3308             // ((X^1)&1)^1 -> X & 1
3309             Val = DAG.getNode(ISD::AND, N0.getValueType(),
3310                               N0.getOperand(0).getOperand(0), N0.getOperand(1));
3311           }
3312           return DAG.getSetCC(VT, Val, N1,
3313                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3314         }
3315       }
3316       
3317       uint64_t MinVal, MaxVal;
3318       unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
3319       if (ISD::isSignedIntSetCC(Cond)) {
3320         MinVal = 1ULL << (OperandBitSize-1);
3321         if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
3322           MaxVal = ~0ULL >> (65-OperandBitSize);
3323         else
3324           MaxVal = 0;
3325       } else {
3326         MinVal = 0;
3327         MaxVal = ~0ULL >> (64-OperandBitSize);
3328       }
3329
3330       // Canonicalize GE/LE comparisons to use GT/LT comparisons.
3331       if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
3332         if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
3333         --C1;                                          // X >= C0 --> X > (C0-1)
3334         return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
3335                         (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
3336       }
3337
3338       if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
3339         if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
3340         ++C1;                                          // X <= C0 --> X < (C0+1)
3341         return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
3342                         (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
3343       }
3344
3345       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
3346         return DAG.getConstant(0, VT);      // X < MIN --> false
3347
3348       // Canonicalize setgt X, Min --> setne X, Min
3349       if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
3350         return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
3351       // Canonicalize setlt X, Max --> setne X, Max
3352       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
3353         return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
3354
3355       // If we have setult X, 1, turn it into seteq X, 0
3356       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
3357         return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
3358                         ISD::SETEQ);
3359       // If we have setugt X, Max-1, turn it into seteq X, Max
3360       else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
3361         return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
3362                         ISD::SETEQ);
3363
3364       // If we have "setcc X, C0", check to see if we can shrink the immediate
3365       // by changing cc.
3366
3367       // SETUGT X, SINTMAX  -> SETLT X, 0
3368       if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
3369           C1 == (~0ULL >> (65-OperandBitSize)))
3370         return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
3371                             ISD::SETLT);
3372
3373       // FIXME: Implement the rest of these.
3374
3375       // Fold bit comparisons when we can.
3376       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3377           VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
3378         if (ConstantSDNode *AndRHS =
3379                     dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3380           if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
3381             // Perform the xform if the AND RHS is a single bit.
3382             if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
3383               return DAG.getNode(ISD::SRL, VT, N0,
3384                              DAG.getConstant(Log2_64(AndRHS->getValue()),
3385                                                    TLI.getShiftAmountTy()));
3386             }
3387           } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
3388             // (X & 8) == 8  -->  (X & 8) >> 3
3389             // Perform the xform if C1 is a single bit.
3390             if ((C1 & (C1-1)) == 0) {
3391               return DAG.getNode(ISD::SRL, VT, N0,
3392                           DAG.getConstant(Log2_64(C1),TLI.getShiftAmountTy()));
3393             }
3394           }
3395         }
3396     }
3397   } else if (isa<ConstantSDNode>(N0.Val)) {
3398       // Ensure that the constant occurs on the RHS.
3399     return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
3400   }
3401
3402   if (ConstantFPSDNode *N0C = dyn_cast<ConstantFPSDNode>(N0.Val))
3403     if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
3404       double C0 = N0C->getValue(), C1 = N1C->getValue();
3405
3406       switch (Cond) {
3407       default: break; // FIXME: Implement the rest of these!
3408       case ISD::SETEQ:  return DAG.getConstant(C0 == C1, VT);
3409       case ISD::SETNE:  return DAG.getConstant(C0 != C1, VT);
3410       case ISD::SETLT:  return DAG.getConstant(C0 < C1, VT);
3411       case ISD::SETGT:  return DAG.getConstant(C0 > C1, VT);
3412       case ISD::SETLE:  return DAG.getConstant(C0 <= C1, VT);
3413       case ISD::SETGE:  return DAG.getConstant(C0 >= C1, VT);
3414       }
3415     } else {
3416       // Ensure that the constant occurs on the RHS.
3417       return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
3418     }
3419
3420   if (N0 == N1) {
3421     // We can always fold X == Y for integer setcc's.
3422     if (MVT::isInteger(N0.getValueType()))
3423       return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
3424     unsigned UOF = ISD::getUnorderedFlavor(Cond);
3425     if (UOF == 2)   // FP operators that are undefined on NaNs.
3426       return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
3427     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
3428       return DAG.getConstant(UOF, VT);
3429     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
3430     // if it is not already.
3431     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
3432     if (NewCond != Cond)
3433       return DAG.getSetCC(VT, N0, N1, NewCond);
3434   }
3435
3436   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3437       MVT::isInteger(N0.getValueType())) {
3438     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
3439         N0.getOpcode() == ISD::XOR) {
3440       // Simplify (X+Y) == (X+Z) -->  Y == Z
3441       if (N0.getOpcode() == N1.getOpcode()) {
3442         if (N0.getOperand(0) == N1.getOperand(0))
3443           return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
3444         if (N0.getOperand(1) == N1.getOperand(1))
3445           return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
3446         if (DAG.isCommutativeBinOp(N0.getOpcode())) {
3447           // If X op Y == Y op X, try other combinations.
3448           if (N0.getOperand(0) == N1.getOperand(1))
3449             return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
3450           if (N0.getOperand(1) == N1.getOperand(0))
3451             return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
3452         }
3453       }
3454       
3455       if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
3456         if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3457           // Turn (X+C1) == C2 --> X == C2-C1
3458           if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
3459             return DAG.getSetCC(VT, N0.getOperand(0),
3460                               DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
3461                                 N0.getValueType()), Cond);
3462           }
3463           
3464           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
3465           if (N0.getOpcode() == ISD::XOR)
3466             // If we know that all of the inverted bits are zero, don't bother
3467             // performing the inversion.
3468             if (TLI.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getValue()))
3469               return DAG.getSetCC(VT, N0.getOperand(0),
3470                               DAG.getConstant(LHSR->getValue()^RHSC->getValue(),
3471                                               N0.getValueType()), Cond);
3472         }
3473         
3474         // Turn (C1-X) == C2 --> X == C1-C2
3475         if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
3476           if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
3477             return DAG.getSetCC(VT, N0.getOperand(1),
3478                              DAG.getConstant(SUBC->getValue()-RHSC->getValue(),
3479                                              N0.getValueType()), Cond);
3480           }
3481         }          
3482       }
3483
3484       // Simplify (X+Z) == X -->  Z == 0
3485       if (N0.getOperand(0) == N1)
3486         return DAG.getSetCC(VT, N0.getOperand(1),
3487                         DAG.getConstant(0, N0.getValueType()), Cond);
3488       if (N0.getOperand(1) == N1) {
3489         if (DAG.isCommutativeBinOp(N0.getOpcode()))
3490           return DAG.getSetCC(VT, N0.getOperand(0),
3491                           DAG.getConstant(0, N0.getValueType()), Cond);
3492         else {
3493           assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
3494           // (Z-X) == X  --> Z == X<<1
3495           SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
3496                                      N1, 
3497                                      DAG.getConstant(1,TLI.getShiftAmountTy()));
3498           AddToWorkList(SH.Val);
3499           return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
3500         }
3501       }
3502     }
3503
3504     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
3505         N1.getOpcode() == ISD::XOR) {
3506       // Simplify  X == (X+Z) -->  Z == 0
3507       if (N1.getOperand(0) == N0) {
3508         return DAG.getSetCC(VT, N1.getOperand(1),
3509                         DAG.getConstant(0, N1.getValueType()), Cond);
3510       } else if (N1.getOperand(1) == N0) {
3511         if (DAG.isCommutativeBinOp(N1.getOpcode())) {
3512           return DAG.getSetCC(VT, N1.getOperand(0),
3513                           DAG.getConstant(0, N1.getValueType()), Cond);
3514         } else {
3515           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
3516           // X == (Z-X)  --> X<<1 == Z
3517           SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0, 
3518                                      DAG.getConstant(1,TLI.getShiftAmountTy()));
3519           AddToWorkList(SH.Val);
3520           return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
3521         }
3522       }
3523     }
3524   }
3525
3526   // Fold away ALL boolean setcc's.
3527   SDOperand Temp;
3528   if (N0.getValueType() == MVT::i1 && foldBooleans) {
3529     switch (Cond) {
3530     default: assert(0 && "Unknown integer setcc!");
3531     case ISD::SETEQ:  // X == Y  -> (X^Y)^1
3532       Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
3533       N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
3534       AddToWorkList(Temp.Val);
3535       break;
3536     case ISD::SETNE:  // X != Y   -->  (X^Y)
3537       N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
3538       break;
3539     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
3540     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
3541       Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
3542       N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
3543       AddToWorkList(Temp.Val);
3544       break;
3545     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
3546     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
3547       Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
3548       N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
3549       AddToWorkList(Temp.Val);
3550       break;
3551     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
3552     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
3553       Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
3554       N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
3555       AddToWorkList(Temp.Val);
3556       break;
3557     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
3558     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
3559       Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
3560       N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
3561       break;
3562     }
3563     if (VT != MVT::i1) {
3564       AddToWorkList(N0.Val);
3565       // FIXME: If running after legalize, we probably can't do this.
3566       N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
3567     }
3568     return N0;
3569   }
3570
3571   // Could not fold it.
3572   return SDOperand();
3573 }
3574
3575 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
3576 /// return a DAG expression to select that will generate the same value by
3577 /// multiplying by a magic number.  See:
3578 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
3579 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
3580   std::vector<SDNode*> Built;
3581   SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
3582
3583   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
3584        ii != ee; ++ii)
3585     AddToWorkList(*ii);
3586   return S;
3587 }
3588
3589 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
3590 /// return a DAG expression to select that will generate the same value by
3591 /// multiplying by a magic number.  See:
3592 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
3593 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
3594   std::vector<SDNode*> Built;
3595   SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
3596
3597   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
3598        ii != ee; ++ii)
3599     AddToWorkList(*ii);
3600   return S;
3601 }
3602
3603 // SelectionDAG::Combine - This is the entry point for the file.
3604 //
3605 void SelectionDAG::Combine(bool RunningAfterLegalize) {
3606   /// run - This is the main entry point to this class.
3607   ///
3608   DAGCombiner(*this).Run(RunningAfterLegalize);
3609 }