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