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