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