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