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