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