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