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