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