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