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