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