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