The guaranteed alignment of ptr+offset is only the minimum of
[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   if (!N->hasAnyUseOfValue(1) &&
1424       (!AfterLegalize ||
1425        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1426     DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0),
1427                                   DAG.getNode(LoOp, N->getValueType(0),
1428                                               N->op_begin(),
1429                                               N->getNumOperands()));
1430     return true;
1431   }
1432
1433   // If the low half is not needed, just compute the high half.
1434   if (!N->hasAnyUseOfValue(0) &&
1435       (!AfterLegalize ||
1436        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1437     DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
1438                                   DAG.getNode(HiOp, N->getValueType(1),
1439                                               N->op_begin(),
1440                                               N->getNumOperands()));
1441     return true;
1442   }
1443
1444   // If the two computed results can be siplified separately, separate them.
1445   SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1446                              N->op_begin(), N->getNumOperands());
1447   SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1448                              N->op_begin(), N->getNumOperands());
1449   unsigned LoExists = !Lo.use_empty();
1450   unsigned HiExists = !Hi.use_empty();
1451   SDOperand LoOpt = Lo;
1452   SDOperand HiOpt = Hi;
1453   if (!LoExists || !HiExists) {
1454     SDOperand Pair = DAG.getNode(ISD::BUILD_PAIR, MVT::Other, Lo, Hi);
1455     assert(Pair.use_empty() && "Pair with type MVT::Other already exists!");
1456     LoOpt = combine(Lo.Val);
1457     HiOpt = combine(Hi.Val);
1458     if (!LoOpt.Val)
1459       LoOpt = Pair.getOperand(0);
1460     if (!HiOpt.Val)
1461       HiOpt = Pair.getOperand(1);
1462     DAG.DeleteNode(Pair.Val);
1463   }
1464   if ((LoExists || LoOpt != Lo) &&
1465       (HiExists || HiOpt != Hi) &&
1466       TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()) &&
1467       TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())) {
1468     DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), LoOpt);
1469     DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), HiOpt);
1470     return true;
1471   }
1472
1473   return false;
1474 }
1475
1476 SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1477   
1478   if (SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
1479     return SDOperand();
1480
1481   return SDOperand();
1482 }
1483
1484 SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1485   
1486   if (SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
1487     return SDOperand();
1488
1489   return SDOperand();
1490 }
1491
1492 SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
1493   
1494   if (SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
1495     return SDOperand();
1496   
1497   return SDOperand();
1498 }
1499
1500 SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
1501   
1502   if (SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
1503     return SDOperand();
1504   
1505   return SDOperand();
1506 }
1507
1508 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1509 /// two operands of the same opcode, try to simplify it.
1510 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1511   SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1512   MVT::ValueType VT = N0.getValueType();
1513   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1514   
1515   // For each of OP in AND/OR/XOR:
1516   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1517   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1518   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1519   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1520   if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1521        N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1522       N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1523     SDOperand ORNode = DAG.getNode(N->getOpcode(), 
1524                                    N0.getOperand(0).getValueType(),
1525                                    N0.getOperand(0), N1.getOperand(0));
1526     AddToWorkList(ORNode.Val);
1527     return DAG.getNode(N0.getOpcode(), VT, ORNode);
1528   }
1529   
1530   // For each of OP in SHL/SRL/SRA/AND...
1531   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1532   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
1533   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1534   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1535        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1536       N0.getOperand(1) == N1.getOperand(1)) {
1537     SDOperand ORNode = DAG.getNode(N->getOpcode(),
1538                                    N0.getOperand(0).getValueType(),
1539                                    N0.getOperand(0), N1.getOperand(0));
1540     AddToWorkList(ORNode.Val);
1541     return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1542   }
1543   
1544   return SDOperand();
1545 }
1546
1547 SDOperand DAGCombiner::visitAND(SDNode *N) {
1548   SDOperand N0 = N->getOperand(0);
1549   SDOperand N1 = N->getOperand(1);
1550   SDOperand LL, LR, RL, RR, CC0, CC1;
1551   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1552   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1553   MVT::ValueType VT = N1.getValueType();
1554   
1555   // fold vector ops
1556   if (MVT::isVector(VT)) {
1557     SDOperand FoldedVOp = SimplifyVBinOp(N);
1558     if (FoldedVOp.Val) return FoldedVOp;
1559   }
1560   
1561   // fold (and x, undef) -> 0
1562   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1563     return DAG.getConstant(0, VT);
1564   // fold (and c1, c2) -> c1&c2
1565   if (N0C && N1C)
1566     return DAG.getNode(ISD::AND, VT, N0, N1);
1567   // canonicalize constant to RHS
1568   if (N0C && !N1C)
1569     return DAG.getNode(ISD::AND, VT, N1, N0);
1570   // fold (and x, -1) -> x
1571   if (N1C && N1C->isAllOnesValue())
1572     return N0;
1573   // if (and x, c) is known to be zero, return 0
1574   if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1575     return DAG.getConstant(0, VT);
1576   // reassociate and
1577   SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1578   if (RAND.Val != 0)
1579     return RAND;
1580   // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1581   if (N1C && N0.getOpcode() == ISD::OR)
1582     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1583       if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
1584         return N1;
1585   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1586   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1587     unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
1588     if (DAG.MaskedValueIsZero(N0.getOperand(0),
1589                               ~N1C->getValue() & InMask)) {
1590       SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1591                                    N0.getOperand(0));
1592       
1593       // Replace uses of the AND with uses of the Zero extend node.
1594       CombineTo(N, Zext);
1595       
1596       // We actually want to replace all uses of the any_extend with the
1597       // zero_extend, to avoid duplicating things.  This will later cause this
1598       // AND to be folded.
1599       CombineTo(N0.Val, Zext);
1600       return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1601     }
1602   }
1603   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1604   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1605     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1606     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1607     
1608     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1609         MVT::isInteger(LL.getValueType())) {
1610       // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1611       if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
1612         SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1613         AddToWorkList(ORNode.Val);
1614         return DAG.getSetCC(VT, ORNode, LR, Op1);
1615       }
1616       // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1617       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1618         SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1619         AddToWorkList(ANDNode.Val);
1620         return DAG.getSetCC(VT, ANDNode, LR, Op1);
1621       }
1622       // fold (X >  -1) & (Y >  -1) -> (X|Y > -1)
1623       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1624         SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1625         AddToWorkList(ORNode.Val);
1626         return DAG.getSetCC(VT, ORNode, LR, Op1);
1627       }
1628     }
1629     // canonicalize equivalent to ll == rl
1630     if (LL == RR && LR == RL) {
1631       Op1 = ISD::getSetCCSwappedOperands(Op1);
1632       std::swap(RL, RR);
1633     }
1634     if (LL == RL && LR == RR) {
1635       bool isInteger = MVT::isInteger(LL.getValueType());
1636       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1637       if (Result != ISD::SETCC_INVALID)
1638         return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1639     }
1640   }
1641
1642   // Simplify: and (op x...), (op y...)  -> (op (and x, y))
1643   if (N0.getOpcode() == N1.getOpcode()) {
1644     SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1645     if (Tmp.Val) return Tmp;
1646   }
1647   
1648   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1649   // fold (and (sra)) -> (and (srl)) when possible.
1650   if (!MVT::isVector(VT) &&
1651       SimplifyDemandedBits(SDOperand(N, 0)))
1652     return SDOperand(N, 0);
1653   // fold (zext_inreg (extload x)) -> (zextload x)
1654   if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1655     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1656     MVT::ValueType EVT = LN0->getLoadedVT();
1657     // If we zero all the possible extended bits, then we can turn this into
1658     // a zextload if we are running before legalize or the operation is legal.
1659     if (DAG.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1660         (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1661       SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1662                                          LN0->getBasePtr(), LN0->getSrcValue(),
1663                                          LN0->getSrcValueOffset(), EVT,
1664                                          LN0->isVolatile(), 
1665                                          LN0->getAlignment());
1666       AddToWorkList(N);
1667       CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1668       return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1669     }
1670   }
1671   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1672   if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1673       N0.hasOneUse()) {
1674     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1675     MVT::ValueType EVT = LN0->getLoadedVT();
1676     // If we zero all the possible extended bits, then we can turn this into
1677     // a zextload if we are running before legalize or the operation is legal.
1678     if (DAG.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1679         (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1680       SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1681                                          LN0->getBasePtr(), LN0->getSrcValue(),
1682                                          LN0->getSrcValueOffset(), EVT,
1683                                          LN0->isVolatile(), 
1684                                          LN0->getAlignment());
1685       AddToWorkList(N);
1686       CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1687       return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1688     }
1689   }
1690   
1691   // fold (and (load x), 255) -> (zextload x, i8)
1692   // fold (and (extload x, i16), 255) -> (zextload x, i8)
1693   if (N1C && N0.getOpcode() == ISD::LOAD) {
1694     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1695     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1696         LN0->getAddressingMode() == ISD::UNINDEXED &&
1697         N0.hasOneUse()) {
1698       MVT::ValueType EVT, LoadedVT;
1699       if (N1C->getValue() == 255)
1700         EVT = MVT::i8;
1701       else if (N1C->getValue() == 65535)
1702         EVT = MVT::i16;
1703       else if (N1C->getValue() == ~0U)
1704         EVT = MVT::i32;
1705       else
1706         EVT = MVT::Other;
1707     
1708       LoadedVT = LN0->getLoadedVT();
1709       if (EVT != MVT::Other && LoadedVT > EVT &&
1710           (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1711         MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1712         // For big endian targets, we need to add an offset to the pointer to
1713         // load the correct bytes.  For little endian systems, we merely need to
1714         // read fewer bytes from the same pointer.
1715         unsigned PtrOff =
1716           (MVT::getSizeInBits(LoadedVT) - MVT::getSizeInBits(EVT)) / 8;
1717         unsigned Alignment = LN0->getAlignment();
1718         SDOperand NewPtr = LN0->getBasePtr();
1719         if (!TLI.isLittleEndian()) {
1720           NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1721                                DAG.getConstant(PtrOff, PtrType));
1722           Alignment = MinAlign(Alignment, PtrOff);
1723         }
1724         AddToWorkList(NewPtr.Val);
1725         SDOperand Load =
1726           DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1727                          LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1728                          LN0->isVolatile(), Alignment);
1729         AddToWorkList(N);
1730         CombineTo(N0.Val, Load, Load.getValue(1));
1731         return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1732       }
1733     }
1734   }
1735   
1736   return SDOperand();
1737 }
1738
1739 SDOperand DAGCombiner::visitOR(SDNode *N) {
1740   SDOperand N0 = N->getOperand(0);
1741   SDOperand N1 = N->getOperand(1);
1742   SDOperand LL, LR, RL, RR, CC0, CC1;
1743   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1744   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1745   MVT::ValueType VT = N1.getValueType();
1746   unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1747   
1748   // fold vector ops
1749   if (MVT::isVector(VT)) {
1750     SDOperand FoldedVOp = SimplifyVBinOp(N);
1751     if (FoldedVOp.Val) return FoldedVOp;
1752   }
1753   
1754   // fold (or x, undef) -> -1
1755   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1756     return DAG.getConstant(~0ULL, VT);
1757   // fold (or c1, c2) -> c1|c2
1758   if (N0C && N1C)
1759     return DAG.getNode(ISD::OR, VT, N0, N1);
1760   // canonicalize constant to RHS
1761   if (N0C && !N1C)
1762     return DAG.getNode(ISD::OR, VT, N1, N0);
1763   // fold (or x, 0) -> x
1764   if (N1C && N1C->isNullValue())
1765     return N0;
1766   // fold (or x, -1) -> -1
1767   if (N1C && N1C->isAllOnesValue())
1768     return N1;
1769   // fold (or x, c) -> c iff (x & ~c) == 0
1770   if (N1C && 
1771       DAG.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
1772     return N1;
1773   // reassociate or
1774   SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1775   if (ROR.Val != 0)
1776     return ROR;
1777   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1778   if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1779              isa<ConstantSDNode>(N0.getOperand(1))) {
1780     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1781     return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1782                                                  N1),
1783                        DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1784   }
1785   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1786   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1787     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1788     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1789     
1790     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1791         MVT::isInteger(LL.getValueType())) {
1792       // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1793       // fold (X <  0) | (Y <  0) -> (X|Y < 0)
1794       if (cast<ConstantSDNode>(LR)->getValue() == 0 && 
1795           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1796         SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1797         AddToWorkList(ORNode.Val);
1798         return DAG.getSetCC(VT, ORNode, LR, Op1);
1799       }
1800       // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1801       // fold (X >  -1) | (Y >  -1) -> (X&Y >  -1)
1802       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 
1803           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1804         SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1805         AddToWorkList(ANDNode.Val);
1806         return DAG.getSetCC(VT, ANDNode, LR, Op1);
1807       }
1808     }
1809     // canonicalize equivalent to ll == rl
1810     if (LL == RR && LR == RL) {
1811       Op1 = ISD::getSetCCSwappedOperands(Op1);
1812       std::swap(RL, RR);
1813     }
1814     if (LL == RL && LR == RR) {
1815       bool isInteger = MVT::isInteger(LL.getValueType());
1816       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1817       if (Result != ISD::SETCC_INVALID)
1818         return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1819     }
1820   }
1821   
1822   // Simplify: or (op x...), (op y...)  -> (op (or x, y))
1823   if (N0.getOpcode() == N1.getOpcode()) {
1824     SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1825     if (Tmp.Val) return Tmp;
1826   }
1827   
1828   // (X & C1) | (Y & C2)  -> (X|Y) & C3  if possible.
1829   if (N0.getOpcode() == ISD::AND &&
1830       N1.getOpcode() == ISD::AND &&
1831       N0.getOperand(1).getOpcode() == ISD::Constant &&
1832       N1.getOperand(1).getOpcode() == ISD::Constant &&
1833       // Don't increase # computations.
1834       (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1835     // We can only do this xform if we know that bits from X that are set in C2
1836     // but not in C1 are already zero.  Likewise for Y.
1837     uint64_t LHSMask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1838     uint64_t RHSMask = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
1839     
1840     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1841         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1842       SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1843       return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1844     }
1845   }
1846   
1847   
1848   // See if this is some rotate idiom.
1849   if (SDNode *Rot = MatchRotate(N0, N1))
1850     return SDOperand(Rot, 0);
1851
1852   return SDOperand();
1853 }
1854
1855
1856 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1857 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1858   if (Op.getOpcode() == ISD::AND) {
1859     if (isa<ConstantSDNode>(Op.getOperand(1))) {
1860       Mask = Op.getOperand(1);
1861       Op = Op.getOperand(0);
1862     } else {
1863       return false;
1864     }
1865   }
1866   
1867   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1868     Shift = Op;
1869     return true;
1870   }
1871   return false;  
1872 }
1873
1874
1875 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
1876 // idioms for rotate, and if the target supports rotation instructions, generate
1877 // a rot[lr].
1878 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1879   // Must be a legal type.  Expanded an promoted things won't work with rotates.
1880   MVT::ValueType VT = LHS.getValueType();
1881   if (!TLI.isTypeLegal(VT)) return 0;
1882
1883   // The target must have at least one rotate flavor.
1884   bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1885   bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1886   if (!HasROTL && !HasROTR) return 0;
1887   
1888   // Match "(X shl/srl V1) & V2" where V2 may not be present.
1889   SDOperand LHSShift;   // The shift.
1890   SDOperand LHSMask;    // AND value if any.
1891   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1892     return 0; // Not part of a rotate.
1893
1894   SDOperand RHSShift;   // The shift.
1895   SDOperand RHSMask;    // AND value if any.
1896   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1897     return 0; // Not part of a rotate.
1898   
1899   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1900     return 0;   // Not shifting the same value.
1901
1902   if (LHSShift.getOpcode() == RHSShift.getOpcode())
1903     return 0;   // Shifts must disagree.
1904     
1905   // Canonicalize shl to left side in a shl/srl pair.
1906   if (RHSShift.getOpcode() == ISD::SHL) {
1907     std::swap(LHS, RHS);
1908     std::swap(LHSShift, RHSShift);
1909     std::swap(LHSMask , RHSMask );
1910   }
1911
1912   unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1913   SDOperand LHSShiftArg = LHSShift.getOperand(0);
1914   SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1915   SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1916
1917   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1918   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1919   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
1920       RHSShiftAmt.getOpcode() == ISD::Constant) {
1921     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
1922     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
1923     if ((LShVal + RShVal) != OpSizeInBits)
1924       return 0;
1925
1926     SDOperand Rot;
1927     if (HasROTL)
1928       Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
1929     else
1930       Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
1931     
1932     // If there is an AND of either shifted operand, apply it to the result.
1933     if (LHSMask.Val || RHSMask.Val) {
1934       uint64_t Mask = MVT::getIntVTBitMask(VT);
1935       
1936       if (LHSMask.Val) {
1937         uint64_t RHSBits = (1ULL << LShVal)-1;
1938         Mask &= cast<ConstantSDNode>(LHSMask)->getValue() | RHSBits;
1939       }
1940       if (RHSMask.Val) {
1941         uint64_t LHSBits = ~((1ULL << (OpSizeInBits-RShVal))-1);
1942         Mask &= cast<ConstantSDNode>(RHSMask)->getValue() | LHSBits;
1943       }
1944         
1945       Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
1946     }
1947     
1948     return Rot.Val;
1949   }
1950   
1951   // If there is a mask here, and we have a variable shift, we can't be sure
1952   // that we're masking out the right stuff.
1953   if (LHSMask.Val || RHSMask.Val)
1954     return 0;
1955   
1956   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
1957   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
1958   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
1959       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
1960     if (ConstantSDNode *SUBC = 
1961           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
1962       if (SUBC->getValue() == OpSizeInBits)
1963         if (HasROTL)
1964           return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1965         else
1966           return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
1967     }
1968   }
1969   
1970   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
1971   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
1972   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
1973       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
1974     if (ConstantSDNode *SUBC = 
1975           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
1976       if (SUBC->getValue() == OpSizeInBits)
1977         if (HasROTL)
1978           return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1979         else
1980           return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
1981     }
1982   }
1983
1984   // Look for sign/zext/any-extended cases:
1985   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
1986        || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
1987        || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
1988       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
1989        || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
1990        || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
1991     SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
1992     SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
1993     if (RExtOp0.getOpcode() == ISD::SUB &&
1994         RExtOp0.getOperand(1) == LExtOp0) {
1995       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
1996       //   (rotr x, y)
1997       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
1998       //   (rotl x, (sub 32, y))
1999       if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2000         if (SUBC->getValue() == OpSizeInBits) {
2001           if (HasROTL)
2002             return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2003           else
2004             return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2005         }
2006       }
2007     } else if (LExtOp0.getOpcode() == ISD::SUB &&
2008                RExtOp0 == LExtOp0.getOperand(1)) {
2009       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) -> 
2010       //   (rotl x, y)
2011       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2012       //   (rotr x, (sub 32, y))
2013       if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2014         if (SUBC->getValue() == OpSizeInBits) {
2015           if (HasROTL)
2016             return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2017           else
2018             return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2019         }
2020       }
2021     }
2022   }
2023   
2024   return 0;
2025 }
2026
2027
2028 SDOperand DAGCombiner::visitXOR(SDNode *N) {
2029   SDOperand N0 = N->getOperand(0);
2030   SDOperand N1 = N->getOperand(1);
2031   SDOperand LHS, RHS, CC;
2032   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2033   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2034   MVT::ValueType VT = N0.getValueType();
2035   
2036   // fold vector ops
2037   if (MVT::isVector(VT)) {
2038     SDOperand FoldedVOp = SimplifyVBinOp(N);
2039     if (FoldedVOp.Val) return FoldedVOp;
2040   }
2041   
2042   // fold (xor x, undef) -> undef
2043   if (N0.getOpcode() == ISD::UNDEF)
2044     return N0;
2045   if (N1.getOpcode() == ISD::UNDEF)
2046     return N1;
2047   // fold (xor c1, c2) -> c1^c2
2048   if (N0C && N1C)
2049     return DAG.getNode(ISD::XOR, VT, N0, N1);
2050   // canonicalize constant to RHS
2051   if (N0C && !N1C)
2052     return DAG.getNode(ISD::XOR, VT, N1, N0);
2053   // fold (xor x, 0) -> x
2054   if (N1C && N1C->isNullValue())
2055     return N0;
2056   // reassociate xor
2057   SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2058   if (RXOR.Val != 0)
2059     return RXOR;
2060   // fold !(x cc y) -> (x !cc y)
2061   if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2062     bool isInt = MVT::isInteger(LHS.getValueType());
2063     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2064                                                isInt);
2065     if (N0.getOpcode() == ISD::SETCC)
2066       return DAG.getSetCC(VT, LHS, RHS, NotCC);
2067     if (N0.getOpcode() == ISD::SELECT_CC)
2068       return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2069     assert(0 && "Unhandled SetCC Equivalent!");
2070     abort();
2071   }
2072   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2073   if (N1C && N1C->getValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2074       N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2075     SDOperand V = N0.getOperand(0);
2076     V = DAG.getNode(ISD::XOR, V.getValueType(), V, 
2077                     DAG.getConstant(1, V.getValueType()));
2078     AddToWorkList(V.Val);
2079     return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2080   }
2081   
2082   // fold !(x or y) -> (!x and !y) iff x or y are setcc
2083   if (N1C && N1C->getValue() == 1 && VT == MVT::i1 &&
2084       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2085     SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2086     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2087       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2088       LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
2089       RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
2090       AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2091       return DAG.getNode(NewOpcode, VT, LHS, RHS);
2092     }
2093   }
2094   // fold !(x or y) -> (!x and !y) iff x or y are constants
2095   if (N1C && N1C->isAllOnesValue() && 
2096       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2097     SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2098     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2099       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2100       LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
2101       RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
2102       AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2103       return DAG.getNode(NewOpcode, VT, LHS, RHS);
2104     }
2105   }
2106   // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2107   if (N1C && N0.getOpcode() == ISD::XOR) {
2108     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2109     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2110     if (N00C)
2111       return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2112                          DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
2113     if (N01C)
2114       return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2115                          DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
2116   }
2117   // fold (xor x, x) -> 0
2118   if (N0 == N1) {
2119     if (!MVT::isVector(VT)) {
2120       return DAG.getConstant(0, VT);
2121     } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2122       // Produce a vector of zeros.
2123       SDOperand El = DAG.getConstant(0, MVT::getVectorElementType(VT));
2124       std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
2125       return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2126     }
2127   }
2128   
2129   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
2130   if (N0.getOpcode() == N1.getOpcode()) {
2131     SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2132     if (Tmp.Val) return Tmp;
2133   }
2134   
2135   // Simplify the expression using non-local knowledge.
2136   if (!MVT::isVector(VT) &&
2137       SimplifyDemandedBits(SDOperand(N, 0)))
2138     return SDOperand(N, 0);
2139   
2140   return SDOperand();
2141 }
2142
2143 SDOperand DAGCombiner::visitSHL(SDNode *N) {
2144   SDOperand N0 = N->getOperand(0);
2145   SDOperand N1 = N->getOperand(1);
2146   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2147   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2148   MVT::ValueType VT = N0.getValueType();
2149   unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2150   
2151   // fold (shl c1, c2) -> c1<<c2
2152   if (N0C && N1C)
2153     return DAG.getNode(ISD::SHL, VT, N0, N1);
2154   // fold (shl 0, x) -> 0
2155   if (N0C && N0C->isNullValue())
2156     return N0;
2157   // fold (shl x, c >= size(x)) -> undef
2158   if (N1C && N1C->getValue() >= OpSizeInBits)
2159     return DAG.getNode(ISD::UNDEF, VT);
2160   // fold (shl x, 0) -> x
2161   if (N1C && N1C->isNullValue())
2162     return N0;
2163   // if (shl x, c) is known to be zero, return 0
2164   if (DAG.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
2165     return DAG.getConstant(0, VT);
2166   if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2167     return SDOperand(N, 0);
2168   // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2169   if (N1C && N0.getOpcode() == ISD::SHL && 
2170       N0.getOperand(1).getOpcode() == ISD::Constant) {
2171     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2172     uint64_t c2 = N1C->getValue();
2173     if (c1 + c2 > OpSizeInBits)
2174       return DAG.getConstant(0, VT);
2175     return DAG.getNode(ISD::SHL, VT, N0.getOperand(0), 
2176                        DAG.getConstant(c1 + c2, N1.getValueType()));
2177   }
2178   // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2179   //                               (srl (and x, -1 << c1), c1-c2)
2180   if (N1C && N0.getOpcode() == ISD::SRL && 
2181       N0.getOperand(1).getOpcode() == ISD::Constant) {
2182     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2183     uint64_t c2 = N1C->getValue();
2184     SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2185                                  DAG.getConstant(~0ULL << c1, VT));
2186     if (c2 > c1)
2187       return DAG.getNode(ISD::SHL, VT, Mask, 
2188                          DAG.getConstant(c2-c1, N1.getValueType()));
2189     else
2190       return DAG.getNode(ISD::SRL, VT, Mask, 
2191                          DAG.getConstant(c1-c2, N1.getValueType()));
2192   }
2193   // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2194   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2195     return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2196                        DAG.getConstant(~0ULL << N1C->getValue(), VT));
2197   return SDOperand();
2198 }
2199
2200 SDOperand DAGCombiner::visitSRA(SDNode *N) {
2201   SDOperand N0 = N->getOperand(0);
2202   SDOperand N1 = N->getOperand(1);
2203   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2204   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2205   MVT::ValueType VT = N0.getValueType();
2206   
2207   // fold (sra c1, c2) -> c1>>c2
2208   if (N0C && N1C)
2209     return DAG.getNode(ISD::SRA, VT, N0, N1);
2210   // fold (sra 0, x) -> 0
2211   if (N0C && N0C->isNullValue())
2212     return N0;
2213   // fold (sra -1, x) -> -1
2214   if (N0C && N0C->isAllOnesValue())
2215     return N0;
2216   // fold (sra x, c >= size(x)) -> undef
2217   if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
2218     return DAG.getNode(ISD::UNDEF, VT);
2219   // fold (sra x, 0) -> x
2220   if (N1C && N1C->isNullValue())
2221     return N0;
2222   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2223   // sext_inreg.
2224   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2225     unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
2226     MVT::ValueType EVT;
2227     switch (LowBits) {
2228     default: EVT = MVT::Other; break;
2229     case  1: EVT = MVT::i1;    break;
2230     case  8: EVT = MVT::i8;    break;
2231     case 16: EVT = MVT::i16;   break;
2232     case 32: EVT = MVT::i32;   break;
2233     }
2234     if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
2235       return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2236                          DAG.getValueType(EVT));
2237   }
2238   
2239   // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2240   if (N1C && N0.getOpcode() == ISD::SRA) {
2241     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2242       unsigned Sum = N1C->getValue() + C1->getValue();
2243       if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
2244       return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2245                          DAG.getConstant(Sum, N1C->getValueType(0)));
2246     }
2247   }
2248   
2249   // Simplify, based on bits shifted out of the LHS. 
2250   if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2251     return SDOperand(N, 0);
2252   
2253   
2254   // If the sign bit is known to be zero, switch this to a SRL.
2255   if (DAG.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
2256     return DAG.getNode(ISD::SRL, VT, N0, N1);
2257   return SDOperand();
2258 }
2259
2260 SDOperand DAGCombiner::visitSRL(SDNode *N) {
2261   SDOperand N0 = N->getOperand(0);
2262   SDOperand N1 = N->getOperand(1);
2263   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2264   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2265   MVT::ValueType VT = N0.getValueType();
2266   unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2267   
2268   // fold (srl c1, c2) -> c1 >>u c2
2269   if (N0C && N1C)
2270     return DAG.getNode(ISD::SRL, VT, N0, N1);
2271   // fold (srl 0, x) -> 0
2272   if (N0C && N0C->isNullValue())
2273     return N0;
2274   // fold (srl x, c >= size(x)) -> undef
2275   if (N1C && N1C->getValue() >= OpSizeInBits)
2276     return DAG.getNode(ISD::UNDEF, VT);
2277   // fold (srl x, 0) -> x
2278   if (N1C && N1C->isNullValue())
2279     return N0;
2280   // if (srl x, c) is known to be zero, return 0
2281   if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
2282     return DAG.getConstant(0, VT);
2283   
2284   // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2285   if (N1C && N0.getOpcode() == ISD::SRL && 
2286       N0.getOperand(1).getOpcode() == ISD::Constant) {
2287     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2288     uint64_t c2 = N1C->getValue();
2289     if (c1 + c2 > OpSizeInBits)
2290       return DAG.getConstant(0, VT);
2291     return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), 
2292                        DAG.getConstant(c1 + c2, N1.getValueType()));
2293   }
2294   
2295   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2296   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2297     // Shifting in all undef bits?
2298     MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
2299     if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
2300       return DAG.getNode(ISD::UNDEF, VT);
2301
2302     SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2303     AddToWorkList(SmallShift.Val);
2304     return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2305   }
2306   
2307   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
2308   // bit, which is unmodified by sra.
2309   if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
2310     if (N0.getOpcode() == ISD::SRA)
2311       return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2312   }
2313   
2314   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
2315   if (N1C && N0.getOpcode() == ISD::CTLZ && 
2316       N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
2317     uint64_t KnownZero, KnownOne, Mask = MVT::getIntVTBitMask(VT);
2318     DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2319     
2320     // If any of the input bits are KnownOne, then the input couldn't be all
2321     // zeros, thus the result of the srl will always be zero.
2322     if (KnownOne) return DAG.getConstant(0, VT);
2323     
2324     // If all of the bits input the to ctlz node are known to be zero, then
2325     // the result of the ctlz is "32" and the result of the shift is one.
2326     uint64_t UnknownBits = ~KnownZero & Mask;
2327     if (UnknownBits == 0) return DAG.getConstant(1, VT);
2328     
2329     // Otherwise, check to see if there is exactly one bit input to the ctlz.
2330     if ((UnknownBits & (UnknownBits-1)) == 0) {
2331       // Okay, we know that only that the single bit specified by UnknownBits
2332       // could be set on input to the CTLZ node.  If this bit is set, the SRL
2333       // will return 0, if it is clear, it returns 1.  Change the CTLZ/SRL pair
2334       // to an SRL,XOR pair, which is likely to simplify more.
2335       unsigned ShAmt = CountTrailingZeros_64(UnknownBits);
2336       SDOperand Op = N0.getOperand(0);
2337       if (ShAmt) {
2338         Op = DAG.getNode(ISD::SRL, VT, Op,
2339                          DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2340         AddToWorkList(Op.Val);
2341       }
2342       return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2343     }
2344   }
2345   
2346   // fold operands of srl based on knowledge that the low bits are not
2347   // demanded.
2348   if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2349     return SDOperand(N, 0);
2350   
2351   return SDOperand();
2352 }
2353
2354 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2355   SDOperand N0 = N->getOperand(0);
2356   MVT::ValueType VT = N->getValueType(0);
2357
2358   // fold (ctlz c1) -> c2
2359   if (isa<ConstantSDNode>(N0))
2360     return DAG.getNode(ISD::CTLZ, VT, N0);
2361   return SDOperand();
2362 }
2363
2364 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2365   SDOperand N0 = N->getOperand(0);
2366   MVT::ValueType VT = N->getValueType(0);
2367   
2368   // fold (cttz c1) -> c2
2369   if (isa<ConstantSDNode>(N0))
2370     return DAG.getNode(ISD::CTTZ, VT, N0);
2371   return SDOperand();
2372 }
2373
2374 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2375   SDOperand N0 = N->getOperand(0);
2376   MVT::ValueType VT = N->getValueType(0);
2377   
2378   // fold (ctpop c1) -> c2
2379   if (isa<ConstantSDNode>(N0))
2380     return DAG.getNode(ISD::CTPOP, VT, N0);
2381   return SDOperand();
2382 }
2383
2384 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2385   SDOperand N0 = N->getOperand(0);
2386   SDOperand N1 = N->getOperand(1);
2387   SDOperand N2 = N->getOperand(2);
2388   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2389   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2390   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2391   MVT::ValueType VT = N->getValueType(0);
2392   MVT::ValueType VT0 = N0.getValueType();
2393
2394   // fold select C, X, X -> X
2395   if (N1 == N2)
2396     return N1;
2397   // fold select true, X, Y -> X
2398   if (N0C && !N0C->isNullValue())
2399     return N1;
2400   // fold select false, X, Y -> Y
2401   if (N0C && N0C->isNullValue())
2402     return N2;
2403   // fold select C, 1, X -> C | X
2404   if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
2405     return DAG.getNode(ISD::OR, VT, N0, N2);
2406   // fold select C, 0, 1 -> ~C
2407   if (MVT::isInteger(VT) && MVT::isInteger(VT0) &&
2408       N1C && N2C && N1C->isNullValue() && N2C->getValue() == 1) {
2409     SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2410     if (VT == VT0)
2411       return XORNode;
2412     AddToWorkList(XORNode.Val);
2413     if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(VT0))
2414       return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2415     return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2416   }
2417   // fold select C, 0, X -> ~C & X
2418   if (VT == VT0 && N1C && N1C->isNullValue()) {
2419     SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2420     AddToWorkList(XORNode.Val);
2421     return DAG.getNode(ISD::AND, VT, XORNode, N2);
2422   }
2423   // fold select C, X, 1 -> ~C | X
2424   if (VT == VT0 && N2C && N2C->getValue() == 1) {
2425     SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2426     AddToWorkList(XORNode.Val);
2427     return DAG.getNode(ISD::OR, VT, XORNode, N1);
2428   }
2429   // fold select C, X, 0 -> C & X
2430   // FIXME: this should check for C type == X type, not i1?
2431   if (MVT::i1 == VT && N2C && N2C->isNullValue())
2432     return DAG.getNode(ISD::AND, VT, N0, N1);
2433   // fold  X ? X : Y --> X ? 1 : Y --> X | Y
2434   if (MVT::i1 == VT && N0 == N1)
2435     return DAG.getNode(ISD::OR, VT, N0, N2);
2436   // fold X ? Y : X --> X ? Y : 0 --> X & Y
2437   if (MVT::i1 == VT && N0 == N2)
2438     return DAG.getNode(ISD::AND, VT, N0, N1);
2439   
2440   // If we can fold this based on the true/false value, do so.
2441   if (SimplifySelectOps(N, N1, N2))
2442     return SDOperand(N, 0);  // Don't revisit N.
2443   
2444   // fold selects based on a setcc into other things, such as min/max/abs
2445   if (N0.getOpcode() == ISD::SETCC)
2446     // FIXME:
2447     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2448     // having to say they don't support SELECT_CC on every type the DAG knows
2449     // about, since there is no way to mark an opcode illegal at all value types
2450     if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2451       return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2452                          N1, N2, N0.getOperand(2));
2453     else
2454       return SimplifySelect(N0, N1, N2);
2455   return SDOperand();
2456 }
2457
2458 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2459   SDOperand N0 = N->getOperand(0);
2460   SDOperand N1 = N->getOperand(1);
2461   SDOperand N2 = N->getOperand(2);
2462   SDOperand N3 = N->getOperand(3);
2463   SDOperand N4 = N->getOperand(4);
2464   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2465   
2466   // fold select_cc lhs, rhs, x, x, cc -> x
2467   if (N2 == N3)
2468     return N2;
2469   
2470   // Determine if the condition we're dealing with is constant
2471   SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
2472   if (SCC.Val) AddToWorkList(SCC.Val);
2473
2474   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2475     if (SCCC->getValue())
2476       return N2;    // cond always true -> true val
2477     else
2478       return N3;    // cond always false -> false val
2479   }
2480   
2481   // Fold to a simpler select_cc
2482   if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2483     return DAG.getNode(ISD::SELECT_CC, N2.getValueType(), 
2484                        SCC.getOperand(0), SCC.getOperand(1), N2, N3, 
2485                        SCC.getOperand(2));
2486   
2487   // If we can fold this based on the true/false value, do so.
2488   if (SimplifySelectOps(N, N2, N3))
2489     return SDOperand(N, 0);  // Don't revisit N.
2490   
2491   // fold select_cc into other things, such as min/max/abs
2492   return SimplifySelectCC(N0, N1, N2, N3, CC);
2493 }
2494
2495 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2496   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2497                        cast<CondCodeSDNode>(N->getOperand(2))->get());
2498 }
2499
2500 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2501   SDOperand N0 = N->getOperand(0);
2502   MVT::ValueType VT = N->getValueType(0);
2503
2504   // fold (sext c1) -> c1
2505   if (isa<ConstantSDNode>(N0))
2506     return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2507   
2508   // fold (sext (sext x)) -> (sext x)
2509   // fold (sext (aext x)) -> (sext x)
2510   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2511     return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2512   
2513   // fold (sext (truncate (load x))) -> (sext (smaller load x))
2514   // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2515   if (N0.getOpcode() == ISD::TRUNCATE) {
2516     SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2517     if (NarrowLoad.Val) {
2518       if (NarrowLoad.Val != N0.Val)
2519         CombineTo(N0.Val, NarrowLoad);
2520       return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2521     }
2522   }
2523
2524   // See if the value being truncated is already sign extended.  If so, just
2525   // eliminate the trunc/sext pair.
2526   if (N0.getOpcode() == ISD::TRUNCATE) {
2527     SDOperand Op = N0.getOperand(0);
2528     unsigned OpBits   = MVT::getSizeInBits(Op.getValueType());
2529     unsigned MidBits  = MVT::getSizeInBits(N0.getValueType());
2530     unsigned DestBits = MVT::getSizeInBits(VT);
2531     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2532     
2533     if (OpBits == DestBits) {
2534       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
2535       // bits, it is already ready.
2536       if (NumSignBits > DestBits-MidBits)
2537         return Op;
2538     } else if (OpBits < DestBits) {
2539       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
2540       // bits, just sext from i32.
2541       if (NumSignBits > OpBits-MidBits)
2542         return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2543     } else {
2544       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
2545       // bits, just truncate to i32.
2546       if (NumSignBits > OpBits-MidBits)
2547         return DAG.getNode(ISD::TRUNCATE, VT, Op);
2548     }
2549     
2550     // fold (sext (truncate x)) -> (sextinreg x).
2551     if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2552                                                N0.getValueType())) {
2553       if (Op.getValueType() < VT)
2554         Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2555       else if (Op.getValueType() > VT)
2556         Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2557       return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2558                          DAG.getValueType(N0.getValueType()));
2559     }
2560   }
2561   
2562   // fold (sext (load x)) -> (sext (truncate (sextload x)))
2563   if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2564       (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
2565     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2566     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2567                                        LN0->getBasePtr(), LN0->getSrcValue(),
2568                                        LN0->getSrcValueOffset(),
2569                                        N0.getValueType(), 
2570                                        LN0->isVolatile(),
2571                                        LN0->getAlignment());
2572     CombineTo(N, ExtLoad);
2573     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2574               ExtLoad.getValue(1));
2575     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2576   }
2577
2578   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2579   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2580   if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2581       ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2582     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2583     MVT::ValueType EVT = LN0->getLoadedVT();
2584     if (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2585       SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2586                                          LN0->getBasePtr(), LN0->getSrcValue(),
2587                                          LN0->getSrcValueOffset(), EVT,
2588                                          LN0->isVolatile(), 
2589                                          LN0->getAlignment());
2590       CombineTo(N, ExtLoad);
2591       CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2592                 ExtLoad.getValue(1));
2593       return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2594     }
2595   }
2596   
2597   // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2598   if (N0.getOpcode() == ISD::SETCC) {
2599     SDOperand SCC = 
2600       SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2601                        DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2602                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2603     if (SCC.Val) return SCC;
2604   }
2605   
2606   return SDOperand();
2607 }
2608
2609 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2610   SDOperand N0 = N->getOperand(0);
2611   MVT::ValueType VT = N->getValueType(0);
2612
2613   // fold (zext c1) -> c1
2614   if (isa<ConstantSDNode>(N0))
2615     return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2616   // fold (zext (zext x)) -> (zext x)
2617   // fold (zext (aext x)) -> (zext x)
2618   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2619     return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2620
2621   // fold (zext (truncate (load x))) -> (zext (smaller load x))
2622   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2623   if (N0.getOpcode() == ISD::TRUNCATE) {
2624     SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2625     if (NarrowLoad.Val) {
2626       if (NarrowLoad.Val != N0.Val)
2627         CombineTo(N0.Val, NarrowLoad);
2628       return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2629     }
2630   }
2631
2632   // fold (zext (truncate x)) -> (and x, mask)
2633   if (N0.getOpcode() == ISD::TRUNCATE &&
2634       (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2635     SDOperand Op = N0.getOperand(0);
2636     if (Op.getValueType() < VT) {
2637       Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2638     } else if (Op.getValueType() > VT) {
2639       Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2640     }
2641     return DAG.getZeroExtendInReg(Op, N0.getValueType());
2642   }
2643   
2644   // fold (zext (and (trunc x), cst)) -> (and x, cst).
2645   if (N0.getOpcode() == ISD::AND &&
2646       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2647       N0.getOperand(1).getOpcode() == ISD::Constant) {
2648     SDOperand X = N0.getOperand(0).getOperand(0);
2649     if (X.getValueType() < VT) {
2650       X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2651     } else if (X.getValueType() > VT) {
2652       X = DAG.getNode(ISD::TRUNCATE, VT, X);
2653     }
2654     uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2655     return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2656   }
2657   
2658   // fold (zext (load x)) -> (zext (truncate (zextload x)))
2659   if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2660       (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2661     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2662     SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2663                                        LN0->getBasePtr(), LN0->getSrcValue(),
2664                                        LN0->getSrcValueOffset(),
2665                                        N0.getValueType(),
2666                                        LN0->isVolatile(), 
2667                                        LN0->getAlignment());
2668     CombineTo(N, ExtLoad);
2669     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2670               ExtLoad.getValue(1));
2671     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2672   }
2673
2674   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2675   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2676   if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2677       ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2678     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2679     MVT::ValueType EVT = LN0->getLoadedVT();
2680     SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2681                                        LN0->getBasePtr(), LN0->getSrcValue(),
2682                                        LN0->getSrcValueOffset(), EVT,
2683                                        LN0->isVolatile(), 
2684                                        LN0->getAlignment());
2685     CombineTo(N, ExtLoad);
2686     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2687               ExtLoad.getValue(1));
2688     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2689   }
2690   
2691   // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2692   if (N0.getOpcode() == ISD::SETCC) {
2693     SDOperand SCC = 
2694       SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2695                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2696                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2697     if (SCC.Val) return SCC;
2698   }
2699   
2700   return SDOperand();
2701 }
2702
2703 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
2704   SDOperand N0 = N->getOperand(0);
2705   MVT::ValueType VT = N->getValueType(0);
2706   
2707   // fold (aext c1) -> c1
2708   if (isa<ConstantSDNode>(N0))
2709     return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
2710   // fold (aext (aext x)) -> (aext x)
2711   // fold (aext (zext x)) -> (zext x)
2712   // fold (aext (sext x)) -> (sext x)
2713   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
2714       N0.getOpcode() == ISD::ZERO_EXTEND ||
2715       N0.getOpcode() == ISD::SIGN_EXTEND)
2716     return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2717   
2718   // fold (aext (truncate (load x))) -> (aext (smaller load x))
2719   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
2720   if (N0.getOpcode() == ISD::TRUNCATE) {
2721     SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2722     if (NarrowLoad.Val) {
2723       if (NarrowLoad.Val != N0.Val)
2724         CombineTo(N0.Val, NarrowLoad);
2725       return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
2726     }
2727   }
2728
2729   // fold (aext (truncate x))
2730   if (N0.getOpcode() == ISD::TRUNCATE) {
2731     SDOperand TruncOp = N0.getOperand(0);
2732     if (TruncOp.getValueType() == VT)
2733       return TruncOp; // x iff x size == zext size.
2734     if (TruncOp.getValueType() > VT)
2735       return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
2736     return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
2737   }
2738   
2739   // fold (aext (and (trunc x), cst)) -> (and x, cst).
2740   if (N0.getOpcode() == ISD::AND &&
2741       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2742       N0.getOperand(1).getOpcode() == ISD::Constant) {
2743     SDOperand X = N0.getOperand(0).getOperand(0);
2744     if (X.getValueType() < VT) {
2745       X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2746     } else if (X.getValueType() > VT) {
2747       X = DAG.getNode(ISD::TRUNCATE, VT, X);
2748     }
2749     uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2750     return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2751   }
2752   
2753   // fold (aext (load x)) -> (aext (truncate (extload x)))
2754   if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2755       (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2756     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2757     SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2758                                        LN0->getBasePtr(), LN0->getSrcValue(),
2759                                        LN0->getSrcValueOffset(),
2760                                        N0.getValueType(),
2761                                        LN0->isVolatile(), 
2762                                        LN0->getAlignment());
2763     CombineTo(N, ExtLoad);
2764     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2765               ExtLoad.getValue(1));
2766     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2767   }
2768   
2769   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
2770   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
2771   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
2772   if (N0.getOpcode() == ISD::LOAD &&
2773       !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
2774       N0.hasOneUse()) {
2775     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2776     MVT::ValueType EVT = LN0->getLoadedVT();
2777     SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
2778                                        LN0->getChain(), LN0->getBasePtr(),
2779                                        LN0->getSrcValue(),
2780                                        LN0->getSrcValueOffset(), EVT,
2781                                        LN0->isVolatile(), 
2782                                        LN0->getAlignment());
2783     CombineTo(N, ExtLoad);
2784     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2785               ExtLoad.getValue(1));
2786     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2787   }
2788   
2789   // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2790   if (N0.getOpcode() == ISD::SETCC) {
2791     SDOperand SCC = 
2792       SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2793                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2794                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2795     if (SCC.Val)
2796       return SCC;
2797   }
2798   
2799   return SDOperand();
2800 }
2801
2802 /// GetDemandedBits - See if the specified operand can be simplified with the
2803 /// knowledge that only the bits specified by Mask are used.  If so, return the
2804 /// simpler operand, otherwise return a null SDOperand.
2805 SDOperand DAGCombiner::GetDemandedBits(SDOperand V, uint64_t Mask) {
2806   switch (V.getOpcode()) {
2807   default: break;
2808   case ISD::OR:
2809   case ISD::XOR:
2810     // If the LHS or RHS don't contribute bits to the or, drop them.
2811     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
2812       return V.getOperand(1);
2813     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
2814       return V.getOperand(0);
2815     break;
2816   case ISD::SRL:
2817     // Only look at single-use SRLs.
2818     if (!V.Val->hasOneUse())
2819       break;
2820     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2821       // See if we can recursively simplify the LHS.
2822       unsigned Amt = RHSC->getValue();
2823       Mask = (Mask << Amt) & MVT::getIntVTBitMask(V.getValueType());
2824       SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), Mask);
2825       if (SimplifyLHS.Val) {
2826         return DAG.getNode(ISD::SRL, V.getValueType(), 
2827                            SimplifyLHS, V.getOperand(1));
2828       }
2829     }
2830   }
2831   return SDOperand();
2832 }
2833
2834 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
2835 /// bits and then truncated to a narrower type and where N is a multiple
2836 /// of number of bits of the narrower type, transform it to a narrower load
2837 /// from address + N / num of bits of new type. If the result is to be
2838 /// extended, also fold the extension to form a extending load.
2839 SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
2840   unsigned Opc = N->getOpcode();
2841   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2842   SDOperand N0 = N->getOperand(0);
2843   MVT::ValueType VT = N->getValueType(0);
2844   MVT::ValueType EVT = N->getValueType(0);
2845
2846   // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
2847   // extended to VT.
2848   if (Opc == ISD::SIGN_EXTEND_INREG) {
2849     ExtType = ISD::SEXTLOAD;
2850     EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2851     if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
2852       return SDOperand();
2853   }
2854
2855   unsigned EVTBits = MVT::getSizeInBits(EVT);
2856   unsigned ShAmt = 0;
2857   bool CombineSRL =  false;
2858   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
2859     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2860       ShAmt = N01->getValue();
2861       // Is the shift amount a multiple of size of VT?
2862       if ((ShAmt & (EVTBits-1)) == 0) {
2863         N0 = N0.getOperand(0);
2864         if (MVT::getSizeInBits(N0.getValueType()) <= EVTBits)
2865           return SDOperand();
2866         CombineSRL = true;
2867       }
2868     }
2869   }
2870
2871   if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2872       // Do not allow folding to i1 here.  i1 is implicitly stored in memory in
2873       // zero extended form: by shrinking the load, we lose track of the fact
2874       // that it is already zero extended.
2875       // FIXME: This should be reevaluated.
2876       VT != MVT::i1) {
2877     assert(MVT::getSizeInBits(N0.getValueType()) > EVTBits &&
2878            "Cannot truncate to larger type!");
2879     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2880     MVT::ValueType PtrType = N0.getOperand(1).getValueType();
2881     // For big endian targets, we need to adjust the offset to the pointer to
2882     // load the correct bytes.
2883     if (!TLI.isLittleEndian())
2884       ShAmt = MVT::getSizeInBits(N0.getValueType()) - ShAmt - EVTBits;
2885     uint64_t PtrOff =  ShAmt / 8;
2886     unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
2887     SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
2888                                    DAG.getConstant(PtrOff, PtrType));
2889     AddToWorkList(NewPtr.Val);
2890     SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
2891       ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
2892                     LN0->getSrcValue(), LN0->getSrcValueOffset(),
2893                     LN0->isVolatile(), NewAlign)
2894       : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
2895                        LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
2896                        LN0->isVolatile(), NewAlign);
2897     AddToWorkList(N);
2898     if (CombineSRL) {
2899       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
2900       CombineTo(N->getOperand(0).Val, Load);
2901     } else
2902       CombineTo(N0.Val, Load, Load.getValue(1));
2903     if (ShAmt) {
2904       if (Opc == ISD::SIGN_EXTEND_INREG)
2905         return DAG.getNode(Opc, VT, Load, N->getOperand(1));
2906       else
2907         return DAG.getNode(Opc, VT, Load);
2908     }
2909     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2910   }
2911
2912   return SDOperand();
2913 }
2914
2915
2916 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
2917   SDOperand N0 = N->getOperand(0);
2918   SDOperand N1 = N->getOperand(1);
2919   MVT::ValueType VT = N->getValueType(0);
2920   MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
2921   unsigned EVTBits = MVT::getSizeInBits(EVT);
2922   
2923   // fold (sext_in_reg c1) -> c1
2924   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
2925     return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
2926   
2927   // If the input is already sign extended, just drop the extension.
2928   if (DAG.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
2929     return N0;
2930   
2931   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
2932   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2933       EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
2934     return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
2935   }
2936
2937   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
2938   if (DAG.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
2939     return DAG.getZeroExtendInReg(N0, EVT);
2940   
2941   // fold operands of sext_in_reg based on knowledge that the top bits are not
2942   // demanded.
2943   if (SimplifyDemandedBits(SDOperand(N, 0)))
2944     return SDOperand(N, 0);
2945   
2946   // fold (sext_in_reg (load x)) -> (smaller sextload x)
2947   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
2948   SDOperand NarrowLoad = ReduceLoadWidth(N);
2949   if (NarrowLoad.Val)
2950     return NarrowLoad;
2951
2952   // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
2953   // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
2954   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
2955   if (N0.getOpcode() == ISD::SRL) {
2956     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2957       if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
2958         // We can turn this into an SRA iff the input to the SRL is already sign
2959         // extended enough.
2960         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
2961         if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
2962           return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
2963       }
2964   }
2965
2966   // fold (sext_inreg (extload x)) -> (sextload x)
2967   if (ISD::isEXTLoad(N0.Val) && 
2968       ISD::isUNINDEXEDLoad(N0.Val) &&
2969       EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2970       (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2971     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2972     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2973                                        LN0->getBasePtr(), LN0->getSrcValue(),
2974                                        LN0->getSrcValueOffset(), EVT,
2975                                        LN0->isVolatile(), 
2976                                        LN0->getAlignment());
2977     CombineTo(N, ExtLoad);
2978     CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2979     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2980   }
2981   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
2982   if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
2983       N0.hasOneUse() &&
2984       EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2985       (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2986     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2987     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2988                                        LN0->getBasePtr(), LN0->getSrcValue(),
2989                                        LN0->getSrcValueOffset(), EVT,
2990                                        LN0->isVolatile(), 
2991                                        LN0->getAlignment());
2992     CombineTo(N, ExtLoad);
2993     CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2994     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2995   }
2996   return SDOperand();
2997 }
2998
2999 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3000   SDOperand N0 = N->getOperand(0);
3001   MVT::ValueType VT = N->getValueType(0);
3002
3003   // noop truncate
3004   if (N0.getValueType() == N->getValueType(0))
3005     return N0;
3006   // fold (truncate c1) -> c1
3007   if (isa<ConstantSDNode>(N0))
3008     return DAG.getNode(ISD::TRUNCATE, VT, N0);
3009   // fold (truncate (truncate x)) -> (truncate x)
3010   if (N0.getOpcode() == ISD::TRUNCATE)
3011     return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3012   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3013   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3014       N0.getOpcode() == ISD::ANY_EXTEND) {
3015     if (N0.getOperand(0).getValueType() < VT)
3016       // if the source is smaller than the dest, we still need an extend
3017       return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3018     else if (N0.getOperand(0).getValueType() > VT)
3019       // if the source is larger than the dest, than we just need the truncate
3020       return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3021     else
3022       // if the source and dest are the same type, we can drop both the extend
3023       // and the truncate
3024       return N0.getOperand(0);
3025   }
3026
3027   // See if we can simplify the input to this truncate through knowledge that
3028   // only the low bits are being used.  For example "trunc (or (shl x, 8), y)"
3029   // -> trunc y
3030   SDOperand Shorter = GetDemandedBits(N0, MVT::getIntVTBitMask(VT));
3031   if (Shorter.Val)
3032     return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3033
3034   // fold (truncate (load x)) -> (smaller load x)
3035   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3036   return ReduceLoadWidth(N);
3037 }
3038
3039 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3040   SDOperand N0 = N->getOperand(0);
3041   MVT::ValueType VT = N->getValueType(0);
3042
3043   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3044   // Only do this before legalize, since afterward the target may be depending
3045   // on the bitconvert.
3046   // First check to see if this is all constant.
3047   if (!AfterLegalize &&
3048       N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3049       MVT::isVector(VT)) {
3050     bool isSimple = true;
3051     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3052       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3053           N0.getOperand(i).getOpcode() != ISD::Constant &&
3054           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3055         isSimple = false; 
3056         break;
3057       }
3058         
3059     MVT::ValueType DestEltVT = MVT::getVectorElementType(N->getValueType(0));
3060     assert(!MVT::isVector(DestEltVT) &&
3061            "Element type of vector ValueType must not be vector!");
3062     if (isSimple) {
3063       return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3064     }
3065   }
3066   
3067   // If the input is a constant, let getNode() fold it.
3068   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3069     SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3070     if (Res.Val != N) return Res;
3071   }
3072   
3073   if (N0.getOpcode() == ISD::BIT_CONVERT)  // conv(conv(x,t1),t2) -> conv(x,t2)
3074     return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3075
3076   // fold (conv (load x)) -> (load (conv*)x)
3077   // If the resultant load doesn't need a higher alignment than the original!
3078   if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
3079       TLI.isOperationLegal(ISD::LOAD, VT)) {
3080     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3081     unsigned Align = TLI.getTargetMachine().getTargetData()->
3082       getABITypeAlignment(MVT::getTypeForValueType(VT));
3083     unsigned OrigAlign = LN0->getAlignment();
3084     if (Align <= OrigAlign) {
3085       SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3086                                    LN0->getSrcValue(), LN0->getSrcValueOffset(),
3087                                    LN0->isVolatile(), Align);
3088       AddToWorkList(N);
3089       CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3090                 Load.getValue(1));
3091       return Load;
3092     }
3093   }
3094   
3095   return SDOperand();
3096 }
3097
3098 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3099 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the 
3100 /// destination element value type.
3101 SDOperand DAGCombiner::
3102 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
3103   MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
3104   
3105   // If this is already the right type, we're done.
3106   if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3107   
3108   unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
3109   unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
3110   
3111   // If this is a conversion of N elements of one type to N elements of another
3112   // type, convert each element.  This handles FP<->INT cases.
3113   if (SrcBitSize == DstBitSize) {
3114     SmallVector<SDOperand, 8> Ops;
3115     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3116       Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3117       AddToWorkList(Ops.back().Val);
3118     }
3119     MVT::ValueType VT =
3120       MVT::getVectorType(DstEltVT,
3121                          MVT::getVectorNumElements(BV->getValueType(0)));
3122     return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3123   }
3124   
3125   // Otherwise, we're growing or shrinking the elements.  To avoid having to
3126   // handle annoying details of growing/shrinking FP values, we convert them to
3127   // int first.
3128   if (MVT::isFloatingPoint(SrcEltVT)) {
3129     // Convert the input float vector to a int vector where the elements are the
3130     // same sizes.
3131     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3132     MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3133     BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3134     SrcEltVT = IntVT;
3135   }
3136   
3137   // Now we know the input is an integer vector.  If the output is a FP type,
3138   // convert to integer first, then to FP of the right size.
3139   if (MVT::isFloatingPoint(DstEltVT)) {
3140     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3141     MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3142     SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3143     
3144     // Next, convert to FP elements of the same size.
3145     return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3146   }
3147   
3148   // Okay, we know the src/dst types are both integers of differing types.
3149   // Handling growing first.
3150   assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
3151   if (SrcBitSize < DstBitSize) {
3152     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3153     
3154     SmallVector<SDOperand, 8> Ops;
3155     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3156          i += NumInputsPerOutput) {
3157       bool isLE = TLI.isLittleEndian();
3158       uint64_t NewBits = 0;
3159       bool EltIsUndef = true;
3160       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3161         // Shift the previously computed bits over.
3162         NewBits <<= SrcBitSize;
3163         SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3164         if (Op.getOpcode() == ISD::UNDEF) continue;
3165         EltIsUndef = false;
3166         
3167         NewBits |= cast<ConstantSDNode>(Op)->getValue();
3168       }
3169       
3170       if (EltIsUndef)
3171         Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3172       else
3173         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3174     }
3175
3176     MVT::ValueType VT = MVT::getVectorType(DstEltVT,
3177                                            Ops.size());
3178     return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3179   }
3180   
3181   // Finally, this must be the case where we are shrinking elements: each input
3182   // turns into multiple outputs.
3183   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3184   SmallVector<SDOperand, 8> Ops;
3185   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3186     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3187       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3188         Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3189       continue;
3190     }
3191     uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
3192
3193     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3194       unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
3195       OpVal >>= DstBitSize;
3196       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3197     }
3198
3199     // For big endian targets, swap the order of the pieces of each element.
3200     if (!TLI.isLittleEndian())
3201       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3202   }
3203   MVT::ValueType VT = MVT::getVectorType(DstEltVT, Ops.size());
3204   return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3205 }
3206
3207
3208
3209 SDOperand DAGCombiner::visitFADD(SDNode *N) {
3210   SDOperand N0 = N->getOperand(0);
3211   SDOperand N1 = N->getOperand(1);
3212   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3213   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3214   MVT::ValueType VT = N->getValueType(0);
3215   
3216   // fold vector ops
3217   if (MVT::isVector(VT)) {
3218     SDOperand FoldedVOp = SimplifyVBinOp(N);
3219     if (FoldedVOp.Val) return FoldedVOp;
3220   }
3221   
3222   // fold (fadd c1, c2) -> c1+c2
3223   if (N0CFP && N1CFP && VT != MVT::ppcf128)
3224     return DAG.getNode(ISD::FADD, VT, N0, N1);
3225   // canonicalize constant to RHS
3226   if (N0CFP && !N1CFP)
3227     return DAG.getNode(ISD::FADD, VT, N1, N0);
3228   // fold (A + (-B)) -> A-B
3229   if (isNegatibleForFree(N1) == 2)
3230     return DAG.getNode(ISD::FSUB, VT, N0, GetNegatedExpression(N1, DAG));
3231   // fold ((-A) + B) -> B-A
3232   if (isNegatibleForFree(N0) == 2)
3233     return DAG.getNode(ISD::FSUB, VT, N1, GetNegatedExpression(N0, DAG));
3234   
3235   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3236   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3237       N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3238     return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3239                        DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3240   
3241   return SDOperand();
3242 }
3243
3244 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3245   SDOperand N0 = N->getOperand(0);
3246   SDOperand N1 = N->getOperand(1);
3247   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3248   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3249   MVT::ValueType VT = N->getValueType(0);
3250   
3251   // fold vector ops
3252   if (MVT::isVector(VT)) {
3253     SDOperand FoldedVOp = SimplifyVBinOp(N);
3254     if (FoldedVOp.Val) return FoldedVOp;
3255   }
3256   
3257   // fold (fsub c1, c2) -> c1-c2
3258   if (N0CFP && N1CFP && VT != MVT::ppcf128)
3259     return DAG.getNode(ISD::FSUB, VT, N0, N1);
3260   // fold (0-B) -> -B
3261   if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3262     if (isNegatibleForFree(N1))
3263       return GetNegatedExpression(N1, DAG);
3264     return DAG.getNode(ISD::FNEG, VT, N1);
3265   }
3266   // fold (A-(-B)) -> A+B
3267   if (isNegatibleForFree(N1))
3268     return DAG.getNode(ISD::FADD, VT, N0, GetNegatedExpression(N1, DAG));
3269   
3270   return SDOperand();
3271 }
3272
3273 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3274   SDOperand N0 = N->getOperand(0);
3275   SDOperand N1 = N->getOperand(1);
3276   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3277   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3278   MVT::ValueType VT = N->getValueType(0);
3279
3280   // fold vector ops
3281   if (MVT::isVector(VT)) {
3282     SDOperand FoldedVOp = SimplifyVBinOp(N);
3283     if (FoldedVOp.Val) return FoldedVOp;
3284   }
3285   
3286   // fold (fmul c1, c2) -> c1*c2
3287   if (N0CFP && N1CFP && VT != MVT::ppcf128)
3288     return DAG.getNode(ISD::FMUL, VT, N0, N1);
3289   // canonicalize constant to RHS
3290   if (N0CFP && !N1CFP)
3291     return DAG.getNode(ISD::FMUL, VT, N1, N0);
3292   // fold (fmul X, 2.0) -> (fadd X, X)
3293   if (N1CFP && N1CFP->isExactlyValue(+2.0))
3294     return DAG.getNode(ISD::FADD, VT, N0, N0);
3295   // fold (fmul X, -1.0) -> (fneg X)
3296   if (N1CFP && N1CFP->isExactlyValue(-1.0))
3297     return DAG.getNode(ISD::FNEG, VT, N0);
3298   
3299   // -X * -Y -> X*Y
3300   if (char LHSNeg = isNegatibleForFree(N0)) {
3301     if (char RHSNeg = isNegatibleForFree(N1)) {
3302       // Both can be negated for free, check to see if at least one is cheaper
3303       // negated.
3304       if (LHSNeg == 2 || RHSNeg == 2)
3305         return DAG.getNode(ISD::FMUL, VT, GetNegatedExpression(N0, DAG),
3306                            GetNegatedExpression(N1, DAG));
3307     }
3308   }
3309   
3310   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3311   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3312       N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3313     return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3314                        DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3315   
3316   return SDOperand();
3317 }
3318
3319 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3320   SDOperand N0 = N->getOperand(0);
3321   SDOperand N1 = N->getOperand(1);
3322   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3323   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3324   MVT::ValueType VT = N->getValueType(0);
3325
3326   // fold vector ops
3327   if (MVT::isVector(VT)) {
3328     SDOperand FoldedVOp = SimplifyVBinOp(N);
3329     if (FoldedVOp.Val) return FoldedVOp;
3330   }
3331   
3332   // fold (fdiv c1, c2) -> c1/c2
3333   if (N0CFP && N1CFP && VT != MVT::ppcf128)
3334     return DAG.getNode(ISD::FDIV, VT, N0, N1);
3335   
3336   
3337   // -X / -Y -> X*Y
3338   if (char LHSNeg = isNegatibleForFree(N0)) {
3339     if (char RHSNeg = isNegatibleForFree(N1)) {
3340       // Both can be negated for free, check to see if at least one is cheaper
3341       // negated.
3342       if (LHSNeg == 2 || RHSNeg == 2)
3343         return DAG.getNode(ISD::FDIV, VT, GetNegatedExpression(N0, DAG),
3344                            GetNegatedExpression(N1, DAG));
3345     }
3346   }
3347   
3348   return SDOperand();
3349 }
3350
3351 SDOperand DAGCombiner::visitFREM(SDNode *N) {
3352   SDOperand N0 = N->getOperand(0);
3353   SDOperand N1 = N->getOperand(1);
3354   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3355   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3356   MVT::ValueType VT = N->getValueType(0);
3357
3358   // fold (frem c1, c2) -> fmod(c1,c2)
3359   if (N0CFP && N1CFP && VT != MVT::ppcf128)
3360     return DAG.getNode(ISD::FREM, VT, N0, N1);
3361
3362   return SDOperand();
3363 }
3364
3365 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3366   SDOperand N0 = N->getOperand(0);
3367   SDOperand N1 = N->getOperand(1);
3368   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3369   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3370   MVT::ValueType VT = N->getValueType(0);
3371
3372   if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
3373     return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3374   
3375   if (N1CFP) {
3376     const APFloat& V = N1CFP->getValueAPF();
3377     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
3378     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3379     if (!V.isNegative())
3380       return DAG.getNode(ISD::FABS, VT, N0);
3381     else
3382       return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3383   }
3384   
3385   // copysign(fabs(x), y) -> copysign(x, y)
3386   // copysign(fneg(x), y) -> copysign(x, y)
3387   // copysign(copysign(x,z), y) -> copysign(x, y)
3388   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3389       N0.getOpcode() == ISD::FCOPYSIGN)
3390     return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3391
3392   // copysign(x, abs(y)) -> abs(x)
3393   if (N1.getOpcode() == ISD::FABS)
3394     return DAG.getNode(ISD::FABS, VT, N0);
3395   
3396   // copysign(x, copysign(y,z)) -> copysign(x, z)
3397   if (N1.getOpcode() == ISD::FCOPYSIGN)
3398     return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3399   
3400   // copysign(x, fp_extend(y)) -> copysign(x, y)
3401   // copysign(x, fp_round(y)) -> copysign(x, y)
3402   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3403     return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3404   
3405   return SDOperand();
3406 }
3407
3408
3409
3410 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3411   SDOperand N0 = N->getOperand(0);
3412   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3413   MVT::ValueType VT = N->getValueType(0);
3414   
3415   // fold (sint_to_fp c1) -> c1fp
3416   if (N0C && N0.getValueType() != MVT::ppcf128)
3417     return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3418   return SDOperand();
3419 }
3420
3421 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3422   SDOperand N0 = N->getOperand(0);
3423   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3424   MVT::ValueType VT = N->getValueType(0);
3425
3426   // fold (uint_to_fp c1) -> c1fp
3427   if (N0C && N0.getValueType() != MVT::ppcf128)
3428     return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3429   return SDOperand();
3430 }
3431
3432 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3433   SDOperand N0 = N->getOperand(0);
3434   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3435   MVT::ValueType VT = N->getValueType(0);
3436   
3437   // fold (fp_to_sint c1fp) -> c1
3438   if (N0CFP)
3439     return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3440   return SDOperand();
3441 }
3442
3443 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3444   SDOperand N0 = N->getOperand(0);
3445   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3446   MVT::ValueType VT = N->getValueType(0);
3447   
3448   // fold (fp_to_uint c1fp) -> c1
3449   if (N0CFP && VT != MVT::ppcf128)
3450     return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3451   return SDOperand();
3452 }
3453
3454 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3455   SDOperand N0 = N->getOperand(0);
3456   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3457   MVT::ValueType VT = N->getValueType(0);
3458   
3459   // fold (fp_round c1fp) -> c1fp
3460   if (N0CFP && N0.getValueType() != MVT::ppcf128)
3461     return DAG.getNode(ISD::FP_ROUND, VT, N0);
3462   
3463   // fold (fp_round (fp_extend x)) -> x
3464   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3465     return N0.getOperand(0);
3466   
3467   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3468   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
3469     SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0));
3470     AddToWorkList(Tmp.Val);
3471     return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3472   }
3473   
3474   return SDOperand();
3475 }
3476
3477 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3478   SDOperand N0 = N->getOperand(0);
3479   MVT::ValueType VT = N->getValueType(0);
3480   MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3481   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3482   
3483   // fold (fp_round_inreg c1fp) -> c1fp
3484   if (N0CFP) {
3485     SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
3486     return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3487   }
3488   return SDOperand();
3489 }
3490
3491 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3492   SDOperand N0 = N->getOperand(0);
3493   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3494   MVT::ValueType VT = N->getValueType(0);
3495   
3496   // fold (fp_extend c1fp) -> c1fp
3497   if (N0CFP && VT != MVT::ppcf128)
3498     return DAG.getNode(ISD::FP_EXTEND, VT, N0);
3499   
3500   // fold (fpext (load x)) -> (fpext (fpround (extload x)))
3501   if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3502       (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3503     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3504     SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3505                                        LN0->getBasePtr(), LN0->getSrcValue(),
3506                                        LN0->getSrcValueOffset(),
3507                                        N0.getValueType(),
3508                                        LN0->isVolatile(), 
3509                                        LN0->getAlignment());
3510     CombineTo(N, ExtLoad);
3511     CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad),
3512               ExtLoad.getValue(1));
3513     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
3514   }
3515   
3516   
3517   return SDOperand();
3518 }
3519
3520 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3521   SDOperand N0 = N->getOperand(0);
3522
3523   if (isNegatibleForFree(N0))
3524     return GetNegatedExpression(N0, DAG);
3525
3526   return SDOperand();
3527 }
3528
3529 SDOperand DAGCombiner::visitFABS(SDNode *N) {
3530   SDOperand N0 = N->getOperand(0);
3531   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3532   MVT::ValueType VT = N->getValueType(0);
3533   
3534   // fold (fabs c1) -> fabs(c1)
3535   if (N0CFP && VT != MVT::ppcf128)
3536     return DAG.getNode(ISD::FABS, VT, N0);
3537   // fold (fabs (fabs x)) -> (fabs x)
3538   if (N0.getOpcode() == ISD::FABS)
3539     return N->getOperand(0);
3540   // fold (fabs (fneg x)) -> (fabs x)
3541   // fold (fabs (fcopysign x, y)) -> (fabs x)
3542   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
3543     return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
3544   
3545   return SDOperand();
3546 }
3547
3548 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
3549   SDOperand Chain = N->getOperand(0);
3550   SDOperand N1 = N->getOperand(1);
3551   SDOperand N2 = N->getOperand(2);
3552   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3553   
3554   // never taken branch, fold to chain
3555   if (N1C && N1C->isNullValue())
3556     return Chain;
3557   // unconditional branch
3558   if (N1C && N1C->getValue() == 1)
3559     return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
3560   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
3561   // on the target.
3562   if (N1.getOpcode() == ISD::SETCC && 
3563       TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
3564     return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
3565                        N1.getOperand(0), N1.getOperand(1), N2);
3566   }
3567   return SDOperand();
3568 }
3569
3570 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
3571 //
3572 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
3573   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
3574   SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
3575   
3576   // Use SimplifySetCC  to simplify SETCC's.
3577   SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
3578   if (Simp.Val) AddToWorkList(Simp.Val);
3579
3580   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
3581
3582   // fold br_cc true, dest -> br dest (unconditional branch)
3583   if (SCCC && SCCC->getValue())
3584     return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
3585                        N->getOperand(4));
3586   // fold br_cc false, dest -> unconditional fall through
3587   if (SCCC && SCCC->isNullValue())
3588     return N->getOperand(0);
3589
3590   // fold to a simpler setcc
3591   if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
3592     return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0), 
3593                        Simp.getOperand(2), Simp.getOperand(0),
3594                        Simp.getOperand(1), N->getOperand(4));
3595   return SDOperand();
3596 }
3597
3598
3599 /// CombineToPreIndexedLoadStore - Try turning a load / store and a
3600 /// pre-indexed load / store when the base pointer is a add or subtract
3601 /// and it has other uses besides the load / store. After the
3602 /// transformation, the new indexed load / store has effectively folded
3603 /// the add / subtract in and all of its other uses are redirected to the
3604 /// new load / store.
3605 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
3606   if (!AfterLegalize)
3607     return false;
3608
3609   bool isLoad = true;
3610   SDOperand Ptr;
3611   MVT::ValueType VT;
3612   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
3613     if (LD->getAddressingMode() != ISD::UNINDEXED)
3614       return false;
3615     VT = LD->getLoadedVT();
3616     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
3617         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
3618       return false;
3619     Ptr = LD->getBasePtr();
3620   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
3621     if (ST->getAddressingMode() != ISD::UNINDEXED)
3622       return false;
3623     VT = ST->getStoredVT();
3624     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
3625         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
3626       return false;
3627     Ptr = ST->getBasePtr();
3628     isLoad = false;
3629   } else
3630     return false;
3631
3632   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
3633   // out.  There is no reason to make this a preinc/predec.
3634   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
3635       Ptr.Val->hasOneUse())
3636     return false;
3637
3638   // Ask the target to do addressing mode selection.
3639   SDOperand BasePtr;
3640   SDOperand Offset;
3641   ISD::MemIndexedMode AM = ISD::UNINDEXED;
3642   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
3643     return false;
3644   // Don't create a indexed load / store with zero offset.
3645   if (isa<ConstantSDNode>(Offset) &&
3646       cast<ConstantSDNode>(Offset)->getValue() == 0)
3647     return false;
3648   
3649   // Try turning it into a pre-indexed load / store except when:
3650   // 1) The new base ptr is a frame index.
3651   // 2) If N is a store and the new base ptr is either the same as or is a
3652   //    predecessor of the value being stored.
3653   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
3654   //    that would create a cycle.
3655   // 4) All uses are load / store ops that use it as old base ptr.
3656
3657   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
3658   // (plus the implicit offset) to a register to preinc anyway.
3659   if (isa<FrameIndexSDNode>(BasePtr))
3660     return false;
3661   
3662   // Check #2.
3663   if (!isLoad) {
3664     SDOperand Val = cast<StoreSDNode>(N)->getValue();
3665     if (Val == BasePtr || BasePtr.Val->isPredecessor(Val.Val))
3666       return false;
3667   }
3668
3669   // Now check for #3 and #4.
3670   bool RealUse = false;
3671   for (SDNode::use_iterator I = Ptr.Val->use_begin(),
3672          E = Ptr.Val->use_end(); I != E; ++I) {
3673     SDNode *Use = *I;
3674     if (Use == N)
3675       continue;
3676     if (Use->isPredecessor(N))
3677       return false;
3678
3679     if (!((Use->getOpcode() == ISD::LOAD &&
3680            cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
3681           (Use->getOpcode() == ISD::STORE) &&
3682           cast<StoreSDNode>(Use)->getBasePtr() == Ptr))
3683       RealUse = true;
3684   }
3685   if (!RealUse)
3686     return false;
3687
3688   SDOperand Result;
3689   if (isLoad)
3690     Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
3691   else
3692     Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
3693   ++PreIndexedNodes;
3694   ++NodesCombined;
3695   DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
3696   DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
3697   DOUT << '\n';
3698   std::vector<SDNode*> NowDead;
3699   if (isLoad) {
3700     DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
3701                                   &NowDead);
3702     DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
3703                                   &NowDead);
3704   } else {
3705     DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
3706                                   &NowDead);
3707   }
3708
3709   // Nodes can end up on the worklist more than once.  Make sure we do
3710   // not process a node that has been replaced.
3711   for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3712     removeFromWorkList(NowDead[i]);
3713   // Finally, since the node is now dead, remove it from the graph.
3714   DAG.DeleteNode(N);
3715
3716   // Replace the uses of Ptr with uses of the updated base value.
3717   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
3718                                 &NowDead);
3719   removeFromWorkList(Ptr.Val);
3720   for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3721     removeFromWorkList(NowDead[i]);
3722   DAG.DeleteNode(Ptr.Val);
3723
3724   return true;
3725 }
3726
3727 /// CombineToPostIndexedLoadStore - Try combine a load / store with a
3728 /// add / sub of the base pointer node into a post-indexed load / store.
3729 /// The transformation folded the add / subtract into the new indexed
3730 /// load / store effectively and all of its uses are redirected to the
3731 /// new load / store.
3732 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
3733   if (!AfterLegalize)
3734     return false;
3735
3736   bool isLoad = true;
3737   SDOperand Ptr;
3738   MVT::ValueType VT;
3739   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
3740     if (LD->getAddressingMode() != ISD::UNINDEXED)
3741       return false;
3742     VT = LD->getLoadedVT();
3743     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
3744         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
3745       return false;
3746     Ptr = LD->getBasePtr();
3747   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
3748     if (ST->getAddressingMode() != ISD::UNINDEXED)
3749       return false;
3750     VT = ST->getStoredVT();
3751     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
3752         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
3753       return false;
3754     Ptr = ST->getBasePtr();
3755     isLoad = false;
3756   } else
3757     return false;
3758
3759   if (Ptr.Val->hasOneUse())
3760     return false;
3761   
3762   for (SDNode::use_iterator I = Ptr.Val->use_begin(),
3763          E = Ptr.Val->use_end(); I != E; ++I) {
3764     SDNode *Op = *I;
3765     if (Op == N ||
3766         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
3767       continue;
3768
3769     SDOperand BasePtr;
3770     SDOperand Offset;
3771     ISD::MemIndexedMode AM = ISD::UNINDEXED;
3772     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
3773       if (Ptr == Offset)
3774         std::swap(BasePtr, Offset);
3775       if (Ptr != BasePtr)
3776         continue;
3777       // Don't create a indexed load / store with zero offset.
3778       if (isa<ConstantSDNode>(Offset) &&
3779           cast<ConstantSDNode>(Offset)->getValue() == 0)
3780         continue;
3781
3782       // Try turning it into a post-indexed load / store except when
3783       // 1) All uses are load / store ops that use it as base ptr.
3784       // 2) Op must be independent of N, i.e. Op is neither a predecessor
3785       //    nor a successor of N. Otherwise, if Op is folded that would
3786       //    create a cycle.
3787
3788       // Check for #1.
3789       bool TryNext = false;
3790       for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
3791              EE = BasePtr.Val->use_end(); II != EE; ++II) {
3792         SDNode *Use = *II;
3793         if (Use == Ptr.Val)
3794           continue;
3795
3796         // If all the uses are load / store addresses, then don't do the
3797         // transformation.
3798         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
3799           bool RealUse = false;
3800           for (SDNode::use_iterator III = Use->use_begin(),
3801                  EEE = Use->use_end(); III != EEE; ++III) {
3802             SDNode *UseUse = *III;
3803             if (!((UseUse->getOpcode() == ISD::LOAD &&
3804                    cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
3805                   (UseUse->getOpcode() == ISD::STORE) &&
3806                   cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use))
3807               RealUse = true;
3808           }
3809
3810           if (!RealUse) {
3811             TryNext = true;
3812             break;
3813           }
3814         }
3815       }
3816       if (TryNext)
3817         continue;
3818
3819       // Check for #2
3820       if (!Op->isPredecessor(N) && !N->isPredecessor(Op)) {
3821         SDOperand Result = isLoad
3822           ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
3823           : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
3824         ++PostIndexedNodes;
3825         ++NodesCombined;
3826         DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
3827         DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
3828         DOUT << '\n';
3829         std::vector<SDNode*> NowDead;
3830         if (isLoad) {
3831           DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
3832                                         &NowDead);
3833           DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
3834                                         &NowDead);
3835         } else {
3836           DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
3837                                         &NowDead);
3838         }
3839
3840         // Nodes can end up on the worklist more than once.  Make sure we do
3841         // not process a node that has been replaced.
3842         for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3843           removeFromWorkList(NowDead[i]);
3844         // Finally, since the node is now dead, remove it from the graph.
3845         DAG.DeleteNode(N);
3846
3847         // Replace the uses of Use with uses of the updated base value.
3848         DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
3849                                       Result.getValue(isLoad ? 1 : 0),
3850                                       &NowDead);
3851         removeFromWorkList(Op);
3852         for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3853           removeFromWorkList(NowDead[i]);
3854         DAG.DeleteNode(Op);
3855
3856         return true;
3857       }
3858     }
3859   }
3860   return false;
3861 }
3862
3863
3864 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
3865   LoadSDNode *LD  = cast<LoadSDNode>(N);
3866   SDOperand Chain = LD->getChain();
3867   SDOperand Ptr   = LD->getBasePtr();
3868
3869   // If load is not volatile and there are no uses of the loaded value (and
3870   // the updated indexed value in case of indexed loads), change uses of the
3871   // chain value into uses of the chain input (i.e. delete the dead load).
3872   if (!LD->isVolatile()) {
3873     if (N->getValueType(1) == MVT::Other) {
3874       // Unindexed loads.
3875       if (N->hasNUsesOfValue(0, 0))
3876         return CombineTo(N, DAG.getNode(ISD::UNDEF, N->getValueType(0)), Chain);
3877     } else {
3878       // Indexed loads.
3879       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
3880       if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
3881         SDOperand Undef0 = DAG.getNode(ISD::UNDEF, N->getValueType(0));
3882         SDOperand Undef1 = DAG.getNode(ISD::UNDEF, N->getValueType(1));
3883         SDOperand To[] = { Undef0, Undef1, Chain };
3884         return CombineTo(N, To, 3);
3885       }
3886     }
3887   }
3888   
3889   // If this load is directly stored, replace the load value with the stored
3890   // value.
3891   // TODO: Handle store large -> read small portion.
3892   // TODO: Handle TRUNCSTORE/LOADEXT
3893   if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
3894     if (ISD::isNON_TRUNCStore(Chain.Val)) {
3895       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
3896       if (PrevST->getBasePtr() == Ptr &&
3897           PrevST->getValue().getValueType() == N->getValueType(0))
3898       return CombineTo(N, Chain.getOperand(1), Chain);
3899     }
3900   }
3901     
3902   if (CombinerAA) {
3903     // Walk up chain skipping non-aliasing memory nodes.
3904     SDOperand BetterChain = FindBetterChain(N, Chain);
3905     
3906     // If there is a better chain.
3907     if (Chain != BetterChain) {
3908       SDOperand ReplLoad;
3909
3910       // Replace the chain to void dependency.
3911       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
3912         ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
3913                                LD->getSrcValue(), LD->getSrcValueOffset(),
3914                                LD->isVolatile(), LD->getAlignment());
3915       } else {
3916         ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
3917                                   LD->getValueType(0),
3918                                   BetterChain, Ptr, LD->getSrcValue(),
3919                                   LD->getSrcValueOffset(),
3920                                   LD->getLoadedVT(),
3921                                   LD->isVolatile(), 
3922                                   LD->getAlignment());
3923       }
3924
3925       // Create token factor to keep old chain connected.
3926       SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
3927                                     Chain, ReplLoad.getValue(1));
3928       
3929       // Replace uses with load result and token factor. Don't add users
3930       // to work list.
3931       return CombineTo(N, ReplLoad.getValue(0), Token, false);
3932     }
3933   }
3934
3935   // Try transforming N to an indexed load.
3936   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
3937     return SDOperand(N, 0);
3938
3939   return SDOperand();
3940 }
3941
3942 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
3943   StoreSDNode *ST  = cast<StoreSDNode>(N);
3944   SDOperand Chain = ST->getChain();
3945   SDOperand Value = ST->getValue();
3946   SDOperand Ptr   = ST->getBasePtr();
3947   
3948   // If this is a store of a bit convert, store the input value if the
3949   // resultant store does not need a higher alignment than the original.
3950   if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
3951       ST->getAddressingMode() == ISD::UNINDEXED) {
3952     unsigned Align = ST->getAlignment();
3953     MVT::ValueType SVT = Value.getOperand(0).getValueType();
3954     unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
3955       getABITypeAlignment(MVT::getTypeForValueType(SVT));
3956     if (Align <= OrigAlign && TLI.isOperationLegal(ISD::STORE, SVT))
3957       return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
3958                           ST->getSrcValueOffset(), ST->isVolatile(), Align);
3959   }
3960   
3961   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
3962   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
3963     if (Value.getOpcode() != ISD::TargetConstantFP) {
3964       SDOperand Tmp;
3965       switch (CFP->getValueType(0)) {
3966       default: assert(0 && "Unknown FP type");
3967       case MVT::f80:    // We don't do this for these yet.
3968       case MVT::f128:
3969       case MVT::ppcf128:
3970         break;
3971       case MVT::f32:
3972         if (!AfterLegalize || TLI.isTypeLegal(MVT::i32)) {
3973           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
3974                               convertToAPInt().getZExtValue(), MVT::i32);
3975           return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
3976                               ST->getSrcValueOffset(), ST->isVolatile(),
3977                               ST->getAlignment());
3978         }
3979         break;
3980       case MVT::f64:
3981         if (!AfterLegalize || TLI.isTypeLegal(MVT::i64)) {
3982           Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
3983                                   getZExtValue(), MVT::i64);
3984           return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
3985                               ST->getSrcValueOffset(), ST->isVolatile(),
3986                               ST->getAlignment());
3987         } else if (TLI.isTypeLegal(MVT::i32)) {
3988           // Many FP stores are not made apparent until after legalize, e.g. for
3989           // argument passing.  Since this is so common, custom legalize the
3990           // 64-bit integer store into two 32-bit stores.
3991           uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
3992           SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
3993           SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
3994           if (!TLI.isLittleEndian()) std::swap(Lo, Hi);
3995
3996           int SVOffset = ST->getSrcValueOffset();
3997           unsigned Alignment = ST->getAlignment();
3998           bool isVolatile = ST->isVolatile();
3999
4000           SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4001                                        ST->getSrcValueOffset(),
4002                                        isVolatile, ST->getAlignment());
4003           Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4004                             DAG.getConstant(4, Ptr.getValueType()));
4005           SVOffset += 4;
4006           Alignment = MinAlign(Alignment, 4U);
4007           SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4008                                        SVOffset, isVolatile, Alignment);
4009           return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4010         }
4011         break;
4012       }
4013     }
4014   }
4015
4016   if (CombinerAA) { 
4017     // Walk up chain skipping non-aliasing memory nodes.
4018     SDOperand BetterChain = FindBetterChain(N, Chain);
4019     
4020     // If there is a better chain.
4021     if (Chain != BetterChain) {
4022       // Replace the chain to avoid dependency.
4023       SDOperand ReplStore;
4024       if (ST->isTruncatingStore()) {
4025         ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4026           ST->getSrcValue(), ST->getSrcValueOffset(), ST->getStoredVT(),
4027           ST->isVolatile(), ST->getAlignment());
4028       } else {
4029         ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4030           ST->getSrcValue(), ST->getSrcValueOffset(),
4031           ST->isVolatile(), ST->getAlignment());
4032       }
4033       
4034       // Create token to keep both nodes around.
4035       SDOperand Token =
4036         DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4037         
4038       // Don't add users to work list.
4039       return CombineTo(N, Token, false);
4040     }
4041   }
4042   
4043   // Try transforming N to an indexed store.
4044   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4045     return SDOperand(N, 0);
4046
4047   // FIXME: is there such a think as a truncating indexed store?
4048   if (ST->isTruncatingStore() && ST->getAddressingMode() == ISD::UNINDEXED &&
4049       MVT::isInteger(Value.getValueType())) {
4050     // See if we can simplify the input to this truncstore with knowledge that
4051     // only the low bits are being used.  For example:
4052     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
4053     SDOperand Shorter = 
4054       GetDemandedBits(Value, MVT::getIntVTBitMask(ST->getStoredVT()));
4055     AddToWorkList(Value.Val);
4056     if (Shorter.Val)
4057       return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4058                                ST->getSrcValueOffset(), ST->getStoredVT(),
4059                                ST->isVolatile(), ST->getAlignment());
4060     
4061     // Otherwise, see if we can simplify the operation with
4062     // SimplifyDemandedBits, which only works if the value has a single use.
4063     if (SimplifyDemandedBits(Value, MVT::getIntVTBitMask(ST->getStoredVT())))
4064       return SDOperand(N, 0);
4065   }
4066   
4067   return SDOperand();
4068 }
4069
4070 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4071   SDOperand InVec = N->getOperand(0);
4072   SDOperand InVal = N->getOperand(1);
4073   SDOperand EltNo = N->getOperand(2);
4074   
4075   // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4076   // vector with the inserted element.
4077   if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4078     unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4079     SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4080     if (Elt < Ops.size())
4081       Ops[Elt] = InVal;
4082     return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4083                        &Ops[0], Ops.size());
4084   }
4085   
4086   return SDOperand();
4087 }
4088
4089 SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4090   SDOperand InVec = N->getOperand(0);
4091   SDOperand EltNo = N->getOperand(1);
4092
4093   // (vextract (v4f32 s2v (f32 load $addr)), 0) -> (f32 load $addr)
4094   // (vextract (v4i32 bc (v4f32 s2v (f32 load $addr))), 0) -> (i32 load $addr)
4095   if (isa<ConstantSDNode>(EltNo)) {
4096     unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4097     bool NewLoad = false;
4098     if (Elt == 0) {
4099       MVT::ValueType VT = InVec.getValueType();
4100       MVT::ValueType EVT = MVT::getVectorElementType(VT);
4101       MVT::ValueType LVT = EVT;
4102       unsigned NumElts = MVT::getVectorNumElements(VT);
4103       if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4104         MVT::ValueType BCVT = InVec.getOperand(0).getValueType();
4105         if (NumElts != MVT::getVectorNumElements(BCVT))
4106           return SDOperand();
4107         InVec = InVec.getOperand(0);
4108         EVT = MVT::getVectorElementType(BCVT);
4109         NewLoad = true;
4110       }
4111       if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4112           InVec.getOperand(0).getValueType() == EVT &&
4113           ISD::isNormalLoad(InVec.getOperand(0).Val) &&
4114           InVec.getOperand(0).hasOneUse()) {
4115         LoadSDNode *LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4116         unsigned Align = LN0->getAlignment();
4117         if (NewLoad) {
4118           // Check the resultant load doesn't need a higher alignment than the
4119           // original load.
4120           unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4121             getABITypeAlignment(MVT::getTypeForValueType(LVT));
4122           if (!TLI.isOperationLegal(ISD::LOAD, LVT) || NewAlign > Align)
4123             return SDOperand();
4124           Align = NewAlign;
4125         }
4126
4127         return DAG.getLoad(LVT, LN0->getChain(), LN0->getBasePtr(),
4128                            LN0->getSrcValue(), LN0->getSrcValueOffset(),
4129                            LN0->isVolatile(), Align);
4130       }
4131     }
4132   }
4133   return SDOperand();
4134 }
4135   
4136
4137 SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4138   unsigned NumInScalars = N->getNumOperands();
4139   MVT::ValueType VT = N->getValueType(0);
4140   unsigned NumElts = MVT::getVectorNumElements(VT);
4141   MVT::ValueType EltType = MVT::getVectorElementType(VT);
4142
4143   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4144   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4145   // at most two distinct vectors, turn this into a shuffle node.
4146   SDOperand VecIn1, VecIn2;
4147   for (unsigned i = 0; i != NumInScalars; ++i) {
4148     // Ignore undef inputs.
4149     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4150     
4151     // If this input is something other than a EXTRACT_VECTOR_ELT with a
4152     // constant index, bail out.
4153     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4154         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4155       VecIn1 = VecIn2 = SDOperand(0, 0);
4156       break;
4157     }
4158     
4159     // If the input vector type disagrees with the result of the build_vector,
4160     // we can't make a shuffle.
4161     SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4162     if (ExtractedFromVec.getValueType() != VT) {
4163       VecIn1 = VecIn2 = SDOperand(0, 0);
4164       break;
4165     }
4166     
4167     // Otherwise, remember this.  We allow up to two distinct input vectors.
4168     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4169       continue;
4170     
4171     if (VecIn1.Val == 0) {
4172       VecIn1 = ExtractedFromVec;
4173     } else if (VecIn2.Val == 0) {
4174       VecIn2 = ExtractedFromVec;
4175     } else {
4176       // Too many inputs.
4177       VecIn1 = VecIn2 = SDOperand(0, 0);
4178       break;
4179     }
4180   }
4181   
4182   // If everything is good, we can make a shuffle operation.
4183   if (VecIn1.Val) {
4184     SmallVector<SDOperand, 8> BuildVecIndices;
4185     for (unsigned i = 0; i != NumInScalars; ++i) {
4186       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4187         BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4188         continue;
4189       }
4190       
4191       SDOperand Extract = N->getOperand(i);
4192       
4193       // If extracting from the first vector, just use the index directly.
4194       if (Extract.getOperand(0) == VecIn1) {
4195         BuildVecIndices.push_back(Extract.getOperand(1));
4196         continue;
4197       }
4198
4199       // Otherwise, use InIdx + VecSize
4200       unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
4201       BuildVecIndices.push_back(DAG.getConstant(Idx+NumInScalars,
4202                                                 TLI.getPointerTy()));
4203     }
4204     
4205     // Add count and size info.
4206     MVT::ValueType BuildVecVT =
4207       MVT::getVectorType(TLI.getPointerTy(), NumElts);
4208     
4209     // Return the new VECTOR_SHUFFLE node.
4210     SDOperand Ops[5];
4211     Ops[0] = VecIn1;
4212     if (VecIn2.Val) {
4213       Ops[1] = VecIn2;
4214     } else {
4215       // Use an undef build_vector as input for the second operand.
4216       std::vector<SDOperand> UnOps(NumInScalars,
4217                                    DAG.getNode(ISD::UNDEF, 
4218                                                EltType));
4219       Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4220                            &UnOps[0], UnOps.size());
4221       AddToWorkList(Ops[1].Val);
4222     }
4223     Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4224                          &BuildVecIndices[0], BuildVecIndices.size());
4225     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4226   }
4227   
4228   return SDOperand();
4229 }
4230
4231 SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4232   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4233   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
4234   // inputs come from at most two distinct vectors, turn this into a shuffle
4235   // node.
4236
4237   // If we only have one input vector, we don't need to do any concatenation.
4238   if (N->getNumOperands() == 1) {
4239     return N->getOperand(0);
4240   }
4241
4242   return SDOperand();
4243 }
4244
4245 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4246   SDOperand ShufMask = N->getOperand(2);
4247   unsigned NumElts = ShufMask.getNumOperands();
4248
4249   // If the shuffle mask is an identity operation on the LHS, return the LHS.
4250   bool isIdentity = true;
4251   for (unsigned i = 0; i != NumElts; ++i) {
4252     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4253         cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4254       isIdentity = false;
4255       break;
4256     }
4257   }
4258   if (isIdentity) return N->getOperand(0);
4259
4260   // If the shuffle mask is an identity operation on the RHS, return the RHS.
4261   isIdentity = true;
4262   for (unsigned i = 0; i != NumElts; ++i) {
4263     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4264         cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4265       isIdentity = false;
4266       break;
4267     }
4268   }
4269   if (isIdentity) return N->getOperand(1);
4270
4271   // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4272   // needed at all.
4273   bool isUnary = true;
4274   bool isSplat = true;
4275   int VecNum = -1;
4276   unsigned BaseIdx = 0;
4277   for (unsigned i = 0; i != NumElts; ++i)
4278     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4279       unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4280       int V = (Idx < NumElts) ? 0 : 1;
4281       if (VecNum == -1) {
4282         VecNum = V;
4283         BaseIdx = Idx;
4284       } else {
4285         if (BaseIdx != Idx)
4286           isSplat = false;
4287         if (VecNum != V) {
4288           isUnary = false;
4289           break;
4290         }
4291       }
4292     }
4293
4294   SDOperand N0 = N->getOperand(0);
4295   SDOperand N1 = N->getOperand(1);
4296   // Normalize unary shuffle so the RHS is undef.
4297   if (isUnary && VecNum == 1)
4298     std::swap(N0, N1);
4299
4300   // If it is a splat, check if the argument vector is a build_vector with
4301   // all scalar elements the same.
4302   if (isSplat) {
4303     SDNode *V = N0.Val;
4304
4305     // If this is a bit convert that changes the element type of the vector but
4306     // not the number of vector elements, look through it.  Be careful not to
4307     // look though conversions that change things like v4f32 to v2f64.
4308     if (V->getOpcode() == ISD::BIT_CONVERT) {
4309       SDOperand ConvInput = V->getOperand(0);
4310       if (MVT::getVectorNumElements(ConvInput.getValueType()) == NumElts)
4311         V = ConvInput.Val;
4312     }
4313
4314     if (V->getOpcode() == ISD::BUILD_VECTOR) {
4315       unsigned NumElems = V->getNumOperands();
4316       if (NumElems > BaseIdx) {
4317         SDOperand Base;
4318         bool AllSame = true;
4319         for (unsigned i = 0; i != NumElems; ++i) {
4320           if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4321             Base = V->getOperand(i);
4322             break;
4323           }
4324         }
4325         // Splat of <u, u, u, u>, return <u, u, u, u>
4326         if (!Base.Val)
4327           return N0;
4328         for (unsigned i = 0; i != NumElems; ++i) {
4329           if (V->getOperand(i) != Base) {
4330             AllSame = false;
4331             break;
4332           }
4333         }
4334         // Splat of <x, x, x, x>, return <x, x, x, x>
4335         if (AllSame)
4336           return N0;
4337       }
4338     }
4339   }
4340
4341   // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4342   // into an undef.
4343   if (isUnary || N0 == N1) {
4344     // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4345     // first operand.
4346     SmallVector<SDOperand, 8> MappedOps;
4347     for (unsigned i = 0; i != NumElts; ++i) {
4348       if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4349           cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4350         MappedOps.push_back(ShufMask.getOperand(i));
4351       } else {
4352         unsigned NewIdx = 
4353           cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4354         MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4355       }
4356     }
4357     ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4358                            &MappedOps[0], MappedOps.size());
4359     AddToWorkList(ShufMask.Val);
4360     return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
4361                        N0,
4362                        DAG.getNode(ISD::UNDEF, N->getValueType(0)),
4363                        ShufMask);
4364   }
4365  
4366   return SDOperand();
4367 }
4368
4369 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
4370 /// an AND to a vector_shuffle with the destination vector and a zero vector.
4371 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
4372 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
4373 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
4374   SDOperand LHS = N->getOperand(0);
4375   SDOperand RHS = N->getOperand(1);
4376   if (N->getOpcode() == ISD::AND) {
4377     if (RHS.getOpcode() == ISD::BIT_CONVERT)
4378       RHS = RHS.getOperand(0);
4379     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
4380       std::vector<SDOperand> IdxOps;
4381       unsigned NumOps = RHS.getNumOperands();
4382       unsigned NumElts = NumOps;
4383       MVT::ValueType EVT = MVT::getVectorElementType(RHS.getValueType());
4384       for (unsigned i = 0; i != NumElts; ++i) {
4385         SDOperand Elt = RHS.getOperand(i);
4386         if (!isa<ConstantSDNode>(Elt))
4387           return SDOperand();
4388         else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
4389           IdxOps.push_back(DAG.getConstant(i, EVT));
4390         else if (cast<ConstantSDNode>(Elt)->isNullValue())
4391           IdxOps.push_back(DAG.getConstant(NumElts, EVT));
4392         else
4393           return SDOperand();
4394       }
4395
4396       // Let's see if the target supports this vector_shuffle.
4397       if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
4398         return SDOperand();
4399
4400       // Return the new VECTOR_SHUFFLE node.
4401       MVT::ValueType VT = MVT::getVectorType(EVT, NumElts);
4402       std::vector<SDOperand> Ops;
4403       LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
4404       Ops.push_back(LHS);
4405       AddToWorkList(LHS.Val);
4406       std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
4407       Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4408                                 &ZeroOps[0], ZeroOps.size()));
4409       Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4410                                 &IdxOps[0], IdxOps.size()));
4411       SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
4412                                      &Ops[0], Ops.size());
4413       if (VT != LHS.getValueType()) {
4414         Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
4415       }
4416       return Result;
4417     }
4418   }
4419   return SDOperand();
4420 }
4421
4422 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
4423 SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
4424   // After legalize, the target may be depending on adds and other
4425   // binary ops to provide legal ways to construct constants or other
4426   // things. Simplifying them may result in a loss of legality.
4427   if (AfterLegalize) return SDOperand();
4428
4429   MVT::ValueType VT = N->getValueType(0);
4430   assert(MVT::isVector(VT) && "SimplifyVBinOp only works on vectors!");
4431
4432   MVT::ValueType EltType = MVT::getVectorElementType(VT);
4433   SDOperand LHS = N->getOperand(0);
4434   SDOperand RHS = N->getOperand(1);
4435   SDOperand Shuffle = XformToShuffleWithZero(N);
4436   if (Shuffle.Val) return Shuffle;
4437
4438   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
4439   // this operation.
4440   if (LHS.getOpcode() == ISD::BUILD_VECTOR && 
4441       RHS.getOpcode() == ISD::BUILD_VECTOR) {
4442     SmallVector<SDOperand, 8> Ops;
4443     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
4444       SDOperand LHSOp = LHS.getOperand(i);
4445       SDOperand RHSOp = RHS.getOperand(i);
4446       // If these two elements can't be folded, bail out.
4447       if ((LHSOp.getOpcode() != ISD::UNDEF &&
4448            LHSOp.getOpcode() != ISD::Constant &&
4449            LHSOp.getOpcode() != ISD::ConstantFP) ||
4450           (RHSOp.getOpcode() != ISD::UNDEF &&
4451            RHSOp.getOpcode() != ISD::Constant &&
4452            RHSOp.getOpcode() != ISD::ConstantFP))
4453         break;
4454       // Can't fold divide by zero.
4455       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
4456           N->getOpcode() == ISD::FDIV) {
4457         if ((RHSOp.getOpcode() == ISD::Constant &&
4458              cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
4459             (RHSOp.getOpcode() == ISD::ConstantFP &&
4460              cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
4461           break;
4462       }
4463       Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
4464       AddToWorkList(Ops.back().Val);
4465       assert((Ops.back().getOpcode() == ISD::UNDEF ||
4466               Ops.back().getOpcode() == ISD::Constant ||
4467               Ops.back().getOpcode() == ISD::ConstantFP) &&
4468              "Scalar binop didn't fold!");
4469     }
4470     
4471     if (Ops.size() == LHS.getNumOperands()) {
4472       MVT::ValueType VT = LHS.getValueType();
4473       return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
4474     }
4475   }
4476   
4477   return SDOperand();
4478 }
4479
4480 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
4481   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
4482   
4483   SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
4484                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
4485   // If we got a simplified select_cc node back from SimplifySelectCC, then
4486   // break it down into a new SETCC node, and a new SELECT node, and then return
4487   // the SELECT node, since we were called with a SELECT node.
4488   if (SCC.Val) {
4489     // Check to see if we got a select_cc back (to turn into setcc/select).
4490     // Otherwise, just return whatever node we got back, like fabs.
4491     if (SCC.getOpcode() == ISD::SELECT_CC) {
4492       SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
4493                                     SCC.getOperand(0), SCC.getOperand(1), 
4494                                     SCC.getOperand(4));
4495       AddToWorkList(SETCC.Val);
4496       return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
4497                          SCC.getOperand(3), SETCC);
4498     }
4499     return SCC;
4500   }
4501   return SDOperand();
4502 }
4503
4504 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
4505 /// are the two values being selected between, see if we can simplify the
4506 /// select.  Callers of this should assume that TheSelect is deleted if this
4507 /// returns true.  As such, they should return the appropriate thing (e.g. the
4508 /// node) back to the top-level of the DAG combiner loop to avoid it being
4509 /// looked at.
4510 ///
4511 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS, 
4512                                     SDOperand RHS) {
4513   
4514   // If this is a select from two identical things, try to pull the operation
4515   // through the select.
4516   if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
4517     // If this is a load and the token chain is identical, replace the select
4518     // of two loads with a load through a select of the address to load from.
4519     // This triggers in things like "select bool X, 10.0, 123.0" after the FP
4520     // constants have been dropped into the constant pool.
4521     if (LHS.getOpcode() == ISD::LOAD &&
4522         // Token chains must be identical.
4523         LHS.getOperand(0) == RHS.getOperand(0)) {
4524       LoadSDNode *LLD = cast<LoadSDNode>(LHS);
4525       LoadSDNode *RLD = cast<LoadSDNode>(RHS);
4526
4527       // If this is an EXTLOAD, the VT's must match.
4528       if (LLD->getLoadedVT() == RLD->getLoadedVT()) {
4529         // FIXME: this conflates two src values, discarding one.  This is not
4530         // the right thing to do, but nothing uses srcvalues now.  When they do,
4531         // turn SrcValue into a list of locations.
4532         SDOperand Addr;
4533         if (TheSelect->getOpcode() == ISD::SELECT) {
4534           // Check that the condition doesn't reach either load.  If so, folding
4535           // this will induce a cycle into the DAG.
4536           if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4537               !RLD->isPredecessor(TheSelect->getOperand(0).Val)) {
4538             Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
4539                                TheSelect->getOperand(0), LLD->getBasePtr(),
4540                                RLD->getBasePtr());
4541           }
4542         } else {
4543           // Check that the condition doesn't reach either load.  If so, folding
4544           // this will induce a cycle into the DAG.
4545           if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4546               !RLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4547               !LLD->isPredecessor(TheSelect->getOperand(1).Val) &&
4548               !RLD->isPredecessor(TheSelect->getOperand(1).Val)) {
4549             Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
4550                              TheSelect->getOperand(0),
4551                              TheSelect->getOperand(1), 
4552                              LLD->getBasePtr(), RLD->getBasePtr(),
4553                              TheSelect->getOperand(4));
4554           }
4555         }
4556         
4557         if (Addr.Val) {
4558           SDOperand Load;
4559           if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
4560             Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
4561                                Addr,LLD->getSrcValue(), 
4562                                LLD->getSrcValueOffset(),
4563                                LLD->isVolatile(), 
4564                                LLD->getAlignment());
4565           else {
4566             Load = DAG.getExtLoad(LLD->getExtensionType(),
4567                                   TheSelect->getValueType(0),
4568                                   LLD->getChain(), Addr, LLD->getSrcValue(),
4569                                   LLD->getSrcValueOffset(),
4570                                   LLD->getLoadedVT(),
4571                                   LLD->isVolatile(), 
4572                                   LLD->getAlignment());
4573           }
4574           // Users of the select now use the result of the load.
4575           CombineTo(TheSelect, Load);
4576         
4577           // Users of the old loads now use the new load's chain.  We know the
4578           // old-load value is dead now.
4579           CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
4580           CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
4581           return true;
4582         }
4583       }
4584     }
4585   }
4586   
4587   return false;
4588 }
4589
4590 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1, 
4591                                         SDOperand N2, SDOperand N3,
4592                                         ISD::CondCode CC, bool NotExtCompare) {
4593   
4594   MVT::ValueType VT = N2.getValueType();
4595   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
4596   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
4597   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
4598
4599   // Determine if the condition we're dealing with is constant
4600   SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
4601   if (SCC.Val) AddToWorkList(SCC.Val);
4602   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
4603
4604   // fold select_cc true, x, y -> x
4605   if (SCCC && SCCC->getValue())
4606     return N2;
4607   // fold select_cc false, x, y -> y
4608   if (SCCC && SCCC->getValue() == 0)
4609     return N3;
4610   
4611   // Check to see if we can simplify the select into an fabs node
4612   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
4613     // Allow either -0.0 or 0.0
4614     if (CFP->getValueAPF().isZero()) {
4615       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
4616       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
4617           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
4618           N2 == N3.getOperand(0))
4619         return DAG.getNode(ISD::FABS, VT, N0);
4620       
4621       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
4622       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
4623           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
4624           N2.getOperand(0) == N3)
4625         return DAG.getNode(ISD::FABS, VT, N3);
4626     }
4627   }
4628   
4629   // Check to see if we can perform the "gzip trick", transforming
4630   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
4631   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
4632       MVT::isInteger(N0.getValueType()) && 
4633       MVT::isInteger(N2.getValueType()) && 
4634       (N1C->isNullValue() ||                    // (a < 0) ? b : 0
4635        (N1C->getValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
4636     MVT::ValueType XType = N0.getValueType();
4637     MVT::ValueType AType = N2.getValueType();
4638     if (XType >= AType) {
4639       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
4640       // single-bit constant.
4641       if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
4642         unsigned ShCtV = Log2_64(N2C->getValue());
4643         ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
4644         SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
4645         SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
4646         AddToWorkList(Shift.Val);
4647         if (XType > AType) {
4648           Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
4649           AddToWorkList(Shift.Val);
4650         }
4651         return DAG.getNode(ISD::AND, AType, Shift, N2);
4652       }
4653       SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
4654                                     DAG.getConstant(MVT::getSizeInBits(XType)-1,
4655                                                     TLI.getShiftAmountTy()));
4656       AddToWorkList(Shift.Val);
4657       if (XType > AType) {
4658         Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
4659         AddToWorkList(Shift.Val);
4660       }
4661       return DAG.getNode(ISD::AND, AType, Shift, N2);
4662     }
4663   }
4664   
4665   // fold select C, 16, 0 -> shl C, 4
4666   if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
4667       TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
4668     
4669     // If the caller doesn't want us to simplify this into a zext of a compare,
4670     // don't do it.
4671     if (NotExtCompare && N2C->getValue() == 1)
4672       return SDOperand();
4673     
4674     // Get a SetCC of the condition
4675     // FIXME: Should probably make sure that setcc is legal if we ever have a
4676     // target where it isn't.
4677     SDOperand Temp, SCC;
4678     // cast from setcc result type to select result type
4679     if (AfterLegalize) {
4680       SCC  = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
4681       if (N2.getValueType() < SCC.getValueType())
4682         Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
4683       else
4684         Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
4685     } else {
4686       SCC  = DAG.getSetCC(MVT::i1, N0, N1, CC);
4687       Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
4688     }
4689     AddToWorkList(SCC.Val);
4690     AddToWorkList(Temp.Val);
4691     
4692     if (N2C->getValue() == 1)
4693       return Temp;
4694     // shl setcc result by log2 n2c
4695     return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
4696                        DAG.getConstant(Log2_64(N2C->getValue()),
4697                                        TLI.getShiftAmountTy()));
4698   }
4699     
4700   // Check to see if this is the equivalent of setcc
4701   // FIXME: Turn all of these into setcc if setcc if setcc is legal
4702   // otherwise, go ahead with the folds.
4703   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
4704     MVT::ValueType XType = N0.getValueType();
4705     if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
4706       SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
4707       if (Res.getValueType() != VT)
4708         Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
4709       return Res;
4710     }
4711     
4712     // seteq X, 0 -> srl (ctlz X, log2(size(X)))
4713     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 
4714         TLI.isOperationLegal(ISD::CTLZ, XType)) {
4715       SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
4716       return DAG.getNode(ISD::SRL, XType, Ctlz, 
4717                          DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
4718                                          TLI.getShiftAmountTy()));
4719     }
4720     // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
4721     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 
4722       SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
4723                                     N0);
4724       SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0, 
4725                                     DAG.getConstant(~0ULL, XType));
4726       return DAG.getNode(ISD::SRL, XType, 
4727                          DAG.getNode(ISD::AND, XType, NegN0, NotN0),
4728                          DAG.getConstant(MVT::getSizeInBits(XType)-1,
4729                                          TLI.getShiftAmountTy()));
4730     }
4731     // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
4732     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
4733       SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
4734                                    DAG.getConstant(MVT::getSizeInBits(XType)-1,
4735                                                    TLI.getShiftAmountTy()));
4736       return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
4737     }
4738   }
4739   
4740   // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
4741   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4742   if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
4743       N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
4744       N2.getOperand(0) == N1 && MVT::isInteger(N0.getValueType())) {
4745     MVT::ValueType XType = N0.getValueType();
4746     SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
4747                                   DAG.getConstant(MVT::getSizeInBits(XType)-1,
4748                                                   TLI.getShiftAmountTy()));
4749     SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
4750     AddToWorkList(Shift.Val);
4751     AddToWorkList(Add.Val);
4752     return DAG.getNode(ISD::XOR, XType, Add, Shift);
4753   }
4754   // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
4755   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4756   if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
4757       N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
4758     if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
4759       MVT::ValueType XType = N0.getValueType();
4760       if (SubC->isNullValue() && MVT::isInteger(XType)) {
4761         SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
4762                                     DAG.getConstant(MVT::getSizeInBits(XType)-1,
4763                                                       TLI.getShiftAmountTy()));
4764         SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
4765         AddToWorkList(Shift.Val);
4766         AddToWorkList(Add.Val);
4767         return DAG.getNode(ISD::XOR, XType, Add, Shift);
4768       }
4769     }
4770   }
4771   
4772   return SDOperand();
4773 }
4774
4775 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
4776 SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
4777                                      SDOperand N1, ISD::CondCode Cond,
4778                                      bool foldBooleans) {
4779   TargetLowering::DAGCombinerInfo 
4780     DagCombineInfo(DAG, !AfterLegalize, false, this);
4781   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
4782 }
4783
4784 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
4785 /// return a DAG expression to select that will generate the same value by
4786 /// multiplying by a magic number.  See:
4787 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4788 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
4789   std::vector<SDNode*> Built;
4790   SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
4791
4792   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4793        ii != ee; ++ii)
4794     AddToWorkList(*ii);
4795   return S;
4796 }
4797
4798 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
4799 /// return a DAG expression to select that will generate the same value by
4800 /// multiplying by a magic number.  See:
4801 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4802 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
4803   std::vector<SDNode*> Built;
4804   SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
4805
4806   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4807        ii != ee; ++ii)
4808     AddToWorkList(*ii);
4809   return S;
4810 }
4811
4812 /// FindBaseOffset - Return true if base is known not to alias with anything
4813 /// but itself.  Provides base object and offset as results.
4814 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
4815   // Assume it is a primitive operation.
4816   Base = Ptr; Offset = 0;
4817   
4818   // If it's an adding a simple constant then integrate the offset.
4819   if (Base.getOpcode() == ISD::ADD) {
4820     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
4821       Base = Base.getOperand(0);
4822       Offset += C->getValue();
4823     }
4824   }
4825   
4826   // If it's any of the following then it can't alias with anything but itself.
4827   return isa<FrameIndexSDNode>(Base) ||
4828          isa<ConstantPoolSDNode>(Base) ||
4829          isa<GlobalAddressSDNode>(Base);
4830 }
4831
4832 /// isAlias - Return true if there is any possibility that the two addresses
4833 /// overlap.
4834 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
4835                           const Value *SrcValue1, int SrcValueOffset1,
4836                           SDOperand Ptr2, int64_t Size2,
4837                           const Value *SrcValue2, int SrcValueOffset2)
4838 {
4839   // If they are the same then they must be aliases.
4840   if (Ptr1 == Ptr2) return true;
4841   
4842   // Gather base node and offset information.
4843   SDOperand Base1, Base2;
4844   int64_t Offset1, Offset2;
4845   bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
4846   bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
4847   
4848   // If they have a same base address then...
4849   if (Base1 == Base2) {
4850     // Check to see if the addresses overlap.
4851     return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
4852   }
4853   
4854   // If we know both bases then they can't alias.
4855   if (KnownBase1 && KnownBase2) return false;
4856
4857   if (CombinerGlobalAA) {
4858     // Use alias analysis information.
4859     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
4860     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
4861     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
4862     AliasAnalysis::AliasResult AAResult = 
4863                              AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
4864     if (AAResult == AliasAnalysis::NoAlias)
4865       return false;
4866   }
4867
4868   // Otherwise we have to assume they alias.
4869   return true;
4870 }
4871
4872 /// FindAliasInfo - Extracts the relevant alias information from the memory
4873 /// node.  Returns true if the operand was a load.
4874 bool DAGCombiner::FindAliasInfo(SDNode *N,
4875                         SDOperand &Ptr, int64_t &Size,
4876                         const Value *&SrcValue, int &SrcValueOffset) {
4877   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4878     Ptr = LD->getBasePtr();
4879     Size = MVT::getSizeInBits(LD->getLoadedVT()) >> 3;
4880     SrcValue = LD->getSrcValue();
4881     SrcValueOffset = LD->getSrcValueOffset();
4882     return true;
4883   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4884     Ptr = ST->getBasePtr();
4885     Size = MVT::getSizeInBits(ST->getStoredVT()) >> 3;
4886     SrcValue = ST->getSrcValue();
4887     SrcValueOffset = ST->getSrcValueOffset();
4888   } else {
4889     assert(0 && "FindAliasInfo expected a memory operand");
4890   }
4891   
4892   return false;
4893 }
4894
4895 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
4896 /// looking for aliasing nodes and adding them to the Aliases vector.
4897 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
4898                                    SmallVector<SDOperand, 8> &Aliases) {
4899   SmallVector<SDOperand, 8> Chains;     // List of chains to visit.
4900   std::set<SDNode *> Visited;           // Visited node set.
4901   
4902   // Get alias information for node.
4903   SDOperand Ptr;
4904   int64_t Size;
4905   const Value *SrcValue;
4906   int SrcValueOffset;
4907   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
4908
4909   // Starting off.
4910   Chains.push_back(OriginalChain);
4911   
4912   // Look at each chain and determine if it is an alias.  If so, add it to the
4913   // aliases list.  If not, then continue up the chain looking for the next
4914   // candidate.  
4915   while (!Chains.empty()) {
4916     SDOperand Chain = Chains.back();
4917     Chains.pop_back();
4918     
4919      // Don't bother if we've been before.
4920     if (Visited.find(Chain.Val) != Visited.end()) continue;
4921     Visited.insert(Chain.Val);
4922   
4923     switch (Chain.getOpcode()) {
4924     case ISD::EntryToken:
4925       // Entry token is ideal chain operand, but handled in FindBetterChain.
4926       break;
4927       
4928     case ISD::LOAD:
4929     case ISD::STORE: {
4930       // Get alias information for Chain.
4931       SDOperand OpPtr;
4932       int64_t OpSize;
4933       const Value *OpSrcValue;
4934       int OpSrcValueOffset;
4935       bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
4936                                     OpSrcValue, OpSrcValueOffset);
4937       
4938       // If chain is alias then stop here.
4939       if (!(IsLoad && IsOpLoad) &&
4940           isAlias(Ptr, Size, SrcValue, SrcValueOffset,
4941                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
4942         Aliases.push_back(Chain);
4943       } else {
4944         // Look further up the chain.
4945         Chains.push_back(Chain.getOperand(0));      
4946         // Clean up old chain.
4947         AddToWorkList(Chain.Val);
4948       }
4949       break;
4950     }
4951     
4952     case ISD::TokenFactor:
4953       // We have to check each of the operands of the token factor, so we queue
4954       // then up.  Adding the  operands to the queue (stack) in reverse order
4955       // maintains the original order and increases the likelihood that getNode
4956       // will find a matching token factor (CSE.)
4957       for (unsigned n = Chain.getNumOperands(); n;)
4958         Chains.push_back(Chain.getOperand(--n));
4959       // Eliminate the token factor if we can.
4960       AddToWorkList(Chain.Val);
4961       break;
4962       
4963     default:
4964       // For all other instructions we will just have to take what we can get.
4965       Aliases.push_back(Chain);
4966       break;
4967     }
4968   }
4969 }
4970
4971 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
4972 /// for a better chain (aliasing node.)
4973 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
4974   SmallVector<SDOperand, 8> Aliases;  // Ops for replacing token factor.
4975   
4976   // Accumulate all the aliases to this node.
4977   GatherAllAliases(N, OldChain, Aliases);
4978   
4979   if (Aliases.size() == 0) {
4980     // If no operands then chain to entry token.
4981     return DAG.getEntryNode();
4982   } else if (Aliases.size() == 1) {
4983     // If a single operand then chain to it.  We don't need to revisit it.
4984     return Aliases[0];
4985   }
4986
4987   // Construct a custom tailored token factor.
4988   SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4989                                    &Aliases[0], Aliases.size());
4990
4991   // Make sure the old chain gets cleaned up.
4992   if (NewChain != OldChain) AddToWorkList(OldChain.Val);
4993   
4994   return NewChain;
4995 }
4996
4997 // SelectionDAG::Combine - This is the entry point for the file.
4998 //
4999 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5000   if (!RunningAfterLegalize && ViewDAGCombine1)
5001     viewGraph();
5002   if (RunningAfterLegalize && ViewDAGCombine2)
5003     viewGraph();
5004   /// run - This is the main entry point to this class.
5005   ///
5006   DAGCombiner(*this, AA).Run(RunningAfterLegalize);
5007 }