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