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