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