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