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